@smartcrab/server 0.8.0 → 0.9.0-next-20261204032426

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/dist/http.d.ts CHANGED
@@ -16,6 +16,9 @@ export declare const DEFAULT_TIMEOUT_MS = 5000;
16
16
  export interface FetchedText {
17
17
  readonly status: number;
18
18
  readonly body: string;
19
+ /** Cache metadata retained for callers that cache validated upstream documents. */
20
+ readonly cacheControl?: string | null;
21
+ readonly age?: string | null;
19
22
  }
20
23
  export declare const fetchBoundedText: (input: {
21
24
  readonly fetchImpl: FetchLike;
package/dist/http.js CHANGED
@@ -52,7 +52,12 @@ export const fetchBoundedText = Result.fn({
52
52
  throw new ResponseTooLargeError();
53
53
  }
54
54
  const body = await readBounded(response, input.maxBytes);
55
- return { status: response.status, body };
55
+ return {
56
+ status: response.status,
57
+ body,
58
+ cacheControl: response.headers.get("cache-control"),
59
+ age: response.headers.get("age"),
60
+ };
56
61
  },
57
62
  catch: (cause) => {
58
63
  if (cause instanceof ResponseTooLargeError) {
@@ -9,8 +9,9 @@ import { timingSafeEqual } from "./security.js";
9
9
  * - discovery via `<issuer>/.well-known/openid-configuration`, validated by
10
10
  * the shared zod contracts and pinned to the configured issuer,
11
11
  * - JWKS fetched from the discovered `jwks_uri` (timeout + bounded size),
12
- * cached, and refetched exactly once when a token references an unknown
13
- * `kid` (signing-key rotation),
12
+ * cached only for the origin-advertised freshness (capped at five minutes),
13
+ * and refetched exactly once when a token references an unknown `kid`,
14
+ * to handle signing-key rotation,
14
15
  * - ID token verification with jose: **ES256 only** (unknown `alg` values are
15
16
  * rejected before verification), mandatory `kid`, and `iss`/`aud`/`exp`/
16
17
  * `typ`/`nonce` all checked (design.md §15.6),
@@ -23,11 +24,33 @@ import { timingSafeEqual } from "./security.js";
23
24
  * `Result.fn`; no raw try/catch (design.md §5.2).
24
25
  */
25
26
  const DISCOVERY_CACHE_TTL_MS = 60 * 60 * 1000;
26
- const JWKS_CACHE_TTL_MS = 60 * 60 * 1000;
27
+ const JWKS_CACHE_MAX_TTL_MS = 5 * 60 * 1000;
27
28
  const DISCOVERY_MAX_BYTES = 64 * 1024;
28
29
  const JWKS_MAX_BYTES = 256 * 1024;
29
30
  const TOKEN_RESPONSE_MAX_BYTES = 64 * 1024;
30
31
  const REVOCATION_RESPONSE_MAX_BYTES = 16 * 1024;
32
+ const JWKS_NO_CACHE_PATTERN = /(?:^|,)\s*(?:no-store|no-cache)(?:\s*(?:=|,|$))/i;
33
+ const JWKS_SHARED_MAX_AGE_PATTERN = /(?:^|,)\s*s-maxage\s*=\s*(?:"(\d+)"|(\d+))\s*(?=,|$)/i;
34
+ const JWKS_MAX_AGE_PATTERN = /(?:^|,)\s*max-age\s*=\s*(?:"(\d+)"|(\d+))\s*(?=,|$)/i;
35
+ const JWKS_AGE_PATTERN = /^\d+$/;
36
+ const jwksCacheTtlMs = (cacheControl, ageHeader) => {
37
+ if (cacheControl === null ||
38
+ cacheControl === undefined ||
39
+ JWKS_NO_CACHE_PATTERN.test(cacheControl)) {
40
+ return 0;
41
+ }
42
+ const maxAgeMatch = JWKS_SHARED_MAX_AGE_PATTERN.exec(cacheControl) ?? JWKS_MAX_AGE_PATTERN.exec(cacheControl);
43
+ const seconds = maxAgeMatch?.[1] ?? maxAgeMatch?.[2];
44
+ if (seconds === undefined)
45
+ return 0;
46
+ const maxAgeMs = Math.min(Number(seconds) * 1000, JWKS_CACHE_MAX_TTL_MS);
47
+ if (ageHeader === null || ageHeader === undefined)
48
+ return maxAgeMs;
49
+ const age = ageHeader.trim();
50
+ if (!JWKS_AGE_PATTERN.test(age))
51
+ return 0;
52
+ return Math.max(0, maxAgeMs - Number(age) * 1000);
53
+ };
31
54
  /**
32
55
  * `authorization_code` is single-use: aborting the exchange burns the code and
33
56
  * the user must log in again. Token issuance (code consumption, session,
@@ -121,9 +144,6 @@ export const createOidcClient = (options) => {
121
144
  }
122
145
  return result;
123
146
  };
124
- // -------------------------------------------------------------------------
125
- // JWKS
126
- // -------------------------------------------------------------------------
127
147
  let jwksCache = null;
128
148
  const parseJwksJson = jsonParser(() => ({ type: "jwks_invalid", detail: "invalid_json" }));
129
149
  const buildLocalKeySet = Result.fn({
@@ -156,22 +176,24 @@ export const createOidcClient = (options) => {
156
176
  };
157
177
  return Result.fail(error);
158
178
  }
159
- return buildLocalKeySet(parsed.data);
179
+ return Result.andThen(buildLocalKeySet(parsed.data), (keySet) => Result.succeed({
180
+ keySet,
181
+ cacheTtlMs: jwksCacheTtlMs(res.cacheControl, res.age),
182
+ }));
160
183
  });
161
184
  });
162
185
  };
163
186
  const getKeySet = async (forceRefresh) => {
164
- if (!forceRefresh &&
165
- jwksCache !== null &&
166
- Date.now() - jwksCache.fetchedAt < JWKS_CACHE_TTL_MS) {
187
+ if (!forceRefresh && jwksCache !== null && Date.now() - jwksCache.fetchedAt < jwksCache.ttlMs) {
167
188
  return Result.succeed(jwksCache.keySet);
168
189
  }
169
190
  const discovery = await getDiscovery();
170
191
  const result = await Result.andThen(discovery, (doc) => fetchAndBuildKeySet(doc.jwks_uri));
171
- if (Result.isSuccess(result)) {
172
- jwksCache = { fetchedAt: Date.now(), keySet: result.value };
173
- }
174
- return result;
192
+ if (Result.isFailure(result))
193
+ return result;
194
+ const { keySet, cacheTtlMs } = result.value;
195
+ jwksCache = cacheTtlMs > 0 ? { fetchedAt: Date.now(), ttlMs: cacheTtlMs, keySet } : null;
196
+ return Result.succeed(keySet);
175
197
  };
176
198
  // -------------------------------------------------------------------------
177
199
  // JWT verification
@@ -256,6 +278,8 @@ export const createOidcClient = (options) => {
256
278
  type: "access_token_invalid",
257
279
  reason,
258
280
  });
281
+ if (audience === undefined)
282
+ return Result.fail(accessTokenError("audience_required"));
259
283
  const headerResult = await headerDecoder(() => accessTokenError("malformed_token"))(token);
260
284
  if (Result.isFailure(headerResult))
261
285
  return headerResult;
@@ -266,7 +290,7 @@ export const createOidcClient = (options) => {
266
290
  // design.md §15.6: access tokens carry typ `at+jwt`.
267
291
  typ: "at+jwt",
268
292
  requiredClaims: ["exp", "iat", "sub"],
269
- ...(audience !== undefined ? { audience } : {}),
293
+ audience,
270
294
  }, (cause) => accessTokenError(joseErrorReason(cause)));
271
295
  };
272
296
  // -------------------------------------------------------------------------
@@ -25,16 +25,17 @@ export declare const timingSafeEqual: (a: string, b: string) => boolean;
25
25
  * the `Origin` header must match the request's own origin (or an explicitly
26
26
  * allowlisted origin); if `Origin` is absent we fall back to the `Referer`
27
27
  * origin; if neither is present the request is rejected (fail closed).
28
- * 3. Safe methods (GET/HEAD/OPTIONS) pass — they are top-level navigations
29
- * protected by `state` + PKCE + the single-use handshake cookie instead.
28
+ * 3. Safe methods (GET/HEAD/OPTIONS) pass here only for navigation flows
29
+ * protected by transaction state/PKCE; mutation handlers must not use them.
30
30
  *
31
31
  * Returns a boolean rather than a Result: the check is pure.
32
32
  */
33
33
  export declare const isRequestOriginValid: (request: Request, extraAllowedOrigins: readonly string[]) => boolean;
34
34
  /**
35
- * Stricter-than-navigation check used on GET handlers: if an `Origin` header
36
- * is present at all on a GET (some fetch-based flows send one), it must match.
37
- * Plain browser navigations send no `Origin` on GET and pass.
35
+ * Navigation-origin check for GET handlers: if an `Origin` header is present,
36
+ * it must match. Missing `Origin` is allowed for browser navigations; mutation
37
+ * handlers must use `isRequestOriginValid`, which falls back to a valid
38
+ * `Referer` and rejects requests when neither header supplies a valid origin.
38
39
  */
39
40
  export declare const hasInvalidNavigationOrigin: (request: Request, extraAllowedOrigins: readonly string[]) => boolean;
40
41
  /**
package/dist/security.js CHANGED
@@ -76,8 +76,8 @@ const isOriginAllowed = (origin, ownOrigin, extraAllowedOrigins) => origin === o
76
76
  * the `Origin` header must match the request's own origin (or an explicitly
77
77
  * allowlisted origin); if `Origin` is absent we fall back to the `Referer`
78
78
  * origin; if neither is present the request is rejected (fail closed).
79
- * 3. Safe methods (GET/HEAD/OPTIONS) pass — they are top-level navigations
80
- * protected by `state` + PKCE + the single-use handshake cookie instead.
79
+ * 3. Safe methods (GET/HEAD/OPTIONS) pass here only for navigation flows
80
+ * protected by transaction state/PKCE; mutation handlers must not use them.
81
81
  *
82
82
  * Returns a boolean rather than a Result: the check is pure.
83
83
  */
@@ -101,9 +101,10 @@ export const isRequestOriginValid = (request, extraAllowedOrigins) => {
101
101
  return false;
102
102
  };
103
103
  /**
104
- * Stricter-than-navigation check used on GET handlers: if an `Origin` header
105
- * is present at all on a GET (some fetch-based flows send one), it must match.
106
- * Plain browser navigations send no `Origin` on GET and pass.
104
+ * Navigation-origin check for GET handlers: if an `Origin` header is present,
105
+ * it must match. Missing `Origin` is allowed for browser navigations; mutation
106
+ * handlers must use `isRequestOriginValid`, which falls back to a valid
107
+ * `Referer` and rejects requests when neither header supplies a valid origin.
107
108
  */
108
109
  export const hasInvalidNavigationOrigin = (request, extraAllowedOrigins) => {
109
110
  const origin = request.headers.get("origin");
@@ -24,8 +24,8 @@ import type { Session } from "./session.js";
24
24
  * `invalid_grant` wipes the local session while transient failures keep it
25
25
  * (§21.7),
26
26
  * - CSRF: SameSite=Lax cookies plus Origin/Referer validation on mutation
27
- * handlers (the assignment's "choose and document" — see security.ts);
28
- * login/callback/logout all validate state and/or origin,
27
+ * handlers; logout is POST-only and validates Origin/Referer (see security.ts),
28
+ * while login/callback also use state/PKCE and navigation-origin checks,
29
29
  * - open-redirect prevention: post-login/logout targets must be relative
30
30
  * paths or byte-for-byte allowlisted URLs (§32.2).
31
31
  *
@@ -321,11 +321,10 @@ export const createServerAuth = (config) => {
321
321
  return redirectResponse(target, [sessionCookie.value, ...pkceClear]);
322
322
  };
323
323
  const logoutHandler = async (request) => {
324
- if (request.method !== "GET" && request.method !== "POST") {
324
+ if (request.method !== "POST") {
325
325
  return problemResponse(405, "method_not_allowed");
326
326
  }
327
- if (hasInvalidNavigationOrigin(request, cfg.allowedOrigins) ||
328
- !isRequestOriginValid(request, cfg.allowedOrigins)) {
327
+ if (!isRequestOriginValid(request, cfg.allowedOrigins)) {
329
328
  return problemResponse(403, "csrf_validation_failed");
330
329
  }
331
330
  const url = new URL(request.url);
package/dist/webhook.d.ts CHANGED
@@ -32,6 +32,10 @@ export type WebhookVerificationError = {
32
32
  readonly toleranceSeconds: number;
33
33
  } | {
34
34
  readonly type: "signature_mismatch";
35
+ } | {
36
+ readonly type: "event_id_mismatch";
37
+ } | {
38
+ readonly type: "malformed_event_body";
35
39
  } | {
36
40
  readonly type: "crypto_operation_failed";
37
41
  };
package/dist/webhook.js CHANGED
@@ -3,9 +3,10 @@ import { timingSafeEqual } from "./security.js";
3
3
  const EVENT_ID_HEADER = "X-Auth-Event-Id";
4
4
  const TIMESTAMP_HEADER = "X-Auth-Timestamp";
5
5
  const SIGNATURE_HEADER = "X-Auth-Signature";
6
+ const V2_SIGNATURE_HEADER = "X-Auth-Signature-V2";
6
7
  const DEFAULT_TOLERANCE_SECONDS = 300;
7
8
  const TIMESTAMP_PATTERN = /^\d+$/;
8
- const SIGNATURE_PATTERN = /^v1=([0-9a-f]+)$/;
9
+ const SIGNATURE_PATTERN = /^(v1|v2)=([0-9a-f]+)$/;
9
10
  const textEncoder = new TextEncoder();
10
11
  const findHeader = (headers, name) => {
11
12
  if ("get" in headers && typeof headers.get === "function") {
@@ -22,7 +23,10 @@ const hmacSha256Hex = Result.fn({
22
23
  try: async (input) => {
23
24
  const secretBytes = new Uint8Array(textEncoder.encode(input.secret));
24
25
  const key = await crypto.subtle.importKey("raw", secretBytes, { name: "HMAC", hash: "SHA-256" }, false, ["sign"]);
25
- const payloadBytes = new Uint8Array(textEncoder.encode(`${input.timestamp}.${input.rawBody}`));
26
+ const signedPayload = input.signatureVersion === "v2"
27
+ ? `${input.timestamp}.${input.eventId}.${input.rawBody}`
28
+ : `${input.timestamp}.${input.rawBody}`;
29
+ const payloadBytes = new Uint8Array(textEncoder.encode(signedPayload));
26
30
  const signature = await crypto.subtle.sign("HMAC", key, payloadBytes);
27
31
  const signatureBytes = new Uint8Array(signature);
28
32
  let hex = "";
@@ -32,6 +36,16 @@ const hmacSha256Hex = Result.fn({
32
36
  },
33
37
  catch: () => ({ type: "crypto_operation_failed" }),
34
38
  });
39
+ const parseWebhookEventId = Result.fn({
40
+ try: async (rawBody) => {
41
+ const body = JSON.parse(rawBody);
42
+ if (body === null || typeof body !== "object" || Array.isArray(body))
43
+ return null;
44
+ const eventId = body.eventId;
45
+ return typeof eventId === "string" ? eventId : null;
46
+ },
47
+ catch: () => ({ type: "malformed_event_body" }),
48
+ });
35
49
  /**
36
50
  * Verifies a Zeroword customer webhook using only WebCrypto. Preserve and pass
37
51
  * the raw body as received; parsing and serializing JSON changes signed bytes.
@@ -48,13 +62,17 @@ export const verifyWebhook = async (input) => {
48
62
  if (!TIMESTAMP_PATTERN.test(timestampHeader)) {
49
63
  return Result.fail({ type: "malformed_timestamp_header" });
50
64
  }
51
- const signatureHeader = findHeader(input.headers, SIGNATURE_HEADER);
52
- if (signatureHeader === undefined || signatureHeader.length === 0) {
65
+ const dedicatedV2Header = findHeader(input.headers, V2_SIGNATURE_HEADER);
66
+ const signatureHeader = dedicatedV2Header ?? findHeader(input.headers, SIGNATURE_HEADER);
67
+ if (signatureHeader === undefined) {
53
68
  return Result.fail({ type: "missing_header", header: SIGNATURE_HEADER });
54
69
  }
55
70
  const signatureMatch = SIGNATURE_PATTERN.exec(signatureHeader);
56
- const providedSignature = signatureMatch?.[1];
57
- if (providedSignature === undefined) {
71
+ const signatureVersion = signatureMatch?.[1];
72
+ const providedSignature = signatureMatch?.[2];
73
+ if (providedSignature === undefined ||
74
+ (signatureVersion !== "v1" && signatureVersion !== "v2") ||
75
+ (dedicatedV2Header !== undefined && signatureVersion !== "v2")) {
58
76
  return Result.fail({ type: "malformed_signature_header" });
59
77
  }
60
78
  const timestampSeconds = Number.parseInt(timestampHeader, 10);
@@ -83,6 +101,8 @@ export const verifyWebhook = async (input) => {
83
101
  const expected = await hmacSha256Hex({
84
102
  secret,
85
103
  timestamp: timestampHeader,
104
+ eventId,
105
+ signatureVersion,
86
106
  rawBody: input.rawBody,
87
107
  });
88
108
  if (Result.isFailure(expected))
@@ -91,5 +111,11 @@ export const verifyWebhook = async (input) => {
91
111
  }
92
112
  if (!matched)
93
113
  return Result.fail({ type: "signature_mismatch" });
114
+ const bodyEventId = await parseWebhookEventId(input.rawBody);
115
+ if (Result.isFailure(bodyEventId))
116
+ return bodyEventId;
117
+ if (bodyEventId.value === null || !timingSafeEqual(bodyEventId.value, eventId)) {
118
+ return Result.fail({ type: "event_id_mismatch" });
119
+ }
94
120
  return Result.succeed({ eventId, timestampSeconds });
95
121
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@smartcrab/server",
3
- "version": "0.8.0",
3
+ "version": "0.9.0-next-20261204032426",
4
4
  "license": "Apache-2.0",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -21,7 +21,8 @@
21
21
  },
22
22
  "files": [
23
23
  "dist",
24
- "src"
24
+ "src",
25
+ "!src/**/*.test.ts"
25
26
  ],
26
27
  "publishConfig": {
27
28
  "access": "public"
@@ -29,7 +30,7 @@
29
30
  "dependencies": {
30
31
  "jose": "6.2.14",
31
32
  "cookie": "2.0.1",
32
- "@smartcrab/contracts-public": "0.8.0"
33
+ "@smartcrab/contracts-public": "0.9.0-next-20261204032426"
33
34
  },
34
35
  "devDependencies": {
35
36
  "typescript": "5.9.3",
package/src/http.ts CHANGED
@@ -22,6 +22,9 @@ export const DEFAULT_TIMEOUT_MS = 5000;
22
22
  export interface FetchedText {
23
23
  readonly status: number;
24
24
  readonly body: string;
25
+ /** Cache metadata retained for callers that cache validated upstream documents. */
26
+ readonly cacheControl?: string | null;
27
+ readonly age?: string | null;
25
28
  }
26
29
 
27
30
  class ResponseTooLargeError extends Error {
@@ -84,7 +87,12 @@ export const fetchBoundedText = Result.fn({
84
87
  throw new ResponseTooLargeError();
85
88
  }
86
89
  const body = await readBounded(response, input.maxBytes);
87
- return { status: response.status, body };
90
+ return {
91
+ status: response.status,
92
+ body,
93
+ cacheControl: response.headers.get("cache-control"),
94
+ age: response.headers.get("age"),
95
+ };
88
96
  },
89
97
  catch: (cause: unknown): ServerAuthError => {
90
98
  if (cause instanceof ResponseTooLargeError) {
@@ -23,8 +23,9 @@ import { timingSafeEqual } from "./security.js";
23
23
  * - discovery via `<issuer>/.well-known/openid-configuration`, validated by
24
24
  * the shared zod contracts and pinned to the configured issuer,
25
25
  * - JWKS fetched from the discovered `jwks_uri` (timeout + bounded size),
26
- * cached, and refetched exactly once when a token references an unknown
27
- * `kid` (signing-key rotation),
26
+ * cached only for the origin-advertised freshness (capped at five minutes),
27
+ * and refetched exactly once when a token references an unknown `kid`,
28
+ * to handle signing-key rotation,
28
29
  * - ID token verification with jose: **ES256 only** (unknown `alg` values are
29
30
  * rejected before verification), mandatory `kid`, and `iss`/`aud`/`exp`/
30
31
  * `typ`/`nonce` all checked (design.md §15.6),
@@ -38,11 +39,39 @@ import { timingSafeEqual } from "./security.js";
38
39
  */
39
40
 
40
41
  const DISCOVERY_CACHE_TTL_MS = 60 * 60 * 1000;
41
- const JWKS_CACHE_TTL_MS = 60 * 60 * 1000;
42
+ const JWKS_CACHE_MAX_TTL_MS = 5 * 60 * 1000;
42
43
  const DISCOVERY_MAX_BYTES = 64 * 1024;
43
44
  const JWKS_MAX_BYTES = 256 * 1024;
44
45
  const TOKEN_RESPONSE_MAX_BYTES = 64 * 1024;
45
46
  const REVOCATION_RESPONSE_MAX_BYTES = 16 * 1024;
47
+
48
+ const JWKS_NO_CACHE_PATTERN = /(?:^|,)\s*(?:no-store|no-cache)(?:\s*(?:=|,|$))/i;
49
+ const JWKS_SHARED_MAX_AGE_PATTERN = /(?:^|,)\s*s-maxage\s*=\s*(?:"(\d+)"|(\d+))\s*(?=,|$)/i;
50
+ const JWKS_MAX_AGE_PATTERN = /(?:^|,)\s*max-age\s*=\s*(?:"(\d+)"|(\d+))\s*(?=,|$)/i;
51
+ const JWKS_AGE_PATTERN = /^\d+$/;
52
+
53
+ const jwksCacheTtlMs = (
54
+ cacheControl: string | null | undefined,
55
+ ageHeader: string | null | undefined,
56
+ ): number => {
57
+ if (
58
+ cacheControl === null ||
59
+ cacheControl === undefined ||
60
+ JWKS_NO_CACHE_PATTERN.test(cacheControl)
61
+ ) {
62
+ return 0;
63
+ }
64
+ const maxAgeMatch =
65
+ JWKS_SHARED_MAX_AGE_PATTERN.exec(cacheControl) ?? JWKS_MAX_AGE_PATTERN.exec(cacheControl);
66
+ const seconds = maxAgeMatch?.[1] ?? maxAgeMatch?.[2];
67
+ if (seconds === undefined) return 0;
68
+
69
+ const maxAgeMs = Math.min(Number(seconds) * 1000, JWKS_CACHE_MAX_TTL_MS);
70
+ if (ageHeader === null || ageHeader === undefined) return maxAgeMs;
71
+ const age = ageHeader.trim();
72
+ if (!JWKS_AGE_PATTERN.test(age)) return 0;
73
+ return Math.max(0, maxAgeMs - Number(age) * 1000);
74
+ };
46
75
  /**
47
76
  * `authorization_code` is single-use: aborting the exchange burns the code and
48
77
  * the user must log in again. Token issuance (code consumption, session,
@@ -200,7 +229,15 @@ export const createOidcClient = (options: OidcClientOptions): OidcClient => {
200
229
  // JWKS
201
230
  // -------------------------------------------------------------------------
202
231
 
203
- let jwksCache: { readonly fetchedAt: number; readonly keySet: LocalJWKSet } | null = null;
232
+ interface LoadedKeySet {
233
+ readonly keySet: LocalJWKSet;
234
+ readonly cacheTtlMs: number;
235
+ }
236
+ let jwksCache: {
237
+ readonly fetchedAt: number;
238
+ readonly ttlMs: number;
239
+ readonly keySet: LocalJWKSet;
240
+ } | null = null;
204
241
 
205
242
  const parseJwksJson = jsonParser(() => ({ type: "jwks_invalid", detail: "invalid_json" }));
206
243
 
@@ -211,14 +248,14 @@ export const createOidcClient = (options: OidcClientOptions): OidcClient => {
211
248
 
212
249
  const fetchAndBuildKeySet = async (
213
250
  jwksUri: string,
214
- ): ResultAsync<LocalJWKSet, ServerAuthError> => {
251
+ ): ResultAsync<LoadedKeySet, ServerAuthError> => {
215
252
  const fetched = await fetchBoundedText({
216
253
  fetchImpl,
217
254
  url: jwksUri,
218
255
  timeoutMs: DEFAULT_TIMEOUT_MS,
219
256
  maxBytes: JWKS_MAX_BYTES,
220
257
  });
221
- return Result.andThen(fetched, async (res): ResultAsync<LocalJWKSet, ServerAuthError> => {
258
+ return Result.andThen(fetched, async (res): ResultAsync<LoadedKeySet, ServerAuthError> => {
222
259
  if (res.status !== 200) {
223
260
  const error: ServerAuthError = {
224
261
  type: "jwks_fetch_failed",
@@ -237,25 +274,26 @@ export const createOidcClient = (options: OidcClientOptions): OidcClient => {
237
274
  };
238
275
  return Result.fail(error);
239
276
  }
240
- return buildLocalKeySet(parsed.data);
277
+ return Result.andThen(buildLocalKeySet(parsed.data), (keySet) =>
278
+ Result.succeed({
279
+ keySet,
280
+ cacheTtlMs: jwksCacheTtlMs(res.cacheControl, res.age),
281
+ }),
282
+ );
241
283
  });
242
284
  });
243
285
  };
244
286
 
245
287
  const getKeySet = async (forceRefresh: boolean): ResultAsync<LocalJWKSet, ServerAuthError> => {
246
- if (
247
- !forceRefresh &&
248
- jwksCache !== null &&
249
- Date.now() - jwksCache.fetchedAt < JWKS_CACHE_TTL_MS
250
- ) {
288
+ if (!forceRefresh && jwksCache !== null && Date.now() - jwksCache.fetchedAt < jwksCache.ttlMs) {
251
289
  return Result.succeed(jwksCache.keySet);
252
290
  }
253
291
  const discovery = await getDiscovery();
254
292
  const result = await Result.andThen(discovery, (doc) => fetchAndBuildKeySet(doc.jwks_uri));
255
- if (Result.isSuccess(result)) {
256
- jwksCache = { fetchedAt: Date.now(), keySet: result.value };
257
- }
258
- return result;
293
+ if (Result.isFailure(result)) return result;
294
+ const { keySet, cacheTtlMs } = result.value;
295
+ jwksCache = cacheTtlMs > 0 ? { fetchedAt: Date.now(), ttlMs: cacheTtlMs, keySet } : null;
296
+ return Result.succeed(keySet);
259
297
  };
260
298
 
261
299
  // -------------------------------------------------------------------------
@@ -373,6 +411,7 @@ export const createOidcClient = (options: OidcClientOptions): OidcClient => {
373
411
  type: "access_token_invalid",
374
412
  reason,
375
413
  });
414
+ if (audience === undefined) return Result.fail(accessTokenError("audience_required"));
376
415
  const headerResult = await headerDecoder(() => accessTokenError("malformed_token"))(token);
377
416
  if (Result.isFailure(headerResult)) return headerResult;
378
417
  const checked = checkHeader(headerResult.value, accessTokenError);
@@ -383,7 +422,7 @@ export const createOidcClient = (options: OidcClientOptions): OidcClient => {
383
422
  // design.md §15.6: access tokens carry typ `at+jwt`.
384
423
  typ: "at+jwt",
385
424
  requiredClaims: ["exp", "iat", "sub"],
386
- ...(audience !== undefined ? { audience } : {}),
425
+ audience,
387
426
  },
388
427
  (cause) => accessTokenError(joseErrorReason(cause)),
389
428
  );
package/src/security.ts CHANGED
@@ -100,8 +100,8 @@ const isOriginAllowed = (
100
100
  * the `Origin` header must match the request's own origin (or an explicitly
101
101
  * allowlisted origin); if `Origin` is absent we fall back to the `Referer`
102
102
  * origin; if neither is present the request is rejected (fail closed).
103
- * 3. Safe methods (GET/HEAD/OPTIONS) pass — they are top-level navigations
104
- * protected by `state` + PKCE + the single-use handshake cookie instead.
103
+ * 3. Safe methods (GET/HEAD/OPTIONS) pass here only for navigation flows
104
+ * protected by transaction state/PKCE; mutation handlers must not use them.
105
105
  *
106
106
  * Returns a boolean rather than a Result: the check is pure.
107
107
  */
@@ -126,9 +126,10 @@ export const isRequestOriginValid = (
126
126
  };
127
127
 
128
128
  /**
129
- * Stricter-than-navigation check used on GET handlers: if an `Origin` header
130
- * is present at all on a GET (some fetch-based flows send one), it must match.
131
- * Plain browser navigations send no `Origin` on GET and pass.
129
+ * Navigation-origin check for GET handlers: if an `Origin` header is present,
130
+ * it must match. Missing `Origin` is allowed for browser navigations; mutation
131
+ * handlers must use `isRequestOriginValid`, which falls back to a valid
132
+ * `Referer` and rejects requests when neither header supplies a valid origin.
132
133
  */
133
134
  export const hasInvalidNavigationOrigin = (
134
135
  request: Request,
@@ -47,8 +47,8 @@ import type { Session, SessionPayloadV1, SessionUser } from "./session.js";
47
47
  * `invalid_grant` wipes the local session while transient failures keep it
48
48
  * (§21.7),
49
49
  * - CSRF: SameSite=Lax cookies plus Origin/Referer validation on mutation
50
- * handlers (the assignment's "choose and document" — see security.ts);
51
- * login/callback/logout all validate state and/or origin,
50
+ * handlers; logout is POST-only and validates Origin/Referer (see security.ts),
51
+ * while login/callback also use state/PKCE and navigation-origin checks,
52
52
  * - open-redirect prevention: post-login/logout targets must be relative
53
53
  * paths or byte-for-byte allowlisted URLs (§32.2).
54
54
  *
@@ -581,13 +581,10 @@ export const createServerAuth = (config: ServerAuthConfig): ServerAuth => {
581
581
  };
582
582
 
583
583
  const logoutHandler = async (request: Request): Promise<Response> => {
584
- if (request.method !== "GET" && request.method !== "POST") {
584
+ if (request.method !== "POST") {
585
585
  return problemResponse(405, "method_not_allowed");
586
586
  }
587
- if (
588
- hasInvalidNavigationOrigin(request, cfg.allowedOrigins) ||
589
- !isRequestOriginValid(request, cfg.allowedOrigins)
590
- ) {
587
+ if (!isRequestOriginValid(request, cfg.allowedOrigins)) {
591
588
  return problemResponse(403, "csrf_validation_failed");
592
589
  }
593
590
  const url = new URL(request.url);
package/src/webhook.ts CHANGED
@@ -4,9 +4,10 @@ import { timingSafeEqual } from "./security.js";
4
4
  const EVENT_ID_HEADER = "X-Auth-Event-Id";
5
5
  const TIMESTAMP_HEADER = "X-Auth-Timestamp";
6
6
  const SIGNATURE_HEADER = "X-Auth-Signature";
7
+ const V2_SIGNATURE_HEADER = "X-Auth-Signature-V2";
7
8
  const DEFAULT_TOLERANCE_SECONDS = 300;
8
9
  const TIMESTAMP_PATTERN = /^\d+$/;
9
- const SIGNATURE_PATTERN = /^v1=([0-9a-f]+)$/;
10
+ const SIGNATURE_PATTERN = /^(v1|v2)=([0-9a-f]+)$/;
10
11
  const textEncoder = new TextEncoder();
11
12
 
12
13
  export type WebhookVerificationHeaders = Headers | Readonly<Record<string, string>>;
@@ -43,6 +44,8 @@ export type WebhookVerificationError =
43
44
  readonly toleranceSeconds: number;
44
45
  }
45
46
  | { readonly type: "signature_mismatch" }
47
+ | { readonly type: "event_id_mismatch" }
48
+ | { readonly type: "malformed_event_body" }
46
49
  | { readonly type: "crypto_operation_failed" };
47
50
 
48
51
  const findHeader = (headers: WebhookVerificationHeaders, name: string): string | undefined => {
@@ -60,6 +63,8 @@ const hmacSha256Hex = Result.fn({
60
63
  try: async (input: {
61
64
  readonly secret: string;
62
65
  readonly timestamp: string;
66
+ readonly eventId: string;
67
+ readonly signatureVersion: "v1" | "v2";
63
68
  readonly rawBody: string;
64
69
  }): Promise<string> => {
65
70
  const secretBytes: Uint8Array<ArrayBuffer> = new Uint8Array(textEncoder.encode(input.secret));
@@ -70,9 +75,11 @@ const hmacSha256Hex = Result.fn({
70
75
  false,
71
76
  ["sign"],
72
77
  );
73
- const payloadBytes: Uint8Array<ArrayBuffer> = new Uint8Array(
74
- textEncoder.encode(`${input.timestamp}.${input.rawBody}`),
75
- );
78
+ const signedPayload =
79
+ input.signatureVersion === "v2"
80
+ ? `${input.timestamp}.${input.eventId}.${input.rawBody}`
81
+ : `${input.timestamp}.${input.rawBody}`;
82
+ const payloadBytes: Uint8Array<ArrayBuffer> = new Uint8Array(textEncoder.encode(signedPayload));
76
83
  const signature = await crypto.subtle.sign("HMAC", key, payloadBytes);
77
84
  const signatureBytes = new Uint8Array(signature);
78
85
  let hex = "";
@@ -82,6 +89,16 @@ const hmacSha256Hex = Result.fn({
82
89
  catch: (): WebhookVerificationError => ({ type: "crypto_operation_failed" }),
83
90
  });
84
91
 
92
+ const parseWebhookEventId = Result.fn({
93
+ try: async (rawBody: string): Promise<string | null> => {
94
+ const body: unknown = JSON.parse(rawBody);
95
+ if (body === null || typeof body !== "object" || Array.isArray(body)) return null;
96
+ const eventId = (body as Record<string, unknown>).eventId;
97
+ return typeof eventId === "string" ? eventId : null;
98
+ },
99
+ catch: (): WebhookVerificationError => ({ type: "malformed_event_body" }),
100
+ });
101
+
85
102
  /**
86
103
  * Verifies a Zeroword customer webhook using only WebCrypto. Preserve and pass
87
104
  * the raw body as received; parsing and serializing JSON changes signed bytes.
@@ -102,13 +119,19 @@ export const verifyWebhook = async (
102
119
  return Result.fail({ type: "malformed_timestamp_header" });
103
120
  }
104
121
 
105
- const signatureHeader = findHeader(input.headers, SIGNATURE_HEADER);
106
- if (signatureHeader === undefined || signatureHeader.length === 0) {
122
+ const dedicatedV2Header = findHeader(input.headers, V2_SIGNATURE_HEADER);
123
+ const signatureHeader = dedicatedV2Header ?? findHeader(input.headers, SIGNATURE_HEADER);
124
+ if (signatureHeader === undefined) {
107
125
  return Result.fail({ type: "missing_header", header: SIGNATURE_HEADER });
108
126
  }
109
127
  const signatureMatch = SIGNATURE_PATTERN.exec(signatureHeader);
110
- const providedSignature = signatureMatch?.[1];
111
- if (providedSignature === undefined) {
128
+ const signatureVersion = signatureMatch?.[1];
129
+ const providedSignature = signatureMatch?.[2];
130
+ if (
131
+ providedSignature === undefined ||
132
+ (signatureVersion !== "v1" && signatureVersion !== "v2") ||
133
+ (dedicatedV2Header !== undefined && signatureVersion !== "v2")
134
+ ) {
112
135
  return Result.fail({ type: "malformed_signature_header" });
113
136
  }
114
137
 
@@ -140,6 +163,8 @@ export const verifyWebhook = async (
140
163
  const expected = await hmacSha256Hex({
141
164
  secret,
142
165
  timestamp: timestampHeader,
166
+ eventId,
167
+ signatureVersion,
143
168
  rawBody: input.rawBody,
144
169
  });
145
170
  if (Result.isFailure(expected)) return expected;
@@ -147,5 +172,10 @@ export const verifyWebhook = async (
147
172
  }
148
173
 
149
174
  if (!matched) return Result.fail({ type: "signature_mismatch" });
175
+ const bodyEventId = await parseWebhookEventId(input.rawBody);
176
+ if (Result.isFailure(bodyEventId)) return bodyEventId;
177
+ if (bodyEventId.value === null || !timingSafeEqual(bodyEventId.value, eventId)) {
178
+ return Result.fail({ type: "event_id_mismatch" });
179
+ }
150
180
  return Result.succeed({ eventId, timestampSeconds });
151
181
  };