@farm.js/auth0 0.1.60 → 0.1.61

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,44 +26,8 @@ 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>;
55
29
  log?: FarmIntegrationLogger;
56
30
  }
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
- }
67
31
  interface ResolvedAuth0Env {
68
32
  domain: string;
69
33
  clientId: string;
@@ -124,7 +88,7 @@ export declare function auth0(input?: Auth0IntegrationInput): import("@farm.js/c
124
88
  routes: import("@farm.js/core").FarmTypedIntegrationRoute<string, never, any, unknown, false, "GET", import("@farm.js/core").FarmSchema | undefined>[];
125
89
  middleware: {
126
90
  matcher: string[];
127
- handler(request: Request): Promise<Response | undefined>;
91
+ handler(request: Request): Response | undefined;
128
92
  }[];
129
93
  }, import("@farm.js/core").FarmSchema | undefined>;
130
94
  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;AA+BhG,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,MAAM,EAAE,CAAC;IAC1B,QAAQ,CAAC,EAA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;CACrB;AA6PD,wBAAgB,KAAK,CAAC,KAAK,GAAE,qBAA0B;;;;;;;yBAU5B,OAAO;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;yBAsSH,OAAO;;mDAmBrC"}
package/dist/index.js CHANGED
@@ -2,13 +2,13 @@ import { createHash, createHmac, randomBytes, timingSafeEqual } from "node:crypt
2
2
  import { defineIntegration, integrationRoute } from "@farm.js/core";
3
3
  import { describeIntegrationOriginRejection, resolveIntegrationAllowedOrigins, validateIntegrationRequestOrigin, } from "@farm.js/core/integrations";
4
4
  import { clearRequestCookie, createPathInferredClientApi, createDocumentNavigationMatchers, createRequestCookie, getOrigin, getReturnTo, integrationConfig, normalizeMatchers, parseCookieHeaderMap, resolveCallbackSettings, } from "@farm.js/integration-utils";
5
- import { resolveDevelopmentSecret } from "@farm.js/integration-utils/dev-secret";
6
5
  import { auth0Client } from "./client.js";
6
+ const DEV_SECRET = "farmjs-auth0-development-secret-2026";
7
7
  // The built server re-evaluates farm.config.ts at runtime to instantiate
8
8
  // integrations, and Farm does not force NODE_ENV=production into that process.
9
9
  // Treating an absent NODE_ENV as "development" would silently sign production
10
- // sessions with a development secret, so only an explicit dev/test value may
11
- // use one. `farm dev` runs through Vite, which sets NODE_ENV="development".
10
+ // sessions with the public DEV_SECRET, so only an explicit dev/test value may
11
+ // use it. `farm dev` runs through Vite, which sets NODE_ENV="development".
12
12
  function isExplicitDevelopmentEnv() {
13
13
  return process.env.NODE_ENV === "development" || process.env.NODE_ENV === "test";
14
14
  }
@@ -34,15 +34,13 @@ function resolveEnv(input) {
34
34
  const domain = normalizeDomain(input.domain ?? process.env.AUTH0_DOMAIN ?? "");
35
35
  const clientId = input.clientId ?? process.env.AUTH0_CLIENT_ID ?? "";
36
36
  const clientSecret = input.clientSecret ?? process.env.AUTH0_CLIENT_SECRET ?? "";
37
- const secret = input.secret ??
38
- process.env.AUTH0_SECRET ??
39
- (isExplicitDevelopmentEnv() ? resolveDevelopmentSecret("auth0") : "");
37
+ const secret = input.secret ?? process.env.AUTH0_SECRET ?? (isExplicitDevelopmentEnv() ? DEV_SECRET : "");
40
38
  const appBaseUrl = input.appBaseUrl ?? process.env.APP_BASE_URL ?? undefined;
41
39
  if (!domain || !clientId) {
42
40
  throw new Error("Auth0 integration requires AUTH0_DOMAIN and AUTH0_CLIENT_ID.");
43
41
  }
44
42
  if (!secret) {
45
- throw new Error("Auth0 integration requires AUTH0_SECRET. A generated development-only secret is used " +
43
+ throw new Error("Auth0 integration requires AUTH0_SECRET. A development-only fallback secret is used " +
46
44
  'only when NODE_ENV is "development" or "test"; set AUTH0_SECRET to a random 32-byte ' +
47
45
  "value in every other environment.");
48
46
  }
@@ -60,14 +58,12 @@ function createCodeVerifier() {
60
58
  function createCodeChallenge(verifier) {
61
59
  return createHash("sha256").update(verifier).digest("base64url");
62
60
  }
63
- function signPayload(payload, secret, purpose) {
64
- return createHmac("sha256", secret).update(`farm-auth0:${purpose}.${payload}`).digest("hex");
65
- }
66
- function signValue(value, secret, purpose) {
61
+ function signValue(value, secret) {
67
62
  const payload = Buffer.from(JSON.stringify(value), "utf8").toString("base64url");
68
- return `${payload}.${signPayload(payload, secret, purpose)}`;
63
+ const signature = createHmac("sha256", secret).update(payload).digest("hex");
64
+ return `${payload}.${signature}`;
69
65
  }
70
- function unsignValue(signed, secret, purpose) {
66
+ function unsignValue(signed, secret) {
71
67
  if (!signed) {
72
68
  return null;
73
69
  }
@@ -77,13 +73,11 @@ function unsignValue(signed, secret, purpose) {
77
73
  }
78
74
  const payload = signed.slice(0, separator);
79
75
  const signature = signed.slice(separator + 1);
80
- const expected = signPayload(payload, secret, purpose);
81
- // Compare byte lengths: a multibyte signature can match the hex digest's
82
- // character count, and timingSafeEqual throws on unequal buffers.
83
- const signatureBytes = Buffer.from(signature, "utf8");
84
- const expectedBytes = Buffer.from(expected, "utf8");
85
- if (signatureBytes.length !== expectedBytes.length ||
86
- !timingSafeEqual(signatureBytes, expectedBytes)) {
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"))) {
87
81
  return null;
88
82
  }
89
83
  try {
@@ -110,14 +104,8 @@ function decodeJwtPayload(token) {
110
104
  }
111
105
  function getSession(request, cookieName, secret) {
112
106
  const cookies = parseCookieHeaderMap(request.headers.get("cookie"));
113
- const session = unsignValue(cookies[cookieName], secret, "session");
114
- if (!session ||
115
- typeof session !== "object" ||
116
- typeof session.expiresAt !== "number" ||
117
- !Number.isFinite(session.expiresAt) ||
118
- !session.user ||
119
- typeof session.user !== "object" ||
120
- Array.isArray(session.user)) {
107
+ const session = unsignValue(cookies[cookieName], secret);
108
+ if (!session) {
121
109
  return null;
122
110
  }
123
111
  if (session.expiresAt <= Date.now()) {
@@ -184,15 +172,6 @@ async function exchangeCode(domain, clientId, clientSecret, code, redirectUri, c
184
172
  }
185
173
  throw new Error(lastFailure);
186
174
  }
187
- function resolveCookieName(value, fallback, option) {
188
- if (value === undefined)
189
- return fallback;
190
- // RFC 6265 token: no separators, whitespace, or control characters.
191
- if (!/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/.test(value)) {
192
- throw new Error(`Auth0 integration ${option} must be a valid cookie name, got ${JSON.stringify(value)}.`);
193
- }
194
- return value;
195
- }
196
175
  export function auth0(input = {}) {
197
176
  if (input.instance) {
198
177
  return defineIntegration({
@@ -218,30 +197,8 @@ export function auth0(input = {}) {
218
197
  const profilePath = input.profilePath ?? "/auth/profile";
219
198
  const scopes = input.scopes?.length ? input.scopes : ["openid", "profile", "email"];
220
199
  const allowedOrigins = resolveIntegrationAllowedOrigins(input.allowedOrigins, "auth0.allowedOrigins");
221
- const stateCookieName = resolveCookieName(input.stateCookieName, "farm_auth0_state", "stateCookieName");
222
- const sessionCookieName = resolveCookieName(input.cookieName, "farm_auth0_session", "cookieName");
223
- if (stateCookieName === sessionCookieName) {
224
- throw new Error("Auth0 integration cookieName and stateCookieName must differ.");
225
- }
226
- const sessionMaxAge = input.sessionMaxAge;
227
- if (sessionMaxAge !== undefined &&
228
- (typeof sessionMaxAge !== "number" || !Number.isFinite(sessionMaxAge) || sessionMaxAge < 60)) {
229
- throw new Error("Auth0 integration sessionMaxAge must be a number of seconds, at least 60.");
230
- }
231
- /** The session cookie, unless it expired, outlived `sessionMaxAge`, or the app revoked it. */
232
- async function readSession(request) {
233
- const session = getSession(request, sessionCookieName, secret);
234
- if (!session)
235
- return null;
236
- if (sessionMaxAge !== undefined &&
237
- typeof session.issuedAt === "number" &&
238
- session.issuedAt + sessionMaxAge * 1000 <= Date.now()) {
239
- return null;
240
- }
241
- if (input.isSessionRevoked && (await input.isSessionRevoked(session, request)))
242
- return null;
243
- return session;
244
- }
200
+ const stateCookieName = "farm_auth0_state";
201
+ const sessionCookieName = "farm_auth0_session";
245
202
  const callbackSettings = resolveCallbackSettings({
246
203
  callbackUrl: input.callbackUrl,
247
204
  callbackPath: input.callbackPath,
@@ -271,7 +228,7 @@ export function auth0(input = {}) {
271
228
  authorizeUrl.searchParams.set("screen_hint", screenHint);
272
229
  }
273
230
  const headers = new Headers();
274
- headers.append("set-cookie", createRequestCookie(stateCookieName, signValue({ state, returnTo, codeVerifier }, secret, "state"), request, { maxAge: 600 }));
231
+ headers.append("set-cookie", createRequestCookie(stateCookieName, signValue({ state, returnTo, codeVerifier }, secret), request, { maxAge: 600 }));
275
232
  return {
276
233
  redirectTo: authorizeUrl.toString(),
277
234
  headers,
@@ -363,7 +320,7 @@ export function auth0(input = {}) {
363
320
  return new Response("Missing Auth0 authorization code or state.", { status: 400 });
364
321
  }
365
322
  const cookies = parseCookieHeaderMap(request.headers.get("cookie"));
366
- const statePayload = unsignValue(cookies[stateCookieName], secret, "state");
323
+ const statePayload = unsignValue(cookies[stateCookieName], secret);
367
324
  if (!statePayload || statePayload.state !== state) {
368
325
  return new Response("Invalid Auth0 state.", { status: 400 });
369
326
  }
@@ -371,16 +328,10 @@ export function auth0(input = {}) {
371
328
  const redirectUri = callbackSettings.getCallbackUrl(request);
372
329
  const tokenResponse = await exchangeCode(domain, clientId, clientSecret, code, redirectUri, statePayload.codeVerifier, input.tokenEndpointAuthMethod);
373
330
  const user = await createUserProfile(domain, tokenResponse.access_token, tokenResponse.id_token);
374
- const issuedAt = Date.now();
375
- const tokenLifetime = Math.max(tokenResponse.expires_in || 3600, 60);
376
- const sessionLifetime = Math.min(tokenLifetime, sessionMaxAge ?? tokenLifetime);
377
- const expiresAt = issuedAt + sessionLifetime * 1000;
378
- const sessionId = randomBytes(16).toString("hex");
331
+ const expiresAt = Date.now() + Math.max(tokenResponse.expires_in || 3600, 60) * 1000;
379
332
  const headers = new Headers();
380
- headers.append("set-cookie", createRequestCookie(sessionCookieName, signValue({ user, expiresAt, sessionId, issuedAt }, secret, "session"), request, {
381
- // The lifetime itself, not expiresAt minus a later clock read, so the
382
- // cookie's Max-Age is exact and never a second short.
383
- maxAge: sessionLifetime,
333
+ headers.append("set-cookie", createRequestCookie(sessionCookieName, signValue({ user, expiresAt }, secret), request, {
334
+ maxAge: Math.max((expiresAt - Date.now()) / 1000, 60),
384
335
  }));
385
336
  headers.append("set-cookie", clearRequestCookie(stateCookieName, request));
386
337
  headers.set("location", new URL(statePayload.returnTo || "/dashboard", origin).toString());
@@ -393,7 +344,7 @@ export function auth0(input = {}) {
393
344
  }),
394
345
  integrationRoute.get(logoutPath, {
395
346
  responseFormat: "json",
396
- async handler(request) {
347
+ handler(request) {
397
348
  // Sign-out is a GET, so it is also reachable as a plain link or a
398
349
  // bookmark with no origin metadata at all. Only a request the browser
399
350
  // labelled cross-site is refused.
@@ -415,9 +366,6 @@ export function auth0(input = {}) {
415
366
  const redirectTo = new URL("/v2/logout", `https://${domain}`);
416
367
  redirectTo.searchParams.set("client_id", clientId);
417
368
  redirectTo.searchParams.set("returnTo", origin);
418
- const endedSession = getSession(request, sessionCookieName, secret);
419
- if (endedSession)
420
- await input.onSignOut?.(endedSession, request);
421
369
  const headers = new Headers();
422
370
  headers.append("set-cookie", clearRequestCookie(sessionCookieName, request));
423
371
  if (request.headers.get("x-farm-integration-client") === "1") {
@@ -437,8 +385,8 @@ export function auth0(input = {}) {
437
385
  }),
438
386
  integrationRoute.get(profilePath, {
439
387
  responseFormat: "json",
440
- async handler(request) {
441
- const session = await readSession(request);
388
+ handler(request) {
389
+ const session = getSession(request, sessionCookieName, secret);
442
390
  if (!session) {
443
391
  return Response.json({
444
392
  authenticated: false,
@@ -455,8 +403,8 @@ export function auth0(input = {}) {
455
403
  ? [
456
404
  {
457
405
  matcher: protectedMatchers,
458
- async handler(request) {
459
- const session = await readSession(request);
406
+ handler(request) {
407
+ const session = getSession(request, sessionCookieName, secret);
460
408
  if (session) {
461
409
  return;
462
410
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@farm.js/auth0",
3
- "version": "0.1.60",
3
+ "version": "0.1.61",
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.60",
33
- "@farm.js/core": "0.1.60"
32
+ "@farm.js/integration-utils": "0.1.61",
33
+ "@farm.js/core": "0.1.61"
34
34
  },
35
35
  "scripts": {
36
36
  "build": "node -e \"require('node:fs').rmSync('dist', { recursive: true, force: true })\" && tsc",