lambder 8.1.2 → 9.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.
Files changed (86) hide show
  1. package/CHANGELOG.md +208 -0
  2. package/README.md +23 -31
  3. package/dist/api/LambderApiCallContext.d.ts +31 -1
  4. package/dist/api/LambderApiCallContext.js +8 -0
  5. package/dist/api/LambderApiDefinition.d.ts +2 -2
  6. package/dist/api/LambderApiEnvelope.d.ts +1 -1
  7. package/dist/api/LambderApiEnvelope.js +3 -4
  8. package/dist/api/LambderApiGuards.d.ts +2 -17
  9. package/dist/api/LambderApiIdempotency.js +5 -7
  10. package/dist/api/LambderApiRateLimits.d.ts +2 -29
  11. package/dist/build/generatedTables.d.ts +72 -0
  12. package/dist/build/generatedTables.js +99 -0
  13. package/dist/build/writeApiGuardParams.d.ts +60 -0
  14. package/dist/build/writeApiGuardParams.js +85 -0
  15. package/dist/build/writeApiOptions.d.ts +68 -0
  16. package/dist/build/writeApiOptions.js +102 -0
  17. package/dist/build.d.ts +10 -4
  18. package/dist/build.js +7 -4
  19. package/dist/client/LambderCaller.d.ts +0 -4
  20. package/dist/client/LambderCaller.js +1 -9
  21. package/dist/client/LambderUploadRunner.d.ts +7 -7
  22. package/dist/client/LambderUploadRunner.js +12 -21
  23. package/dist/client.d.ts +7 -0
  24. package/dist/client.js +11 -0
  25. package/dist/core/Lambder.d.ts +71 -12
  26. package/dist/core/Lambder.js +116 -38
  27. package/dist/core/LambderContext.d.ts +9 -6
  28. package/dist/core/LambderContext.js +2 -1
  29. package/dist/core/LambderResolver.d.ts +6 -12
  30. package/dist/core/LambderResolver.js +2 -14
  31. package/dist/core/LambderResponseBuilder.d.ts +15 -70
  32. package/dist/core/LambderResponseBuilder.js +15 -99
  33. package/dist/index.d.ts +16 -3
  34. package/dist/index.js +14 -1
  35. package/dist/invoke/LambderInvokeCaller.js +3 -4
  36. package/dist/mock/LambderMockApp.d.ts +34 -17
  37. package/dist/mock/LambderMockApp.js +69 -24
  38. package/dist/mock/LambderMockCreateOptions.d.ts +70 -7
  39. package/dist/mock/LambderMockTypes.d.ts +31 -21
  40. package/dist/mock/lambderMockPoliciesFrom.d.ts +51 -0
  41. package/dist/mock/lambderMockPoliciesFrom.js +46 -0
  42. package/dist/mock.d.ts +3 -0
  43. package/dist/mock.js +3 -0
  44. package/dist/secrets/LambderOneShotSecrets.d.ts +166 -0
  45. package/dist/secrets/LambderOneShotSecrets.js +217 -0
  46. package/dist/session/LambderSessionCrypto.js +6 -16
  47. package/dist/shared/contracts/LambderIdempotencyStore.d.ts +3 -2
  48. package/dist/shared/contracts/LambderOneShotSecretStore.d.ts +122 -0
  49. package/dist/shared/contracts/LambderOneShotSecretStore.js +38 -0
  50. package/dist/shared/util/LambderBackoffTimer.d.ts +82 -0
  51. package/dist/shared/util/LambderBackoffTimer.js +86 -0
  52. package/dist/shared/util/LambderBase64.d.ts +14 -0
  53. package/dist/shared/util/LambderBase64.js +17 -0
  54. package/dist/shared/util/LambderSignedClaims.d.ts +78 -0
  55. package/dist/shared/util/LambderSignedClaims.js +109 -0
  56. package/dist/shared/util/LambderTextDigest.d.ts +19 -5
  57. package/dist/shared/util/LambderTextDigest.js +30 -5
  58. package/dist/shared/util/LambderTypeUtilities.d.ts +18 -0
  59. package/dist/shared/util/assertPlainData.d.ts +9 -0
  60. package/dist/shared/util/assertPlainData.js +41 -0
  61. package/dist/shared/wire/LambderAnswerHeaders.d.ts +3 -2
  62. package/dist/shared/wire/LambderAnswerHeaders.js +3 -2
  63. package/dist/shared/wire/LambderApiContract.d.ts +9 -14
  64. package/dist/shared/wire/LambderApiOptionEntries.d.ts +148 -0
  65. package/dist/shared/wire/LambderApiOptionEntries.js +35 -0
  66. package/dist/shared/wire/LambderApiRefusal.d.ts +3 -4
  67. package/dist/shared/wire/LambderApiRefusal.js +3 -4
  68. package/dist/stores/LambderDdbOneShotSecretStore.d.ts +64 -0
  69. package/dist/stores/LambderDdbOneShotSecretStore.js +266 -0
  70. package/dist/stores/LambderMemoryIdempotencyStore.d.ts +3 -2
  71. package/dist/stores/LambderMemoryIdempotencyStore.js +3 -2
  72. package/dist/stores/LambderMemoryOneShotSecretStore.d.ts +36 -0
  73. package/dist/stores/LambderMemoryOneShotSecretStore.js +93 -0
  74. package/dist/testing/LambderConformanceRunner.d.ts +46 -0
  75. package/dist/testing/LambderConformanceRunner.js +21 -0
  76. package/dist/testing/lambderIdempotencyStoreConformance.d.ts +33 -0
  77. package/dist/testing/lambderIdempotencyStoreConformance.js +237 -0
  78. package/dist/testing/lambderOneShotSecretStoreConformance.d.ts +43 -0
  79. package/dist/testing/lambderOneShotSecretStoreConformance.js +224 -0
  80. package/dist/testing/lambderRateLimiterConformance.d.ts +20 -0
  81. package/dist/testing/lambderRateLimiterConformance.js +72 -0
  82. package/dist/testing/lambderSessionStoreConformance.d.ts +27 -0
  83. package/dist/testing/lambderSessionStoreConformance.js +165 -0
  84. package/dist/testing.d.ts +14 -0
  85. package/dist/testing.js +12 -0
  86. package/package.json +1 -1
@@ -0,0 +1,82 @@
1
+ /**
2
+ * One pending wait at a time, where each retry after a failure waits longer
3
+ * than the one before it.
4
+ *
5
+ * Most things that retry also wait for other reasons (a refresh cadence, a
6
+ * pause before recreating something), and those waits must never stack with a
7
+ * retry. So the timer holds exactly one wait of either kind: `retry` and
8
+ * `wait` climb the ladder, `after` waits a fixed time without climbing it, and
9
+ * scheduling any of them replaces whatever was waiting. A caller says what to
10
+ * run and when it worked, and never keeps a handle and a counter of its own.
11
+ *
12
+ * The ladder: a retry waits the base plus a share of a ceiling that grows by
13
+ * `factor` with every failed attempt, the whole never past `maxMs`. With full
14
+ * jitter (the default) the share is random, so anything many clients fail at
15
+ * together (a deploy dropping every socket, a power cut bringing every screen
16
+ * in a building up at once) is retried across the whole window instead of in
17
+ * step, which is what keeps the herd off the server.
18
+ *
19
+ * Runs wherever setTimeout does: a browser, a Worker, Node. The upload runner
20
+ * waits on one between tries at storage, and an app's reconnecting client or
21
+ * self-healing screen holds one of its own.
22
+ */
23
+ export type LambderBackoffTimerOptions = {
24
+ /**
25
+ * The shortest retry wait, in milliseconds. The first after a reset falls
26
+ * between it and twice it (exactly twice with `jitter: "none"`), so even
27
+ * the first retries of many clients spread out. Default: 1000.
28
+ */
29
+ baseMs?: number;
30
+ /**
31
+ * The longest any retry wait is, in milliseconds, however many attempts
32
+ * have failed; at least `baseMs`. Default: 60000, or `baseMs` when that is
33
+ * longer.
34
+ */
35
+ maxMs?: number;
36
+ /** How much the ceiling grows with each failed attempt. Default: 2. */
37
+ factor?: number;
38
+ /**
39
+ * "full" (the default): the base plus a random share of the ceiling, which
40
+ * spreads a herd out. "none": the base plus the whole ceiling, a
41
+ * predictable ladder for a caller that is alone.
42
+ */
43
+ jitter?: "full" | "none";
44
+ };
45
+ export declare class LambderBackoffTimer {
46
+ private readonly baseMs;
47
+ private readonly maxMs;
48
+ private readonly factor;
49
+ private readonly jitter;
50
+ private attempts;
51
+ private timer;
52
+ /** Settles the promise of a `wait` that cancel() or a replacement drops, so no `await` is left hanging. */
53
+ private dropPending;
54
+ constructor(options?: LambderBackoffTimerOptions);
55
+ /** True while a wait of any kind is pending. False again by the time it runs. */
56
+ get pending(): boolean;
57
+ /**
58
+ * Runs `run` after the next rung of the ladder, counting one more failed
59
+ * attempt. Replaces whatever was waiting.
60
+ */
61
+ retry(run: () => void): void;
62
+ /**
63
+ * Resolves after the next rung of the ladder, counting one more failed
64
+ * attempt: the `retry` for code that awaits rather than calls back.
65
+ * Replaces whatever was waiting. Rejects at once with the signal's reason
66
+ * when `signal` aborts, and with an Error when cancel() or a later wait
67
+ * drops it before it ran, so an await on it always settles.
68
+ */
69
+ wait(signal?: AbortSignal): Promise<void>;
70
+ /**
71
+ * Runs `run` after a fixed wait, off the ladder: nothing failed, so nothing
72
+ * climbs. Replaces whatever was waiting.
73
+ */
74
+ after(delayMs: number, run: () => void): void;
75
+ /** The attempt worked: the next failure waits the shortest time again. A pending wait is left alone. */
76
+ reset(): void;
77
+ /** Drops the pending wait (the caller is trying right now, or going away), keeping the count. */
78
+ cancel(): void;
79
+ /** The next wait on the ladder, in milliseconds, counting one more failed attempt. */
80
+ private nextRung;
81
+ private schedule;
82
+ }
@@ -0,0 +1,86 @@
1
+ import { assertNumberAtLeast } from "./LambderOptionChecks.js";
2
+ export class LambderBackoffTimer {
3
+ baseMs;
4
+ maxMs;
5
+ factor;
6
+ jitter;
7
+ attempts = 0;
8
+ timer = null;
9
+ /** Settles the promise of a `wait` that cancel() or a replacement drops, so no `await` is left hanging. */
10
+ dropPending = null;
11
+ constructor(options = {}) {
12
+ this.baseMs = assertNumberAtLeast(options.baseMs ?? 1_000, 0, "baseMs");
13
+ this.maxMs = assertNumberAtLeast(options.maxMs ?? Math.max(60_000, this.baseMs), this.baseMs, "maxMs");
14
+ this.factor = assertNumberAtLeast(options.factor ?? 2, 1, "factor");
15
+ this.jitter = options.jitter ?? "full";
16
+ }
17
+ /** True while a wait of any kind is pending. False again by the time it runs. */
18
+ get pending() {
19
+ return this.timer !== null;
20
+ }
21
+ /**
22
+ * Runs `run` after the next rung of the ladder, counting one more failed
23
+ * attempt. Replaces whatever was waiting.
24
+ */
25
+ retry(run) {
26
+ this.schedule(this.nextRung(), run, null);
27
+ }
28
+ /**
29
+ * Resolves after the next rung of the ladder, counting one more failed
30
+ * attempt: the `retry` for code that awaits rather than calls back.
31
+ * Replaces whatever was waiting. Rejects at once with the signal's reason
32
+ * when `signal` aborts, and with an Error when cancel() or a later wait
33
+ * drops it before it ran, so an await on it always settles.
34
+ */
35
+ wait(signal) {
36
+ return new Promise((resolve, reject) => {
37
+ if (signal?.aborted)
38
+ return reject(abortReasonOf(signal));
39
+ const onAbort = () => this.cancel();
40
+ const settle = (outcome) => {
41
+ signal?.removeEventListener("abort", onAbort);
42
+ outcome();
43
+ };
44
+ this.schedule(this.nextRung(), () => settle(resolve), () => settle(() => reject(signal?.aborted ? abortReasonOf(signal) : new Error("LambderBackoffTimer: the wait was dropped by cancel() or by a later wait before it ran."))));
45
+ signal?.addEventListener("abort", onAbort, { once: true });
46
+ });
47
+ }
48
+ /**
49
+ * Runs `run` after a fixed wait, off the ladder: nothing failed, so nothing
50
+ * climbs. Replaces whatever was waiting.
51
+ */
52
+ after(delayMs, run) {
53
+ this.schedule(delayMs, run, null);
54
+ }
55
+ /** The attempt worked: the next failure waits the shortest time again. A pending wait is left alone. */
56
+ reset() {
57
+ this.attempts = 0;
58
+ }
59
+ /** Drops the pending wait (the caller is trying right now, or going away), keeping the count. */
60
+ cancel() {
61
+ if (this.timer === null)
62
+ return;
63
+ clearTimeout(this.timer);
64
+ this.timer = null;
65
+ const drop = this.dropPending;
66
+ this.dropPending = null;
67
+ drop?.();
68
+ }
69
+ /** The next wait on the ladder, in milliseconds, counting one more failed attempt. */
70
+ nextRung() {
71
+ const ceiling = Math.min(this.baseMs * this.factor ** this.attempts, this.maxMs - this.baseMs);
72
+ this.attempts += 1;
73
+ return this.baseMs + (this.jitter === "full" ? Math.random() : 1) * ceiling;
74
+ }
75
+ schedule(delayMs, run, drop) {
76
+ this.cancel();
77
+ this.dropPending = drop;
78
+ this.timer = setTimeout(() => {
79
+ this.timer = null;
80
+ this.dropPending = null;
81
+ run();
82
+ }, delayMs);
83
+ }
84
+ }
85
+ /** What an aborted signal carries, or an Error for a runtime whose signals carry nothing. */
86
+ const abortReasonOf = (signal) => signal.reason ?? new Error("LambderBackoffTimer: the wait was aborted.");
@@ -8,3 +8,17 @@ export declare const bytesToBase64: (bytes: Uint8Array) => string;
8
8
  export declare const base64ToBytes: (base64: string) => Uint8Array;
9
9
  /** The base64 of UTF-8 text back to the text. */
10
10
  export declare const base64ToText: (base64: string) => string;
11
+ /**
12
+ * The base64url alphabet (RFC 4648 section 5) without padding: what a token
13
+ * or a digest carries where "+", "/" and "=" would need escaping, in a URL, a
14
+ * header or a database column.
15
+ */
16
+ export declare const bytesToBase64Url: (bytes: Uint8Array) => string;
17
+ /**
18
+ * Whether `text` is base64url and nothing else, so decoding it decodes rather
19
+ * than guesses; Buffer decodes anything. A length that leaves a remainder of
20
+ * one past a multiple of four is no encoding of any bytes, and the platform's
21
+ * atob throws on it where Buffer shrugs, so it is refused here on both.
22
+ */
23
+ export declare const isBase64Url: (text: string) => boolean;
24
+ export declare const base64UrlToBytes: (base64Url: string) => Uint8Array;
@@ -25,3 +25,20 @@ export const base64ToBytes = (base64) => {
25
25
  };
26
26
  /** The base64 of UTF-8 text back to the text. */
27
27
  export const base64ToText = (base64) => new TextDecoder().decode(base64ToBytes(base64));
28
+ /**
29
+ * The base64url alphabet (RFC 4648 section 5) without padding: what a token
30
+ * or a digest carries where "+", "/" and "=" would need escaping, in a URL, a
31
+ * header or a database column.
32
+ */
33
+ export const bytesToBase64Url = (bytes) => bytesToBase64(bytes).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
34
+ /**
35
+ * Whether `text` is base64url and nothing else, so decoding it decodes rather
36
+ * than guesses; Buffer decodes anything. A length that leaves a remainder of
37
+ * one past a multiple of four is no encoding of any bytes, and the platform's
38
+ * atob throws on it where Buffer shrugs, so it is refused here on both.
39
+ */
40
+ export const isBase64Url = (text) => text.length % 4 !== 1 && /^[A-Za-z0-9_-]*$/.test(text);
41
+ export const base64UrlToBytes = (base64Url) => {
42
+ const base64 = base64Url.replace(/-/g, "+").replace(/_/g, "/");
43
+ return base64ToBytes(base64.padEnd(base64.length + (4 - base64.length % 4) % 4, "="));
44
+ };
@@ -0,0 +1,78 @@
1
+ import type { z } from "zod";
2
+ export type LambderSignedClaimsOptions<TClaims> = {
3
+ /** The HMAC key. Server side, and every runtime that verifies; never a browser. */
4
+ secret: string;
5
+ /**
6
+ * Names this kind of token, as the first segment of every one it signs;
7
+ * a token of another version does not verify. Any text without a dot.
8
+ */
9
+ version: string;
10
+ /** The claims' shape, parsed on the way out and on the way back, so a token never carries a shape the app did not declare. */
11
+ schema: z.ZodType<TClaims>;
12
+ /** The clock `exp` is judged against, in epoch milliseconds. Default: Date.now. */
13
+ now?: () => number;
14
+ };
15
+ /**
16
+ * Refuses a claims type whose `exp` is not a number, at the constructor: the
17
+ * class would judge it as an expiry, find no number, and let the token live
18
+ * for ever. The property name is the message.
19
+ */
20
+ type LambderExpIsSeconds<TClaims> = TClaims extends {
21
+ exp: infer E;
22
+ } ? ([E] extends [number] ? unknown : {
23
+ readonly "lambder: the exp claim is an expiry in epoch seconds, so the schema must declare it as a number.": never;
24
+ }) : unknown;
25
+ /**
26
+ * One kind of signed token: constructed once with its secret, version and
27
+ * claims schema, it keeps the imported HMAC key and answers `sign` and
28
+ * `verify`. An app declares one instance per kind of token it hands out.
29
+ *
30
+ * The one claim with a meaning here is `exp`, an expiry in epoch seconds,
31
+ * the unit sessions, DynamoDB's TTL and JWTs use. A schema that declares it
32
+ * gets it checked on every verify; a schema without it declares a token that
33
+ * does not expire on its own, which is right where the thing the token names
34
+ * (a request, a message) decides what it may still do.
35
+ *
36
+ * `verify` answers null for every failure alike: a forged signature, another
37
+ * version, malformed text, claims the schema refuses, an `exp` in the past.
38
+ * A caller cannot tell them apart, and so cannot tell a client apart either.
39
+ */
40
+ export declare class LambderSignedClaims<TClaims extends object> {
41
+ private readonly secret;
42
+ private readonly version;
43
+ private readonly schema;
44
+ private readonly now;
45
+ /** Imported on first use and kept: signing and verifying share one key object for the life of the instance. */
46
+ private keyPromise;
47
+ constructor(options: LambderSignedClaimsOptions<TClaims> & LambderExpIsSeconds<TClaims>);
48
+ /** The token for these claims, which the schema parses first. `exp`, when the schema has it, is epoch seconds. */
49
+ sign(claims: TClaims): Promise<string>;
50
+ /**
51
+ * The claims, when the token is this version, signed under this secret,
52
+ * well formed, accepted by the schema and not past its `exp`; null
53
+ * otherwise, for every reason alike. `now`, in epoch milliseconds, is the
54
+ * moment `exp` is judged against for this call; default: the clock's.
55
+ */
56
+ verify(token: string, options?: {
57
+ now?: number;
58
+ }): Promise<TClaims | null>;
59
+ private key;
60
+ }
61
+ /**
62
+ * The keyed digest of a secret an app stores and later looks up or compares
63
+ * by value: a device's secret, a code sent by email, a pairing code. Keyed
64
+ * under the app's secret rather than a plain hash, so a copied table alone
65
+ * cannot be attacked offline, and deterministic, so a lookup is one indexed
66
+ * read. HMAC-SHA256 as 43 characters of base64url; compare two with
67
+ * constantTimeEquals.
68
+ */
69
+ export declare const keyedDigest: (secret: string, value: string) => Promise<string>;
70
+ /**
71
+ * A fresh secret from the runtime's cryptographic random source, as base64url
72
+ * (43 characters for the default 32 bytes): the credential a paired device
73
+ * keeps, the token in a link that must not be guessable. Synchronous, since
74
+ * getRandomValues is, on every runtime with a WebCrypto global; a runtime
75
+ * without one is told so.
76
+ */
77
+ export declare const randomSecret: (bytes?: number) => string;
78
+ export {};
@@ -0,0 +1,109 @@
1
+ import { base64UrlToBytes, bytesToBase64Url, isBase64Url } from "./LambderBase64.js";
2
+ import { hmacSha256Of, importHmacKey, resolveWebCrypto } from "./LambderTextDigest.js";
3
+ /**
4
+ * One kind of signed token: constructed once with its secret, version and
5
+ * claims schema, it keeps the imported HMAC key and answers `sign` and
6
+ * `verify`. An app declares one instance per kind of token it hands out.
7
+ *
8
+ * The one claim with a meaning here is `exp`, an expiry in epoch seconds,
9
+ * the unit sessions, DynamoDB's TTL and JWTs use. A schema that declares it
10
+ * gets it checked on every verify; a schema without it declares a token that
11
+ * does not expire on its own, which is right where the thing the token names
12
+ * (a request, a message) decides what it may still do.
13
+ *
14
+ * `verify` answers null for every failure alike: a forged signature, another
15
+ * version, malformed text, claims the schema refuses, an `exp` in the past.
16
+ * A caller cannot tell them apart, and so cannot tell a client apart either.
17
+ */
18
+ export class LambderSignedClaims {
19
+ secret;
20
+ version;
21
+ schema;
22
+ now;
23
+ /** Imported on first use and kept: signing and verifying share one key object for the life of the instance. */
24
+ keyPromise;
25
+ constructor(options) {
26
+ if (typeof options.secret !== "string" || options.secret.length === 0) {
27
+ throw new Error("Lambder: LambderSignedClaims needs a secret to sign with.");
28
+ }
29
+ if (typeof options.version !== "string" || options.version.length === 0 || options.version.includes(".")) {
30
+ throw new Error(`Lambder: LambderSignedClaims version must be text without a dot, got ${JSON.stringify(options.version)}: it is the first of the token's three dot-separated segments.`);
31
+ }
32
+ this.secret = options.secret;
33
+ this.version = options.version;
34
+ this.schema = options.schema;
35
+ this.now = options.now ?? (() => Date.now());
36
+ }
37
+ /** The token for these claims, which the schema parses first. `exp`, when the schema has it, is epoch seconds. */
38
+ async sign(claims) {
39
+ const body = bytesToBase64Url(new TextEncoder().encode(JSON.stringify(this.schema.parse(claims))));
40
+ const message = `${this.version}.${body}`;
41
+ const webCrypto = await resolveWebCrypto();
42
+ const mac = await webCrypto.subtle.sign("HMAC", await this.key(webCrypto), new TextEncoder().encode(message));
43
+ return `${message}.${bytesToBase64Url(new Uint8Array(mac))}`;
44
+ }
45
+ /**
46
+ * The claims, when the token is this version, signed under this secret,
47
+ * well formed, accepted by the schema and not past its `exp`; null
48
+ * otherwise, for every reason alike. `now`, in epoch milliseconds, is the
49
+ * moment `exp` is judged against for this call; default: the clock's.
50
+ */
51
+ async verify(token, options = {}) {
52
+ const parts = token.split(".");
53
+ if (parts.length !== 3 || parts[0] !== this.version)
54
+ return null;
55
+ const [, body, mac] = parts;
56
+ if (!isBase64Url(body) || !isBase64Url(mac))
57
+ return null;
58
+ // The last character of a MAC carries bits decoding ignores, so four
59
+ // spellings decode to the same bytes. Only the one sign() writes is a
60
+ // token: an app that keys anything on the token string (a list of
61
+ // spent tokens, a rate limit) must not meet the same token again
62
+ // under another spelling.
63
+ const macBytes = base64UrlToBytes(mac);
64
+ if (bytesToBase64Url(macBytes) !== mac)
65
+ return null;
66
+ const webCrypto = await resolveWebCrypto();
67
+ const valid = await webCrypto.subtle.verify("HMAC", await this.key(webCrypto), macBytes, new TextEncoder().encode(`${this.version}.${body}`));
68
+ if (!valid)
69
+ return null;
70
+ let claims;
71
+ try {
72
+ claims = this.schema.parse(JSON.parse(new TextDecoder().decode(base64UrlToBytes(body))));
73
+ }
74
+ catch {
75
+ return null;
76
+ }
77
+ const exp = claims.exp;
78
+ if (typeof exp === "number" && exp * 1000 <= (options.now ?? this.now()))
79
+ return null;
80
+ return claims;
81
+ }
82
+ key(webCrypto) {
83
+ this.keyPromise ??= importHmacKey(webCrypto, this.secret, ["sign", "verify"]);
84
+ return this.keyPromise;
85
+ }
86
+ }
87
+ /**
88
+ * The keyed digest of a secret an app stores and later looks up or compares
89
+ * by value: a device's secret, a code sent by email, a pairing code. Keyed
90
+ * under the app's secret rather than a plain hash, so a copied table alone
91
+ * cannot be attacked offline, and deterministic, so a lookup is one indexed
92
+ * read. HMAC-SHA256 as 43 characters of base64url; compare two with
93
+ * constantTimeEquals.
94
+ */
95
+ export const keyedDigest = async (secret, value) => bytesToBase64Url(await hmacSha256Of(secret, value));
96
+ /**
97
+ * A fresh secret from the runtime's cryptographic random source, as base64url
98
+ * (43 characters for the default 32 bytes): the credential a paired device
99
+ * keeps, the token in a link that must not be guessable. Synchronous, since
100
+ * getRandomValues is, on every runtime with a WebCrypto global; a runtime
101
+ * without one is told so.
102
+ */
103
+ export const randomSecret = (bytes = 32) => {
104
+ const webCrypto = globalThis.crypto;
105
+ if (typeof webCrypto?.getRandomValues !== "function") {
106
+ throw new Error("Lambder needs crypto.getRandomValues in this runtime to mint a secret. Every browser provides it; Node 20+ provides it as globalThis.crypto.");
107
+ }
108
+ return bytesToBase64Url(webCrypto.getRandomValues(new Uint8Array(bytes)));
109
+ };
@@ -1,9 +1,11 @@
1
1
  /**
2
- * SHA-256 through WebCrypto: the one digest every layer shares. The session
3
- * crypto hashes bearer secrets with it and the rate-limit engine folds an
4
- * over-long tracker key with it, so both key spaces are built from the same
5
- * primitive on every runtime (browsers on a secure context, Node 20+, edge
6
- * runtimes); an upload's checksum is the same digest over the file's bytes.
2
+ * SHA-256 and HMAC-SHA256 through WebCrypto: the digests every layer shares.
3
+ * The session crypto hashes bearer secrets with the first and partitions
4
+ * session keys with the second, the rate-limit engine folds an over-long
5
+ * tracker key, signed claims and keyed digests are HMACs under an app's
6
+ * secret, so every key space is built from the same primitives on every
7
+ * runtime (browsers on a secure context, Node 20+, edge runtimes); an
8
+ * upload's checksum is the same digest over the file's bytes.
7
9
  */
8
10
  /** Lowercase hex of a byte array, two characters per byte. */
9
11
  export declare const bytesToHexString: (bytes: Uint8Array) => string;
@@ -17,3 +19,15 @@ export declare const resolveWebCrypto: () => Promise<Crypto>;
17
19
  export declare const sha256HexOf: (text: string) => Promise<string>;
18
20
  /** The SHA-256 digest of `bytes`, as base64: the form object storage checks an upload's checksum in. */
19
21
  export declare const sha256Base64Of: (bytes: Uint8Array) => Promise<string>;
22
+ /** An HMAC-SHA256 key over `secret` (UTF-8), for `usages`; a holder that signs often keeps the key rather than importing it per call. */
23
+ export declare const importHmacKey: (webCrypto: Crypto, secret: string, usages?: KeyUsage[]) => Promise<CryptoKey>;
24
+ /** HMAC-SHA256 of `text` under `secret` (both UTF-8), as bytes. */
25
+ export declare const hmacSha256Of: (secret: string, text: string) => Promise<Uint8Array>;
26
+ /**
27
+ * Length-aware, timing-neutral string comparison: no early exit on the first
28
+ * differing character, so how long it takes says nothing about where two
29
+ * digests part. For comparing a stored digest with the digest of a candidate;
30
+ * a signature is verified by WebCrypto, which compares in constant time
31
+ * itself.
32
+ */
33
+ export declare const constantTimeEquals: (a: string, b: string) => boolean;
@@ -1,11 +1,13 @@
1
1
  import { bytesToBase64 } from "./LambderBase64.js";
2
2
  import { getCrypto } from "./LambderNodeModules.js";
3
3
  /**
4
- * SHA-256 through WebCrypto: the one digest every layer shares. The session
5
- * crypto hashes bearer secrets with it and the rate-limit engine folds an
6
- * over-long tracker key with it, so both key spaces are built from the same
7
- * primitive on every runtime (browsers on a secure context, Node 20+, edge
8
- * runtimes); an upload's checksum is the same digest over the file's bytes.
4
+ * SHA-256 and HMAC-SHA256 through WebCrypto: the digests every layer shares.
5
+ * The session crypto hashes bearer secrets with the first and partitions
6
+ * session keys with the second, the rate-limit engine folds an over-long
7
+ * tracker key, signed claims and keyed digests are HMACs under an app's
8
+ * secret, so every key space is built from the same primitives on every
9
+ * runtime (browsers on a secure context, Node 20+, edge runtimes); an
10
+ * upload's checksum is the same digest over the file's bytes.
9
11
  */
10
12
  /** Lowercase hex of a byte array, two characters per byte. */
11
13
  export const bytesToHexString = (bytes) => Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join("");
@@ -38,3 +40,26 @@ export const sha256Base64Of = async (bytes) => {
38
40
  const webCrypto = await resolveWebCrypto();
39
41
  return bytesToBase64(new Uint8Array(await webCrypto.subtle.digest("SHA-256", bytes)));
40
42
  };
43
+ /** An HMAC-SHA256 key over `secret` (UTF-8), for `usages`; a holder that signs often keeps the key rather than importing it per call. */
44
+ export const importHmacKey = async (webCrypto, secret, usages = ["sign"]) => await webCrypto.subtle.importKey("raw", new TextEncoder().encode(secret), { name: "HMAC", hash: "SHA-256" }, false, usages);
45
+ /** HMAC-SHA256 of `text` under `secret` (both UTF-8), as bytes. */
46
+ export const hmacSha256Of = async (secret, text) => {
47
+ const webCrypto = await resolveWebCrypto();
48
+ const key = await importHmacKey(webCrypto, secret);
49
+ return new Uint8Array(await webCrypto.subtle.sign("HMAC", key, new TextEncoder().encode(text)));
50
+ };
51
+ /**
52
+ * Length-aware, timing-neutral string comparison: no early exit on the first
53
+ * differing character, so how long it takes says nothing about where two
54
+ * digests part. For comparing a stored digest with the digest of a candidate;
55
+ * a signature is verified by WebCrypto, which compares in constant time
56
+ * itself.
57
+ */
58
+ export const constantTimeEquals = (a, b) => {
59
+ if (a.length !== b.length)
60
+ return false;
61
+ let difference = 0;
62
+ for (let i = 0; i < a.length; i += 1)
63
+ difference |= a.charCodeAt(i) ^ b.charCodeAt(i);
64
+ return difference === 0;
65
+ };
@@ -12,6 +12,24 @@
12
12
  * awaits either.
13
13
  */
14
14
  export type MaybePromise<T> = T | Promise<T>;
15
+ /**
16
+ * T with every object and array readonly, all the way down: what an API
17
+ * handler's returned answer is checked against.
18
+ *
19
+ * An answer is a return value, and TypeScript widens the literals of a
20
+ * return value whose expected type is still generic (`{ kind: "a" }` reads
21
+ * as `{ kind: string }`), where a call argument keeps them. The handler's
22
+ * return is therefore its own `const` type parameter, which keeps literals;
23
+ * `const` also makes array literals readonly, which a schema's mutable arrays
24
+ * would refuse, so the bound is this readonly view of the output. Nothing
25
+ * writes to an answer (it is parsed and sent), so readonly costs nothing.
26
+ * Functions and Dates pass through whole. Eight levels deep and no further,
27
+ * because an output may be recursive (`z.json()`), and past that depth the
28
+ * type is left as it is.
29
+ */
30
+ export type LambderReadonlyDeep<T, TDepth extends unknown[] = []> = TDepth["length"] extends 8 ? T : T extends (...args: never[]) => unknown ? T : T extends Date ? T : T extends object ? {
31
+ readonly [K in keyof T]: LambderReadonlyDeep<T[K], [...TDepth, unknown]>;
32
+ } : T;
15
33
  /**
16
34
  * A declaration map with AT LEAST ONE entry: the union, over every declarable
17
35
  * name, of "this one required and the rest optional".
@@ -0,0 +1,9 @@
1
+ /**
2
+ * Whether a value survives JSON unchanged, and so can be written into a
3
+ * generated module as the data it is: strings, finite numbers, booleans,
4
+ * null, and arrays and plain objects of them. Anything else (a function, a
5
+ * class instance such as a zod schema, a symbol, a bigint, NaN, undefined
6
+ * inside a container) is code or a shape JSON would silently rewrite, and
7
+ * the caller is told where it sits.
8
+ */
9
+ export declare const assertPlainData: (value: unknown, subject: string) => void;
@@ -0,0 +1,41 @@
1
+ /**
2
+ * Whether a value survives JSON unchanged, and so can be written into a
3
+ * generated module as the data it is: strings, finite numbers, booleans,
4
+ * null, and arrays and plain objects of them. Anything else (a function, a
5
+ * class instance such as a zod schema, a symbol, a bigint, NaN, undefined
6
+ * inside a container) is code or a shape JSON would silently rewrite, and
7
+ * the caller is told where it sits.
8
+ */
9
+ export const assertPlainData = (value, subject) => {
10
+ const offence = findNonPlain(value, "");
11
+ if (offence === null)
12
+ return;
13
+ throw new Error(`Lambder: ${subject} must be plain data (strings, finite numbers, booleans, null, and arrays and plain objects of them) to be written as a value, but ${offence.path || "it"} is ${offence.kind}.`);
14
+ };
15
+ const findNonPlain = (value, path) => {
16
+ if (value === null || typeof value === "string" || typeof value === "boolean")
17
+ return null;
18
+ if (typeof value === "number")
19
+ return Number.isFinite(value) ? null : { path, kind: String(value) };
20
+ if (Array.isArray(value)) {
21
+ for (let index = 0; index < value.length; index += 1) {
22
+ const offence = findNonPlain(value[index], `${path}[${index}]`);
23
+ if (offence)
24
+ return offence;
25
+ }
26
+ return null;
27
+ }
28
+ if (typeof value === "object") {
29
+ const prototype = Object.getPrototypeOf(value);
30
+ if (prototype !== Object.prototype && prototype !== null) {
31
+ return { path, kind: `an instance of ${value.constructor?.name || "a class"}` };
32
+ }
33
+ for (const [key, member] of Object.entries(value)) {
34
+ const offence = findNonPlain(member, path ? `${path}.${key}` : key);
35
+ if (offence)
36
+ return offence;
37
+ }
38
+ return null;
39
+ }
40
+ return { path, kind: typeof value === "function" ? "a function" : `a ${typeof value}` };
41
+ };
@@ -21,8 +21,9 @@ export type LambderHeaderTarget = {
21
21
  addHeader(key: string, value: string): unknown;
22
22
  };
23
23
  /**
24
- * Response headers written while a call runs (`res.setHeader`, `res.addHeader`,
25
- * the session controller's Set-Cookie), applied onto the answer once the
24
+ * Response headers written while a call runs (`ctx.setResponseHeader`,
25
+ * `ctx.addResponseHeader`, `ctx.setCookie`, the session controller's
26
+ * Set-Cookie), applied onto the answer once the
26
27
  * call has one. Recorded as operations in call order rather than as a map,
27
28
  * so `set` replaces what the answer itself carries (a Content-Type, say) and
28
29
  * `add` appends to it, exactly as if called on the answer directly.
@@ -36,8 +36,9 @@ export const addAnswerHeader = (headers, name, value) => {
36
36
  headers[name] = [value];
37
37
  };
38
38
  /**
39
- * Response headers written while a call runs (`res.setHeader`, `res.addHeader`,
40
- * the session controller's Set-Cookie), applied onto the answer once the
39
+ * Response headers written while a call runs (`ctx.setResponseHeader`,
40
+ * `ctx.addResponseHeader`, `ctx.setCookie`, the session controller's
41
+ * Set-Cookie), applied onto the answer once the
41
42
  * call has one. Recorded as operations in call order rather than as a map,
42
43
  * so `set` replaces what the answer itself carries (a Content-Type, say) and
43
44
  * `add` appends to it, exactly as if called on the answer directly.
@@ -4,7 +4,6 @@
4
4
  * Contracts are built via method chaining and inferred using typeof lambder.ApiContract
5
5
  */
6
6
  import type { LambderCrashDetail } from "./LambderCrashDetail.js";
7
- import type { LambderNonEmptyOptionMap } from "../util/LambderTypeUtilities.js";
8
7
  import type { LambderAppRefusalMessage } from "./LambderApiRefusal.js";
9
8
  import type { LambderApiIdempotencyOption, LambderGuardsOptionValue, LambderRateLimitOptionValue } from "./LambderApiOptionValues.js";
10
9
  /** Whether an endpoint runs without a session or requires one (addApi versus addSessionApi). */
@@ -32,15 +31,18 @@ export type LambderApiContractShape = Record<string, {
32
31
  /** Present when the API declares idempotency: the `idempotency` option exactly as written. */
33
32
  idempotency?: LambderApiIdempotencyOption;
34
33
  }>;
35
- /** Envelope flags/channels the server may set beside (or instead of) the payload. */
34
+ /**
35
+ * Envelope flags and channels beside (or instead of) the payload: what a
36
+ * refusal, the pipeline's own answers, a hook or an error handler set. An API
37
+ * handler sets none of them itself: it returns its output or refuses.
38
+ */
36
39
  export type LambderApiResponseConfig = {
37
40
  versionExpired?: boolean;
38
41
  sessionExpired?: boolean;
39
42
  notAuthorized?: boolean;
40
- message?: any;
41
43
  /**
42
- * A refusal message, or a plain string when writing
43
- * (`res.api(null, { errorMessage: "..." })`): the envelope goes out with
44
+ * A refusal message, or a plain string when writing (a refusal thrown
45
+ * with refuse(), or an error handler's `res.api(null, { errorMessage })`): the envelope goes out with
44
46
  * the message object either way. Read off the wire it can still be a
45
47
  * string, or no message at all, wherever a Lambder server did not write
46
48
  * the body (a hand-built mock answer, a proxy); refusalMessageOf reads
@@ -58,15 +60,8 @@ export type LambderApiResponseConfig = {
58
60
  crash?: LambderCrashDetail;
59
61
  };
60
62
  /**
61
- * The config a null answer carries: at least one of the reason fields, so
62
- * `res.api(null, {})` is a compile error. A bare null with no flag and no
63
- * message reaches the caller as a success whose payload is null, which is
64
- * indistinguishable from an endpoint that answered nothing on purpose.
65
- */
66
- export type LambderApiNullAnswerConfig = LambderNonEmptyOptionMap<Pick<LambderApiResponseConfig, "versionExpired" | "sessionExpired" | "notAuthorized" | "errorMessage" | "message">> & LambderApiResponseConfig;
67
- /**
68
- * The API wire envelope both sides speak: res.api() emits it, LambderCaller
69
- * parses it. `apiVersion` is always there (null when the server set none):
63
+ * The API wire envelope both sides speak: the server writes it around a
64
+ * handler's output or a refusal, LambderCaller parses it. `apiVersion` is always there (null when the server set none):
70
65
  * it is how a reader tells a Lambder envelope from another JSON answer, such
71
66
  * as API Gateway's own `{ "message": ... }` errors, so an answer without it
72
67
  * reads as a server failure.