@farm.js/auth0 0.1.31 → 0.1.35

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/index.d.ts CHANGED
@@ -26,8 +26,44 @@ export interface Auth0IntegrationInput {
26
26
  audience?: string;
27
27
  scopes?: string[];
28
28
  tokenEndpointAuthMethod?: "auto" | "client_secret_basic" | "client_secret_post" | "none";
29
+ /**
30
+ * Session cookie name. A `__Host-` name (`__Host-farm_auth0_session`) cannot be set or
31
+ * shadowed by a sibling subdomain; Farm adds the `Secure` and `Path=/` it requires.
32
+ * @default "farm_auth0_session"
33
+ */
34
+ cookieName?: string;
35
+ /**
36
+ * Login state cookie name, held between the redirect to Auth0 and the callback.
37
+ * @default "farm_auth0_state"
38
+ */
39
+ stateCookieName?: string;
40
+ /**
41
+ * Longest a sign-in lasts, in seconds, when shorter than the Auth0 token lifetime. The session
42
+ * is a signed cookie, not a server record, so sign-out cannot invalidate a copy of it: a short
43
+ * max age bounds how long a copied cookie stays usable.
44
+ * @default the token's `expires_in`
45
+ */
46
+ sessionMaxAge?: number;
47
+ /**
48
+ * Called for every session Farm reads (profile route, protected routes). Return `true` to treat
49
+ * it as signed out, for example after `onSignOut` recorded its `sessionId` in your store.
50
+ * Sessions issued before this option existed have no `sessionId`.
51
+ */
52
+ isSessionRevoked?(session: Auth0Session, request: Request): boolean | Promise<boolean>;
53
+ /** Called on sign-out with the session being ended, so the app can revoke its `sessionId`. */
54
+ onSignOut?(session: Auth0Session, request: Request): void | Promise<void>;
29
55
  log?: FarmIntegrationLogger;
30
56
  }
57
+ /** A signed-in Auth0 session as Farm stores it in the session cookie. */
58
+ export interface Auth0Session {
59
+ user: Record<string, unknown>;
60
+ /** Epoch milliseconds after which the session is no longer accepted. */
61
+ expiresAt: number;
62
+ /** Random id of this sign-in; absent on sessions issued by older Farm releases. */
63
+ sessionId?: string;
64
+ /** Epoch milliseconds the session was issued; absent on older sessions. */
65
+ issuedAt?: number;
66
+ }
31
67
  interface ResolvedAuth0Env {
32
68
  domain: string;
33
69
  clientId: string;
@@ -88,7 +124,7 @@ export declare function auth0(input?: Auth0IntegrationInput): import("@farm.js/c
88
124
  routes: import("@farm.js/core").FarmTypedIntegrationRoute<string, never, any, unknown, false, "GET", import("@farm.js/core").FarmSchema | undefined>[];
89
125
  middleware: {
90
126
  matcher: string[];
91
- handler(request: Request): Response | undefined;
127
+ handler(request: Request): Promise<Response | undefined>;
92
128
  }[];
93
129
  }, import("@farm.js/core").FarmSchema | undefined>;
94
130
  export {};
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AACA,OAAO,EAAuC,KAAK,qBAAqB,EAAE,MAAM,eAAe,CAAC;AAgChG,MAAM,WAAW,aAAa;IAC5B,UAAU,CAAC,OAAO,EAAE,OAAO,GAAG,OAAO,CAAC,QAAQ,GAAG,IAAI,CAAC,GAAG,QAAQ,GAAG,IAAI,CAAC;IACzE,OAAO,CAAC,EAAE,MAAM,GAAG,MAAM,EAAE,CAAC;CAC7B;AAED,MAAM,WAAW,qBAAqB;IACpC,QAAQ,CAAC,EAAE,aAAa,CAAC;IACzB,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,eAAe,CAAC,EAAE,MAAM,GAAG,MAAM,EAAE,CAAC;IACpC;;;;OAIG;IACH,cAAc,CAAC,EAAE,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M,CAAC;IACf,UAAU,CAAC,EAAE,MAAM,CAAC;CACrB;AA2RD,wBAAgB,KAAK,CAAC,KAAK,GAAE,qBAA0B;;;;;;;yBAU5B,OAAO;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;yBAkVG,OAAO;;mDAmB3C"}
package/dist/index.js CHANGED
@@ -58,12 +58,14 @@ function createCodeVerifier() {
58
58
  function createCodeChallenge(verifier) {
59
59
  return createHash("sha256").update(verifier).digest("base64url");
60
60
  }
61
- function signValue(value, secret) {
61
+ function signPayload(payload, secret, purpose) {
62
+ return createHmac("sha256", secret).update(`farm-auth0:${purpose}.${payload}`).digest("hex");
63
+ }
64
+ function signValue(value, secret, purpose) {
62
65
  const payload = Buffer.from(JSON.stringify(value), "utf8").toString("base64url");
63
- const signature = createHmac("sha256", secret).update(payload).digest("hex");
64
- return `${payload}.${signature}`;
66
+ return `${payload}.${signPayload(payload, secret, purpose)}`;
65
67
  }
66
- function unsignValue(signed, secret) {
68
+ function unsignValue(signed, secret, purpose) {
67
69
  if (!signed) {
68
70
  return null;
69
71
  }
@@ -73,11 +75,13 @@ function unsignValue(signed, secret) {
73
75
  }
74
76
  const payload = signed.slice(0, separator);
75
77
  const signature = signed.slice(separator + 1);
76
- const expected = createHmac("sha256", secret).update(payload).digest("hex");
77
- if (signature.length !== expected.length) {
78
- return null;
79
- }
80
- if (!timingSafeEqual(Buffer.from(signature, "utf8"), Buffer.from(expected, "utf8"))) {
78
+ const expected = signPayload(payload, secret, purpose);
79
+ // Compare byte lengths: a multibyte signature can match the hex digest's
80
+ // character count, and timingSafeEqual throws on unequal buffers.
81
+ const signatureBytes = Buffer.from(signature, "utf8");
82
+ const expectedBytes = Buffer.from(expected, "utf8");
83
+ if (signatureBytes.length !== expectedBytes.length ||
84
+ !timingSafeEqual(signatureBytes, expectedBytes)) {
81
85
  return null;
82
86
  }
83
87
  try {
@@ -104,8 +108,14 @@ function decodeJwtPayload(token) {
104
108
  }
105
109
  function getSession(request, cookieName, secret) {
106
110
  const cookies = parseCookieHeaderMap(request.headers.get("cookie"));
107
- const session = unsignValue(cookies[cookieName], secret);
108
- if (!session) {
111
+ const session = unsignValue(cookies[cookieName], secret, "session");
112
+ if (!session ||
113
+ typeof session !== "object" ||
114
+ typeof session.expiresAt !== "number" ||
115
+ !Number.isFinite(session.expiresAt) ||
116
+ !session.user ||
117
+ typeof session.user !== "object" ||
118
+ Array.isArray(session.user)) {
109
119
  return null;
110
120
  }
111
121
  if (session.expiresAt <= Date.now()) {
@@ -172,6 +182,15 @@ async function exchangeCode(domain, clientId, clientSecret, code, redirectUri, c
172
182
  }
173
183
  throw new Error(lastFailure);
174
184
  }
185
+ function resolveCookieName(value, fallback, option) {
186
+ if (value === undefined)
187
+ return fallback;
188
+ // RFC 6265 token: no separators, whitespace, or control characters.
189
+ if (!/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/.test(value)) {
190
+ throw new Error(`Auth0 integration ${option} must be a valid cookie name, got ${JSON.stringify(value)}.`);
191
+ }
192
+ return value;
193
+ }
175
194
  export function auth0(input = {}) {
176
195
  if (input.instance) {
177
196
  return defineIntegration({
@@ -197,8 +216,30 @@ export function auth0(input = {}) {
197
216
  const profilePath = input.profilePath ?? "/auth/profile";
198
217
  const scopes = input.scopes?.length ? input.scopes : ["openid", "profile", "email"];
199
218
  const allowedOrigins = resolveIntegrationAllowedOrigins(input.allowedOrigins, "auth0.allowedOrigins");
200
- const stateCookieName = "farm_auth0_state";
201
- const sessionCookieName = "farm_auth0_session";
219
+ const stateCookieName = resolveCookieName(input.stateCookieName, "farm_auth0_state", "stateCookieName");
220
+ const sessionCookieName = resolveCookieName(input.cookieName, "farm_auth0_session", "cookieName");
221
+ if (stateCookieName === sessionCookieName) {
222
+ throw new Error("Auth0 integration cookieName and stateCookieName must differ.");
223
+ }
224
+ const sessionMaxAge = input.sessionMaxAge;
225
+ if (sessionMaxAge !== undefined &&
226
+ (typeof sessionMaxAge !== "number" || !Number.isFinite(sessionMaxAge) || sessionMaxAge < 60)) {
227
+ throw new Error("Auth0 integration sessionMaxAge must be a number of seconds, at least 60.");
228
+ }
229
+ /** The session cookie, unless it expired, outlived `sessionMaxAge`, or the app revoked it. */
230
+ async function readSession(request) {
231
+ const session = getSession(request, sessionCookieName, secret);
232
+ if (!session)
233
+ return null;
234
+ if (sessionMaxAge !== undefined &&
235
+ typeof session.issuedAt === "number" &&
236
+ session.issuedAt + sessionMaxAge * 1000 <= Date.now()) {
237
+ return null;
238
+ }
239
+ if (input.isSessionRevoked && (await input.isSessionRevoked(session, request)))
240
+ return null;
241
+ return session;
242
+ }
202
243
  const callbackSettings = resolveCallbackSettings({
203
244
  callbackUrl: input.callbackUrl,
204
245
  callbackPath: input.callbackPath,
@@ -228,7 +269,7 @@ export function auth0(input = {}) {
228
269
  authorizeUrl.searchParams.set("screen_hint", screenHint);
229
270
  }
230
271
  const headers = new Headers();
231
- headers.append("set-cookie", createRequestCookie(stateCookieName, signValue({ state, returnTo, codeVerifier }, secret), request, { maxAge: 600 }));
272
+ headers.append("set-cookie", createRequestCookie(stateCookieName, signValue({ state, returnTo, codeVerifier }, secret, "state"), request, { maxAge: 600 }));
232
273
  return {
233
274
  redirectTo: authorizeUrl.toString(),
234
275
  headers,
@@ -320,7 +361,7 @@ export function auth0(input = {}) {
320
361
  return new Response("Missing Auth0 authorization code or state.", { status: 400 });
321
362
  }
322
363
  const cookies = parseCookieHeaderMap(request.headers.get("cookie"));
323
- const statePayload = unsignValue(cookies[stateCookieName], secret);
364
+ const statePayload = unsignValue(cookies[stateCookieName], secret, "state");
324
365
  if (!statePayload || statePayload.state !== state) {
325
366
  return new Response("Invalid Auth0 state.", { status: 400 });
326
367
  }
@@ -328,9 +369,12 @@ export function auth0(input = {}) {
328
369
  const redirectUri = callbackSettings.getCallbackUrl(request);
329
370
  const tokenResponse = await exchangeCode(domain, clientId, clientSecret, code, redirectUri, statePayload.codeVerifier, input.tokenEndpointAuthMethod);
330
371
  const user = await createUserProfile(domain, tokenResponse.access_token, tokenResponse.id_token);
331
- const expiresAt = Date.now() + Math.max(tokenResponse.expires_in || 3600, 60) * 1000;
372
+ const issuedAt = Date.now();
373
+ const tokenLifetime = Math.max(tokenResponse.expires_in || 3600, 60);
374
+ const expiresAt = issuedAt + Math.min(tokenLifetime, sessionMaxAge ?? tokenLifetime) * 1000;
375
+ const sessionId = randomBytes(16).toString("hex");
332
376
  const headers = new Headers();
333
- headers.append("set-cookie", createRequestCookie(sessionCookieName, signValue({ user, expiresAt }, secret), request, {
377
+ headers.append("set-cookie", createRequestCookie(sessionCookieName, signValue({ user, expiresAt, sessionId, issuedAt }, secret, "session"), request, {
334
378
  maxAge: Math.max((expiresAt - Date.now()) / 1000, 60),
335
379
  }));
336
380
  headers.append("set-cookie", clearRequestCookie(stateCookieName, request));
@@ -344,7 +388,7 @@ export function auth0(input = {}) {
344
388
  }),
345
389
  integrationRoute.get(logoutPath, {
346
390
  responseFormat: "json",
347
- handler(request) {
391
+ async handler(request) {
348
392
  // Sign-out is a GET, so it is also reachable as a plain link or a
349
393
  // bookmark with no origin metadata at all. Only a request the browser
350
394
  // labelled cross-site is refused.
@@ -366,6 +410,9 @@ export function auth0(input = {}) {
366
410
  const redirectTo = new URL("/v2/logout", `https://${domain}`);
367
411
  redirectTo.searchParams.set("client_id", clientId);
368
412
  redirectTo.searchParams.set("returnTo", origin);
413
+ const endedSession = getSession(request, sessionCookieName, secret);
414
+ if (endedSession)
415
+ await input.onSignOut?.(endedSession, request);
369
416
  const headers = new Headers();
370
417
  headers.append("set-cookie", clearRequestCookie(sessionCookieName, request));
371
418
  if (request.headers.get("x-farm-integration-client") === "1") {
@@ -385,8 +432,8 @@ export function auth0(input = {}) {
385
432
  }),
386
433
  integrationRoute.get(profilePath, {
387
434
  responseFormat: "json",
388
- handler(request) {
389
- const session = getSession(request, sessionCookieName, secret);
435
+ async handler(request) {
436
+ const session = await readSession(request);
390
437
  if (!session) {
391
438
  return Response.json({
392
439
  authenticated: false,
@@ -403,8 +450,8 @@ export function auth0(input = {}) {
403
450
  ? [
404
451
  {
405
452
  matcher: protectedMatchers,
406
- handler(request) {
407
- const session = getSession(request, sessionCookieName, secret);
453
+ async handler(request) {
454
+ const session = await readSession(request);
408
455
  if (session) {
409
456
  return;
410
457
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@farm.js/auth0",
3
- "version": "0.1.31",
3
+ "version": "0.1.35",
4
4
  "description": "Auth0 integration for Farm.js",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -29,8 +29,8 @@
29
29
  "access": "public"
30
30
  },
31
31
  "dependencies": {
32
- "@farm.js/integration-utils": "0.1.31",
33
- "@farm.js/core": "0.1.31"
32
+ "@farm.js/integration-utils": "0.1.35",
33
+ "@farm.js/core": "0.1.35"
34
34
  },
35
35
  "scripts": {
36
36
  "build": "node -e \"require('node:fs').rmSync('dist', { recursive: true, force: true })\" && tsc",