Adds auth layer to docs.scalekit.com#410
Conversation
- Added middleware for handling authentication and session management, ensuring protected routes are accessible only to authenticated users. - Introduced new API routes for login, logout, and session verification, enhancing the authentication flow. - Created utility functions for PKCE (Proof Key for Code Exchange) to improve security during the OAuth process. - Added environment template for GitHub token and other configuration settings to streamline setup for developers. - Integrated new authentication components for user interface, including AuthCTA, AuthGate, and AuthValue, to manage user sessions effectively. This update significantly enhances the authentication capabilities of the Scalekit application, providing a robust framework for user management and security.
…users - Added a dropdown menu to the AuthCTA component for users who are logged in, allowing access to the Dashboard and Sign out options. - Implemented event listeners for menu interactions, including opening and closing the menu on click and keyboard events. - Updated styles to manage visibility of the Sign in button and dropdown menu based on authentication state. - Improved accessibility with ARIA attributes for better screen reader support. This update significantly improves the user experience by providing a more intuitive interface for authenticated users.
- Eliminated the Dashboard link from the AuthCTA dropdown menu to streamline the user interface for authenticated users. - This change enhances the focus on the Sign out option, improving the overall user experience.
- Added scripts to load the Pylon widget, enabling real-time user engagement features. - Implemented logic to derive user information from local storage, enhancing personalization within the widget. - This update improves the overall user experience by providing tailored interactions based on user data.
…lock.yaml - Eliminated `repomix` from both `package.json` and `pnpm-lock.yaml` to streamline dependencies and reduce potential bloat. - This cleanup improves the overall project maintainability by ensuring only necessary packages are included.
📝 WalkthroughWalkthroughAdds a PKCE OAuth flow (login, callback, refresh, logout, session), server middleware protecting routes, JWT verification with per-issuer JWKS caching, client session utilities and UI components, PostHog/Pylon widget integration, auth helper modules, several API endpoints, and related config/dependency updates. Changes
Sequence Diagram(s)sequenceDiagram
participant Browser as User Browser
participant App as Astro App
participant IdP as OAuth Provider
participant JWKS as JWKS Endpoint
Browser->>App: GET /auth/login (or click Sign In)
App->>App: genCodeVerifier & code_challenge, set PKCE cookies
App->>Browser: 302 Redirect to IdP with state & challenge
Browser->>IdP: Auth request (user authenticates)
IdP->>Browser: Redirect back /auth/callback?code&state
Browser->>App: GET /auth/callback
App->>App: validate state, read verifier from cookies
App->>IdP: POST token exchange (code + verifier)
IdP->>App: access_token, id_token, refresh_token
App->>JWKS: fetch keys (cached) for token verification
JWKS->>App: keys
App->>App: verify tokens, set HttpOnly cookies, respond with redirect page
Browser->>App: Request protected resource
App->>App: middleware reads sk_access_token
App->>JWKS: verify token via cached JWKS
JWKS->>App: valid -> allow request
Browser->>App: logout
App->>Browser: clear cookies + client redirect page to IdP /oidc/logout
Estimated code review effort🎯 4 (Complex) | ⏱️ ~50 minutes Possibly related PRs
Suggested reviewers
Poem
🚥 Pre-merge checks | ✅ 2 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (2 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing touches
🧪 Generate unit tests (beta)
📜 Recent review detailsConfiguration used: Repository UI Review profile: CHILL Plan: Pro 📒 Files selected for processing (1)
🚧 Files skipped from review as they are similar to previous changes (1)
✏️ Tip: You can disable this entire section by setting Comment |
- Refactored the Pylon widget script to use async functions for better session management. - Added logic to fetch session data from the server if no cached session is found, enhancing user experience. - Improved error handling during widget initialization to provide clearer debugging information. - This update enhances the reliability and responsiveness of the Pylon widget by ensuring user data is accurately derived and utilized.
- Added debug.log to .gitignore to prevent logging files from being tracked in version control. - This change helps maintain a cleaner repository by excluding unnecessary log files.
…rity and session handling - Changed output configuration in `astro.config.mjs` from 'static' to 'server' for better server-side rendering. - Removed unnecessary logging from `src/middleware.ts` to streamline the authentication process. - Enhanced the authentication flow by validating redirect URLs in `callback.ts` and `login.ts` to prevent open redirect attacks. - Improved error handling in `session.ts` to ensure proper responses for unauthorized access. - Cleaned up JWT utility functions in `jwt.ts` by removing debug logging, enhancing performance and security. These changes enhance the overall security and reliability of the authentication process within the application.
- Added verification for received tokens in `callback.ts` to ensure a complete OAuth response. - Implemented cryptographic verification of the access token in `session.ts` to enhance security. - Improved error handling in `jwt.ts` for JWKS initialization failures, ensuring graceful degradation of JWT verification. These changes strengthen the authentication process by ensuring that only valid tokens are processed and providing clearer error handling for potential issues.
…itialization - Implemented robust validation for session data to prevent injection of malicious properties and ensure proper structure. - Added sanitization for user email and name to remove potential HTML/script tags, enhancing security. - Improved error handling during session parsing to prevent widget initialization with invalid data. - Updated middleware to ensure access is denied if JWT verification fails, enhancing overall authentication security. These changes strengthen the integrity of user session management and improve the security of the Pylon widget integration.
- Introduced caching for JWKS by issuer URL to optimize performance and reduce redundant requests during JWT verification. - Updated the `verifyJwt` function to extract issuer and audience claims directly from the token, eliminating the need for environment variables. - Improved error handling for missing claims in the JWT, providing clearer feedback when verification fails. These changes strengthen the JWT verification process, enhance performance, and improve error reporting for better debugging.
- Updated the logout flow to extract the ID token from localStorage before clearing it, ensuring proper session termination. - Modified the logout endpoint to accept the ID token as a query parameter for improved session invalidation with Scalekit. - Included the raw ID token in the session response to facilitate logout operations. These changes strengthen the logout process and improve session management, enhancing overall security and user experience.
… endpoints - Eliminated the `client_secret` parameter from the token requests in both `callback.ts` and `refresh.ts` to enhance security by preventing sensitive information from being exposed. - This change aligns with best practices for OAuth implementations, ensuring that client secrets are not unnecessarily transmitted during token exchanges. These updates strengthen the security posture of the authentication flow by minimizing the risk of credential exposure.
- Added extraction of `uid` (user ID) and `xoid` (workspace ID) from ID token claims and access token payload to the session response. - Updated the `AuthSession` type to include optional `uid` and `xoid` properties for better session management. These changes improve the session response by providing essential identifiers, enhancing the overall user experience and session handling.
- Added a new Pylon widget script to initialize the chat widget with user session data, improving user interaction. - Implemented robust session validation and sanitization for user email and name to enhance security. - Introduced a new API endpoint to fetch email hashes for identity verification, ensuring accurate user identification. - Improved error handling during widget initialization and session fetching to provide clearer feedback. These changes strengthen the integration of the Pylon widget, enhance user experience, and improve overall security in session management.
- Introduced session management improvements by implementing a polling mechanism to identify users from session data. - Added functions to read session data from localStorage and reset PostHog identity when the session changes. - Enhanced the Pylon widget by ensuring user identifiers are correctly set during initialization. - Updated documentation to include the new external organization ID (xoid) in the session response. These changes strengthen user session handling and improve the integration with PostHog, enhancing overall user experience and data accuracy.
- Enhanced session management by implementing a refresh mechanism for access tokens, ensuring users remain authenticated seamlessly. - Updated the `AuthCTA` component to periodically refresh the UI state based on session data, improving user experience. - Modified the session API to handle access token verification and expiry more effectively, ensuring accurate session responses. These changes strengthen session handling and enhance the user interface, providing a more reliable authentication experience.
- Updated the Header component to include a dashboard button that is conditionally displayed based on user authentication status. - Implemented session management functions to read, write, and clear session data from localStorage, improving user experience. - Added a script to periodically refresh the dashboard button state, ensuring the UI remains in sync with the user's authentication status. These changes enhance the dashboard button's visibility and improve session handling, providing a more dynamic user interface.
- Added a new cookies.txt file to manage HTTP cookies generated by the application. - Updated the logout process to return an intermediate page that clears localStorage before redirecting to Scalekit, enhancing user experience during logout. - Modified the refresh endpoint to scope the refresh token cookie to the '/auth/refresh' path, improving security by limiting cookie access. These changes enhance session management and improve cookie handling, providing a more secure and user-friendly authentication experience.
…ogout functionality - Replaced user icon with a logout icon in the profile menu for better clarity. - Enhanced profile menu to display user name and email, improving user experience. - Added functions to normalize and retrieve user name and email from session data. - Updated styles for profile elements to enhance visual consistency and accessibility. These changes improve the user interface of the AuthCTA component, providing a clearer logout option and better user information display.
- Introduced a new support hash mechanism to improve user identification and session management within the Pylon widget. - Updated the Pylon widget script to cache and retrieve the support hash from localStorage, enhancing performance and user experience. - Modified the API endpoint to return both support and email hashes for better identity verification. - Improved error handling and session validation during widget initialization to provide clearer feedback. These changes strengthen the integration of the Pylon widget, enhance user experience, and improve overall session management.
- Added logging functionality to the middleware and auth callback to capture key events and data for debugging purposes. - Implemented fetch requests to send log data to a local ingestion endpoint, including details about the request and response flow. - Enhanced error handling by logging invalid state scenarios and cookie values, improving traceability during authentication processes. These changes improve the observability of the authentication flow, aiding in troubleshooting and performance monitoring.
There was a problem hiding this comment.
Actionable comments posted: 3
🤖 Fix all issues with AI agents
In `@src/pages/auth/callback.ts`:
- Around line 7-25: The handler contains development-only debug fetch calls
(e.g., the POST to 'http://127.0.0.1:7242' with body containing location:
'callback.ts:entry') that leak request context and will fail in production;
remove these debug blocks from src/pages/auth/callback.ts or wrap them behind a
build-time/runtime gate (e.g., check import.meta.env.DEBUG_AUTH) so they only
run when the env flag is set, and ensure any retained logging strips sensitive
fields (fullUrl, cookies, redirect paths) or uses the app's production
logging/observability pipeline instead; apply the same removal/gating to the
other debug blocks referenced in this file (lines ~38-56, 59-78, 163-176,
189-209) so no localhost POSTs remain in production.
- Around line 235-240: The response currently adds X-Debug-* headers via the
Headers instance (headers.set('X-Debug-CleanRedirect', ...),
headers.set('X-Debug-PostLoginRedirect', ...), headers.set('X-Debug-FinalUrl',
...)); remove those debug headers from production responses by either deleting
those headers entirely or wrapping their creation in a development-only guard
(e.g., check an isDev / NODE_ENV !== 'production' flag) so only the Location
header (headers.set('Location', finalRedirectUrl)) and Set-Cookie entries from
cookieHeaders are always sent; update the code around the headers variable and
the uses of cleanRedirect, postLoginRedirect, and finalRedirectUrl accordingly.
- Around line 125-158: The code is setting cookies twice (using
context.cookies.set(...) and also building manual Set-Cookie headers), which can
produce inconsistent headers; choose one approach and remove the other: if you
prefer framework cookie helpers, delete the manual Set-Cookie header
construction (ensure all values from tokenData.access_token, tokenData.id_token,
tokenData.refresh_token and deletions using context.cookies.delete(...) remain
and are used), otherwise remove the context.cookies.set(...) /
context.cookies.delete(...) calls and keep the manual header construction
(ensure names sk_access_token, sk_id_token, sk_refresh_token, sk_pkce_verifier,
sk_pkce_state, sk_post_login_redirect and attributes like httpOnly, secure
(secureCookie), sameSite, path, maxAge/refreshMaxAge are applied correctly).
🧹 Nitpick comments (1)
src/pages/auth/callback.ts (1)
1-6: Add JSDoc documentation for the exported API route.Per coding guidelines, public APIs should have function comments explaining purpose, parameters, and behavior. This route handler lacks documentation.
📝 Suggested documentation
import type { APIRoute } from 'astro' -import { verifyJwt } from '@/utils/auth/jwt' export const prerender = false +/** + * OAuth PKCE callback handler. + * Exchanges authorization code for tokens, validates PKCE state, + * sets secure cookies, and redirects to the post-login destination. + * + * `@param` context - Astro API context containing URL params and cookies + * `@returns` 302 redirect response with token cookies set + */ export const GET: APIRoute = async (context) => {
📜 Review details
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (2)
src/middleware.tssrc/pages/auth/callback.ts
🚧 Files skipped from review as they are similar to previous changes (1)
- src/middleware.ts
🧰 Additional context used
📓 Path-based instructions (4)
**/*.{js,ts,py,go,java,tsx,jsx}
📄 CodeRabbit inference engine (CLAUDE.md)
SDK variable names must follow language-specific conventions: Node.js uses
scalekit, Python usesscalekit_client, Go usesscalekitClient, Java usesscalekitClient
Files:
src/pages/auth/callback.ts
**/*.{js,ts,tsx,jsx,py,java,cs,go,cpp,c,rb,php,swift,kt,scala,rs,m,mm,groovy,gradle,xml,json}
📄 CodeRabbit inference engine (.cursor/rules/comment-standards.mdc)
Comments should not duplicate the code - avoid comments that simply restate what the code does; comments should add value beyond what's obvious from reading the code
Files:
src/pages/auth/callback.ts
**/*.{js,ts,tsx,jsx,py,java,cs,go,cpp,c,rb,php,swift,kt,scala,rs,m,mm,groovy}
📄 CodeRabbit inference engine (.cursor/rules/comment-standards.mdc)
**/*.{js,ts,tsx,jsx,py,java,cs,go,cpp,c,rb,php,swift,kt,scala,rs,m,mm,groovy}: Good comments do not excuse unclear code - refactor the code to be self-explanatory instead of using comments to explain poorly written code; use better variable names, function names, and code structure
Comments should dispel confusion, not cause it - ensure comments clarify rather than obscure the code's purpose; avoid cryptic or joke comments
Explain unidiomatic code in comments - comment on code that might seem unnecessary or redundant and document why you chose a specific pattern over more common alternatives, especially when it deviates from team conventions
Provide links to the original source of copied code - always attribute code copied from external sources with URLs to Stack Overflow answers, GitHub repositories, or documentation
Include links to external references where helpful - reference standards, RFCs, and official documentation; link to relevant specifications when implementing protocols
Add comments when fixing bugs - document bug fixes with context about the issue, reference issue trackers and bug reports, and explain workarounds and their limitations
Use comments to mark incomplete implementations - use standard formats for TODO, FIXME, and NOTE comments with context about what needs to be done and reference issue trackers when possible
Always document public APIs with function/class comments - explain the purpose, parameters, return values, and exceptions; include usage examples for complex functions
Include file headers with copyright information, license, and authorship - provide a brief description of the file's purpose and document dependencies and requirements
Files:
src/pages/auth/callback.ts
**/*.{js,ts,tsx,jsx}
📄 CodeRabbit inference engine (.cursor/rules/comment-standards.mdc)
Use JSDoc standards for all function, class, and complex logic comments in JavaScript/TypeScript - include parameter descriptions (
@param), return values (@returns), types (@type), and descriptions; document exceptions and edge cases
Files:
src/pages/auth/callback.ts
🧠 Learnings (1)
📚 Learning: 2026-01-13T12:46:55.260Z
Learnt from: CR
Repo: scalekit-inc/developer-docs PR: 0
File: .cursorrules:0-0
Timestamp: 2026-01-13T12:46:55.260Z
Learning: Applies to **/*.mdx : Include context comments explaining what's happening in code: '// Extract encrypted tokens from request cookies', '// Decrypt the access token before validation'
Applied to files:
src/pages/auth/callback.ts
🧬 Code graph analysis (1)
src/pages/auth/callback.ts (2)
src/pages/auth/session.ts (1)
GET(6-117)src/pages/auth/login.ts (1)
GET(6-55)
🪛 Biome (2.3.13)
src/pages/auth/callback.ts
[error] 240-240: This callback passed to forEach() iterable method should not return a value.
Either remove this return or remove the returned value.
(lint/suspicious/useIterableCallbackReturn)
🔇 Additional comments (2)
src/pages/auth/callback.ts (2)
58-80: LGTM!The PKCE state validation logic correctly checks for the presence of all required parameters and verifies state matching to prevent CSRF attacks.
82-86: LGTM!The redirect URL sanitization correctly prevents open redirect attacks by enforcing relative paths, stripping query parameters/fragments, and constructing an absolute URL for Netlify middleware compatibility.
Also applies to: 178-188
✏️ Tip: You can disable this entire section by setting review_details to false in your review settings.
- Removed unnecessary logging functionality from the middleware and auth callback to simplify the codebase. - Updated the auth callback to use a client-side redirect, improving compatibility with Netlify's handling of query parameters. - Enhanced response handling by returning an HTML page for redirects, ensuring a smoother user experience. These changes improve code clarity and maintainability while enhancing the redirect process in the authentication flow.
There was a problem hiding this comment.
Actionable comments posted: 2
🤖 Fix all issues with AI agents
In `@src/pages/auth/callback.ts`:
- Around line 59-78: The secondary open-redirect check around postLoginRedirect
should also reject values starting with "//" (protocol-relative URLs); update
the logic that sets cleanRedirect (after computing pathnameOnly) to ensure it
only allows paths that start with a single leading slash and not a double slash
— e.g., enforce that cleanRedirect startsWith('/') and does not startWith('//'),
otherwise set cleanRedirect = '/'; apply this change where pathnameOnly,
cleanRedirect, redirectUrl and finalRedirectUrl are used so the redirect URL
can't be protocol-relative.
- Around line 23-27: The redirect validation is bypassed by protocol-relative
URLs like "//evil.com/path"; update the check around the postLoginRedirect
variable so you reject any redirect that is not a strict relative path (starts
with a single "/" and NOT with "//") or that resolves to a different origin when
parsed with new URL. Concretely, in the code that currently checks
postLoginRedirect.startsWith('/'), add a guard to reject values starting with
'//' and/or validate by constructing new URL(postLoginRedirect, origin) and
ensuring its origin equals the app origin before allowing it; otherwise set
postLoginRedirect = '/'.
🧹 Nitpick comments (1)
src/pages/auth/callback.ts (1)
104-107: LGTM with minor linter fix.Cookie header construction and response setup is correct. The comments explaining the Netlify workaround are helpful. To silence the Biome linter warning about forEach callback return value, add braces.
♻️ Optional fix for linter
- cookieHeaders.forEach((cookie) => headers.append('Set-Cookie', cookie)) + cookieHeaders.forEach((cookie) => { + headers.append('Set-Cookie', cookie) + })
📜 Review details
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (1)
src/pages/auth/callback.ts
🧰 Additional context used
📓 Path-based instructions (4)
**/*.{js,ts,py,go,java,tsx,jsx}
📄 CodeRabbit inference engine (CLAUDE.md)
SDK variable names must follow language-specific conventions: Node.js uses
scalekit, Python usesscalekit_client, Go usesscalekitClient, Java usesscalekitClient
Files:
src/pages/auth/callback.ts
**/*.{js,ts,tsx,jsx,py,java,cs,go,cpp,c,rb,php,swift,kt,scala,rs,m,mm,groovy,gradle,xml,json}
📄 CodeRabbit inference engine (.cursor/rules/comment-standards.mdc)
Comments should not duplicate the code - avoid comments that simply restate what the code does; comments should add value beyond what's obvious from reading the code
Files:
src/pages/auth/callback.ts
**/*.{js,ts,tsx,jsx,py,java,cs,go,cpp,c,rb,php,swift,kt,scala,rs,m,mm,groovy}
📄 CodeRabbit inference engine (.cursor/rules/comment-standards.mdc)
**/*.{js,ts,tsx,jsx,py,java,cs,go,cpp,c,rb,php,swift,kt,scala,rs,m,mm,groovy}: Good comments do not excuse unclear code - refactor the code to be self-explanatory instead of using comments to explain poorly written code; use better variable names, function names, and code structure
Comments should dispel confusion, not cause it - ensure comments clarify rather than obscure the code's purpose; avoid cryptic or joke comments
Explain unidiomatic code in comments - comment on code that might seem unnecessary or redundant and document why you chose a specific pattern over more common alternatives, especially when it deviates from team conventions
Provide links to the original source of copied code - always attribute code copied from external sources with URLs to Stack Overflow answers, GitHub repositories, or documentation
Include links to external references where helpful - reference standards, RFCs, and official documentation; link to relevant specifications when implementing protocols
Add comments when fixing bugs - document bug fixes with context about the issue, reference issue trackers and bug reports, and explain workarounds and their limitations
Use comments to mark incomplete implementations - use standard formats for TODO, FIXME, and NOTE comments with context about what needs to be done and reference issue trackers when possible
Always document public APIs with function/class comments - explain the purpose, parameters, return values, and exceptions; include usage examples for complex functions
Include file headers with copyright information, license, and authorship - provide a brief description of the file's purpose and document dependencies and requirements
Files:
src/pages/auth/callback.ts
**/*.{js,ts,tsx,jsx}
📄 CodeRabbit inference engine (.cursor/rules/comment-standards.mdc)
Use JSDoc standards for all function, class, and complex logic comments in JavaScript/TypeScript - include parameter descriptions (
@param), return values (@returns), types (@type), and descriptions; document exceptions and edge cases
Files:
src/pages/auth/callback.ts
🧠 Learnings (1)
📚 Learning: 2026-01-13T12:46:55.260Z
Learnt from: CR
Repo: scalekit-inc/developer-docs PR: 0
File: .cursorrules:0-0
Timestamp: 2026-01-13T12:46:55.260Z
Learning: Applies to **/*.mdx : Include context comments explaining what's happening in code: '// Extract encrypted tokens from request cookies', '// Decrypt the access token before validation'
Applied to files:
src/pages/auth/callback.ts
🪛 Biome (2.3.13)
src/pages/auth/callback.ts
[error] 107-107: This callback passed to forEach() iterable method should not return a value.
Either remove this return or remove the returned value.
(lint/suspicious/useIterableCallbackReturn)
🔇 Additional comments (5)
src/pages/auth/callback.ts (5)
1-4: LGTM!Clean imports and correct SSR configuration with
prerender = false.
6-10: Placeholder URL fallback may mask configuration errors.The fallback to
'https://placeholder.scalekit.com/oauth/token'and empty string forclientIdcould cause confusing failures in production. Consider failing explicitly when required environment variables are not configured.🔧 Suggested improvement
- const tokenUrl = - import.meta.env.SCALEKIT_TOKEN_URL ?? 'https://placeholder.scalekit.com/oauth/token' - const clientId = import.meta.env.SCALEKIT_CLIENT_ID ?? '' + const tokenUrl = import.meta.env.SCALEKIT_TOKEN_URL + const clientId = import.meta.env.SCALEKIT_CLIENT_ID + if (!tokenUrl || !clientId) { + console.error('[auth/callback] Missing required env: SCALEKIT_TOKEN_URL or SCALEKIT_CLIENT_ID') + return context.redirect('/auth/login?error=misconfigured') + }[raise_minor_issue, duplicate_comment]
29-43: Add timeout and error handling for token exchange fetch.The
fetch()call lacks a timeout and try-catch wrapper. Network errors or unresponsive servers can hang the request indefinitely or throw uncaught exceptions.⏱️ Suggested implementation
+ const controller = new AbortController() + const timeoutId = setTimeout(() => controller.abort(), 10_000) + let tokenResponse: Response + try { - const tokenResponse = await fetch(tokenUrl, { + tokenResponse = await fetch(tokenUrl, { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, body: new URLSearchParams({ grant_type: 'authorization_code', code, redirect_uri: redirectUri, client_id: clientId, code_verifier: codeVerifier, }).toString(), + signal: controller.signal, }) + } catch { + return context.redirect('/auth/login?error=token_exchange_failed') + } finally { + clearTimeout(timeoutId) + }[raise_major_issue, duplicate_comment]
45-57: Wrap JSON parsing in try-catch.The
tokenResponse.json()call at line 45 can throw if the response body is malformed. This should be wrapped in a try-catch to handle parsing failures gracefully.🔧 Suggested fix
+ let tokenData: { + access_token?: string + id_token?: string + refresh_token?: string + expires_in?: number + refresh_token_expires_in?: number + } + try { - const tokenData = (await tokenResponse.json()) as { - access_token?: string - id_token?: string - refresh_token?: string - expires_in?: number - refresh_token_expires_in?: number - } + tokenData = await tokenResponse.json() + } catch { + return context.redirect('/auth/login?error=token_exchange_failed') + }[raise_major_issue, duplicate_comment]
109-126: LGTM!The HTML redirect approach with meta refresh + JS fallback is a sensible workaround for the Netlify middleware issue. The comment at lines 109-111 properly documents the reasoning.
✏️ Tip: You can disable this entire section by setting review_details to false in your review settings.
- Temporarily commented out the code responsible for fetching the support hash from the API. - Added a TODO note indicating the need for a method to retrieve the support hash on auth.scalekit.com. - This change prepares the code for future enhancements while maintaining current functionality.
There was a problem hiding this comment.
Actionable comments posted: 1
🤖 Fix all issues with AI agents
In `@src/pages/api/v1/users/support-hash.ts`:
- Around line 6-67: The GET handler (export const GET) can fall through without
returning a Response if the commented TODO code remains disabled; ensure the
route always returns a Response by adding a safe fallback return at the end of
the function (for example a 501/500 or a JSON payload indicating the feature is
unavailable) so every execution path in GET returns a Response; locate the token
verification logic (verifyJwt) and the supportHashUrl construction and append a
final return new Response(...) that mirrors the existing response shape
(Content-Type: application/json and an error or placeholder
support_hash/email_hash) to prevent runtime errors.
🧹 Nitpick comments (2)
src/pages/api/v1/users/support-hash.ts (2)
1-6: Add required file header and JSDoc for the public API route.This file lacks the required header and the exported public API route lacks JSDoc (params/returns/exceptions). Also consider removing the redundant inline comment at Line 16 once JSDoc is added.
As per coding guidelines: “Include file headers with copyright information, license, and authorship - provide a brief description of the file's purpose and document dependencies and requirements” and “Always document public APIs with function/class comments - explain the purpose, parameters, return values, and exceptions; include usage examples for complex functions” and “Use JSDoc standards for all function, class, and complex logic comments in JavaScript/TypeScript - include parameter descriptions (`@param`), return values (`@returns`), types (`@type`), and descriptions; document exceptions and edge cases”.📝 Suggested documentation additions
+/** + * Copyright (c) 2026 ScaleKit + * License: <license-name> + * Author: <author-or-team> + * + * Purpose: API route for support-hash proxying. + * Dependencies: astro (APIRoute), `@/utils/auth/jwt` (verifyJwt) + * Requirements: SCALEKIT_AUTHORIZE_URL env var. + */ import type { APIRoute } from 'astro' import { verifyJwt } from '@/utils/auth/jwt' export const prerender = false +/** + * GET /api/v1/users/support-hash + * + * Validates the `sk_access_token` cookie and (when enabled) proxies the + * support hash from the auth service. + * + * `@param` context - Astro API route context. + * `@returns` JSON response with support_hash or an error payload. + * `@throws` Returns 401 for missing/invalid tokens. + * `@example` + * // curl -H 'Cookie: sk_access_token=...' https://<host>/api/v1/users/support-hash + */ export const GET: APIRoute = async (context) => {
37-37: Use a standard TODO format with issue reference.The TODO lacks an issue reference and ownership context.
As per coding guidelines: “Use comments to mark incomplete implementations - use standard formats for TODO, FIXME, and NOTE comments with context about what needs to be done and reference issue trackers when possible”.🧭 TODO format suggestion
- // TODO: Uncomment this when we have a way to get the support hash on auth.scalekit.com + // TODO(`#1234`): Uncomment when auth.scalekit.com exposes support-hash; update once issue is resolved.
📜 Review details
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (1)
src/pages/api/v1/users/support-hash.ts
🧰 Additional context used
📓 Path-based instructions (4)
**/*.{js,ts,py,go,java,tsx,jsx}
📄 CodeRabbit inference engine (CLAUDE.md)
SDK variable names must follow language-specific conventions: Node.js uses
scalekit, Python usesscalekit_client, Go usesscalekitClient, Java usesscalekitClient
Files:
src/pages/api/v1/users/support-hash.ts
**/*.{js,ts,tsx,jsx,py,java,cs,go,cpp,c,rb,php,swift,kt,scala,rs,m,mm,groovy,gradle,xml,json}
📄 CodeRabbit inference engine (.cursor/rules/comment-standards.mdc)
Comments should not duplicate the code - avoid comments that simply restate what the code does; comments should add value beyond what's obvious from reading the code
Files:
src/pages/api/v1/users/support-hash.ts
**/*.{js,ts,tsx,jsx,py,java,cs,go,cpp,c,rb,php,swift,kt,scala,rs,m,mm,groovy}
📄 CodeRabbit inference engine (.cursor/rules/comment-standards.mdc)
**/*.{js,ts,tsx,jsx,py,java,cs,go,cpp,c,rb,php,swift,kt,scala,rs,m,mm,groovy}: Good comments do not excuse unclear code - refactor the code to be self-explanatory instead of using comments to explain poorly written code; use better variable names, function names, and code structure
Comments should dispel confusion, not cause it - ensure comments clarify rather than obscure the code's purpose; avoid cryptic or joke comments
Explain unidiomatic code in comments - comment on code that might seem unnecessary or redundant and document why you chose a specific pattern over more common alternatives, especially when it deviates from team conventions
Provide links to the original source of copied code - always attribute code copied from external sources with URLs to Stack Overflow answers, GitHub repositories, or documentation
Include links to external references where helpful - reference standards, RFCs, and official documentation; link to relevant specifications when implementing protocols
Add comments when fixing bugs - document bug fixes with context about the issue, reference issue trackers and bug reports, and explain workarounds and their limitations
Use comments to mark incomplete implementations - use standard formats for TODO, FIXME, and NOTE comments with context about what needs to be done and reference issue trackers when possible
Always document public APIs with function/class comments - explain the purpose, parameters, return values, and exceptions; include usage examples for complex functions
Include file headers with copyright information, license, and authorship - provide a brief description of the file's purpose and document dependencies and requirements
Files:
src/pages/api/v1/users/support-hash.ts
**/*.{js,ts,tsx,jsx}
📄 CodeRabbit inference engine (.cursor/rules/comment-standards.mdc)
Use JSDoc standards for all function, class, and complex logic comments in JavaScript/TypeScript - include parameter descriptions (
@param), return values (@returns), types (@type), and descriptions; document exceptions and edge cases
Files:
src/pages/api/v1/users/support-hash.ts
🧠 Learnings (1)
📚 Learning: 2026-01-13T12:46:55.260Z
Learnt from: CR
Repo: scalekit-inc/developer-docs PR: 0
File: .cursorrules:0-0
Timestamp: 2026-01-13T12:46:55.260Z
Learning: Applies to **/*.mdx : Include context comments explaining what's happening in code: '// Extract encrypted tokens from request cookies', '// Decrypt the access token before validation'
Applied to files:
src/pages/api/v1/users/support-hash.ts
🧬 Code graph analysis (1)
src/pages/api/v1/users/support-hash.ts (1)
src/utils/auth/jwt.ts (1)
verifyJwt(196-222)
✏️ Tip: You can disable this entire section by setting review_details to false in your review settings.
- Commented out the code responsible for fetching the support hash from the API until the backend is ready for deployment. - Added TODO notes indicating the need to uncomment the code when the API is operational. - Updated the response handling to return a 503 status, indicating that the service is temporarily unavailable. These changes ensure that the code remains functional while awaiting backend readiness, maintaining clarity for future implementation.
There was a problem hiding this comment.
Actionable comments posted: 6
🤖 Fix all issues with AI agents
In `@public/js/pylon-widget.js`:
- Around line 1-8: The file header for the Pylon chat widget is missing required
metadata; add a top-of-file comment block that includes copyright owner and
year, an appropriate license identifier (e.g., MIT/BSD/Apache),
author/maintainer name or team, purpose/description (you can keep the existing
"Pylon Chat Widget Configuration" summary), and any dependencies or references
(e.g., link to Pylon docs). Place this metadata above the existing comment block
so the file begins with the new header comment and keep the existing purpose and
reference lines (retain the "Pylon Chat Widget Configuration" text and the docs
URL) for clarity.
- Around line 17-29: Convert the existing block comments to JSDoc for all
functions in this file: for getSession(), replace the current comment with a
JSDoc block that documents the function, its return type (e.g., `@returns`
{{...}|null} or `@returns` {Object|null}), and describes behavior on parse
failure; do the same for every other function in public/js/pylon-widget.js (use
each function name like getSession, [otherFunctionName]) adding appropriate
`@param` tags for parameters and `@returns` tags for return values so tooling and
linters recognize the types and descriptions. Ensure each JSDoc is directly
above the function declaration and uses standard JSDoc syntax (/** ... */)
including brief description, `@param` entries for each parameter, and `@returns` for
the return type.
- Around line 61-66: The TODO in function fetchEmailHash lacks context and a
tracking reference; update the comment above and the inline TODO in
fetchEmailHash to include a ticket/issue ID (e.g., `#1234` or SPRINT-567) and a
precise re-enable condition such as "re-enable when backend endpoint
/api/email-hash is implemented and returns 200 with {email_hash:string}". Also
state any required contract (HTTP method, response shape) and testing criteria
(integration test or QA sign-off) so reviewers know exactly when to uncomment
the API call.
In `@src/pages/api/v1/users/support-hash.ts`:
- Around line 1-2: Add the mandated file header metadata at the top of this
module: include copyright, license, authorship, file purpose/description, and
dependency notes for the imports (APIRoute and verifyJwt) as a multi-line
comment block before any imports; ensure the header follows project conventions
(fields and formatting) so tools/readers can validate it and do not alter
existing imports or code (keep the existing import lines for APIRoute and
verifyJwt intact).
- Around line 32-39: Replace the informal TODO comments around the API URL
construction (authorizeUrl, baseUrl, supportHashUrl) and the commented out try
block with the project's standard TODO format including a tracking reference
(e.g., JIRA/ISSUE-#### or GH-####), a short description of why the feature is
disabled, the condition for re-enabling (e.g., "when SCALEKIT_AUTHORIZE_URL
points to production and /oauth/authorize endpoint exists"), and a link or
reference to the upstream task; keep the variable names authorizeUrl, baseUrl,
and supportHashUrl and the surrounding try block intact so reviewers can
re-enable by removing the TODO and uncommenting once the referenced issue is
resolved.
- Line 6: Add a JSDoc block above the exported handler GET (typed as APIRoute)
that documents the handler purpose, the context parameter (describe request,
params, and any relevant properties on context) using `@param` {APIRouteContext}
context, and the return value using `@returns` {Promise<Response>} (or the actual
response type), plus any thrown errors or side effects; keep the description
concise and include examples of expected input or behavior if helpful.
📜 Review details
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (2)
public/js/pylon-widget.jssrc/pages/api/v1/users/support-hash.ts
🧰 Additional context used
📓 Path-based instructions (4)
**/*.{js,ts,py,go,java,tsx,jsx}
📄 CodeRabbit inference engine (CLAUDE.md)
SDK variable names must follow language-specific conventions: Node.js uses
scalekit, Python usesscalekit_client, Go usesscalekitClient, Java usesscalekitClient
Files:
src/pages/api/v1/users/support-hash.tspublic/js/pylon-widget.js
**/*.{js,ts,tsx,jsx,py,java,cs,go,cpp,c,rb,php,swift,kt,scala,rs,m,mm,groovy,gradle,xml,json}
📄 CodeRabbit inference engine (.cursor/rules/comment-standards.mdc)
Comments should not duplicate the code - avoid comments that simply restate what the code does; comments should add value beyond what's obvious from reading the code
Files:
src/pages/api/v1/users/support-hash.tspublic/js/pylon-widget.js
**/*.{js,ts,tsx,jsx,py,java,cs,go,cpp,c,rb,php,swift,kt,scala,rs,m,mm,groovy}
📄 CodeRabbit inference engine (.cursor/rules/comment-standards.mdc)
**/*.{js,ts,tsx,jsx,py,java,cs,go,cpp,c,rb,php,swift,kt,scala,rs,m,mm,groovy}: Good comments do not excuse unclear code - refactor the code to be self-explanatory instead of using comments to explain poorly written code; use better variable names, function names, and code structure
Comments should dispel confusion, not cause it - ensure comments clarify rather than obscure the code's purpose; avoid cryptic or joke comments
Explain unidiomatic code in comments - comment on code that might seem unnecessary or redundant and document why you chose a specific pattern over more common alternatives, especially when it deviates from team conventions
Provide links to the original source of copied code - always attribute code copied from external sources with URLs to Stack Overflow answers, GitHub repositories, or documentation
Include links to external references where helpful - reference standards, RFCs, and official documentation; link to relevant specifications when implementing protocols
Add comments when fixing bugs - document bug fixes with context about the issue, reference issue trackers and bug reports, and explain workarounds and their limitations
Use comments to mark incomplete implementations - use standard formats for TODO, FIXME, and NOTE comments with context about what needs to be done and reference issue trackers when possible
Always document public APIs with function/class comments - explain the purpose, parameters, return values, and exceptions; include usage examples for complex functions
Include file headers with copyright information, license, and authorship - provide a brief description of the file's purpose and document dependencies and requirements
Files:
src/pages/api/v1/users/support-hash.tspublic/js/pylon-widget.js
**/*.{js,ts,tsx,jsx}
📄 CodeRabbit inference engine (.cursor/rules/comment-standards.mdc)
Use JSDoc standards for all function, class, and complex logic comments in JavaScript/TypeScript - include parameter descriptions (
@param), return values (@returns), types (@type), and descriptions; document exceptions and edge cases
Files:
src/pages/api/v1/users/support-hash.tspublic/js/pylon-widget.js
🧠 Learnings (1)
📚 Learning: 2026-01-13T12:46:55.260Z
Learnt from: CR
Repo: scalekit-inc/developer-docs PR: 0
File: .cursorrules:0-0
Timestamp: 2026-01-13T12:46:55.260Z
Learning: Applies to **/*.mdx : Include context comments explaining what's happening in code: '// Extract encrypted tokens from request cookies', '// Decrypt the access token before validation'
Applied to files:
src/pages/api/v1/users/support-hash.ts
🧬 Code graph analysis (2)
src/pages/api/v1/users/support-hash.ts (1)
src/utils/auth/jwt.ts (1)
verifyJwt(196-222)
public/js/pylon-widget.js (2)
src/utils/auth/session-client.ts (1)
getSession(44-88)public/js/posthog.js (4)
session(23-23)uid(26-26)xoid(27-27)attempts(53-53)
✏️ Tip: You can disable this entire section by setting review_details to false in your review settings.
| /** | ||
| * Helper to safely get session from localStorage | ||
| */ | ||
| var getSession = function () { | ||
| try { | ||
| var raw = localStorage.getItem('sk_auth_session') | ||
| if (!raw) return null | ||
| var session = JSON.parse(raw) | ||
| return session && typeof session === 'object' ? session : null | ||
| } catch (e) { | ||
| return null | ||
| } | ||
| } |
There was a problem hiding this comment.
Convert function comments to JSDoc.
JS/TS function comments must use JSDoc with @param/@returns; apply to all functions in this file.
📄 Example for getSession
- /**
- * Helper to safely get session from localStorage
- */
+ /**
+ * Safely read the cached auth session from localStorage.
+ * `@returns` {object|null} Parsed session object or null on failure.
+ */
var getSession = function () {🤖 Prompt for AI Agents
In `@public/js/pylon-widget.js` around lines 17 - 29, Convert the existing block
comments to JSDoc for all functions in this file: for getSession(), replace the
current comment with a JSDoc block that documents the function, its return type
(e.g., `@returns` {{...}|null} or `@returns` {Object|null}), and describes behavior
on parse failure; do the same for every other function in
public/js/pylon-widget.js (use each function name like getSession,
[otherFunctionName]) adding appropriate `@param` tags for parameters and `@returns`
tags for return values so tooling and linters recognize the types and
descriptions. Ensure each JSDoc is directly above the function declaration and
uses standard JSDoc syntax (/** ... */) including brief description, `@param`
entries for each parameter, and `@returns` for the return type.
| import type { APIRoute } from 'astro' | ||
| import { verifyJwt } from '@/utils/auth/jwt' |
There was a problem hiding this comment.
Add the required file header metadata.
Missing the mandated header (copyright, license, authorship, purpose, dependencies).
🔧 Suggested header
+/**
+ * Copyright (c) 2026 ScaleKit, Inc.
+ * License: [License]
+ * Authors: [Team/Author]
+ *
+ * Purpose: Support-hash API route (temporary 503 until backend is ready).
+ * Dependencies: Astro APIRoute, verifyJwt
+ */
import type { APIRoute } from 'astro'
import { verifyJwt } from '@/utils/auth/jwt'📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| import type { APIRoute } from 'astro' | |
| import { verifyJwt } from '@/utils/auth/jwt' | |
| /** | |
| * Copyright (c) 2026 ScaleKit, Inc. | |
| * License: [License] | |
| * Authors: [Team/Author] | |
| * | |
| * Purpose: Support-hash API route (temporary 503 until backend is ready). | |
| * Dependencies: Astro APIRoute, verifyJwt | |
| */ | |
| import type { APIRoute } from 'astro' | |
| import { verifyJwt } from '@/utils/auth/jwt' |
🤖 Prompt for AI Agents
In `@src/pages/api/v1/users/support-hash.ts` around lines 1 - 2, Add the mandated
file header metadata at the top of this module: include copyright, license,
authorship, file purpose/description, and dependency notes for the imports
(APIRoute and verifyJwt) as a multi-line comment block before any imports;
ensure the header follows project conventions (fields and formatting) so
tools/readers can validate it and do not alter existing imports or code (keep
the existing import lines for APIRoute and verifyJwt intact).
|
|
||
| export const prerender = false | ||
|
|
||
| export const GET: APIRoute = async (context) => { |
There was a problem hiding this comment.
Add JSDoc for the exported GET handler.
This is a public API surface and should be documented with @param/@returns.
📄 JSDoc example
-export const GET: APIRoute = async (context) => {
+/**
+ * GET /api/v1/users/support-hash
+ * Validates access token and returns 503 until the support-hash API is live.
+ * `@param` {import('astro').APIContext} context
+ * `@returns` {Promise<Response>}
+ */
+export const GET: APIRoute = async (context) => {📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| export const GET: APIRoute = async (context) => { | |
| /** | |
| * GET /api/v1/users/support-hash | |
| * Validates access token and returns 503 until the support-hash API is live. | |
| * `@param` {import('astro').APIContext} context | |
| * `@returns` {Promise<Response>} | |
| */ | |
| export const GET: APIRoute = async (context) => { |
🤖 Prompt for AI Agents
In `@src/pages/api/v1/users/support-hash.ts` at line 6, Add a JSDoc block above
the exported handler GET (typed as APIRoute) that documents the handler purpose,
the context parameter (describe request, params, and any relevant properties on
context) using `@param` {APIRouteContext} context, and the return value using
`@returns` {Promise<Response>} (or the actual response type), plus any thrown
errors or side effects; keep the description concise and include examples of
expected input or behavior if helpful.
- Uncommented the code responsible for fetching the support hash from the backend API, allowing for identity verification. - Updated the response handling to return the support hash or email hash as needed, improving user identification. - Added a minimal configuration for anonymous users to ensure the widget can load even without an authenticated session. These changes enhance the functionality of the Pylon widget by integrating support hash retrieval, improving user experience and session management.
- Uncommented the code for fetching the support hash from the backend API, enabling identity verification. - Enhanced response handling to return the appropriate support or email hash, improving user identification. - Ensured minimal configuration for anonymous users, allowing the widget to load without an authenticated session. These updates enhance the Pylon widget's functionality by re-integrating support hash retrieval, thereby improving user experience and session management.
- Added logic to handle OAuth error responses, specifically for 'login_required' scenarios. - Constructed a login URL without the prompt=none parameter to redirect users when they are not logged in. - Implemented PKCE (Proof Key for Code Exchange) support by generating code verifiers and challenges, improving security during the authentication process. - Updated the login URL to ensure it points to the correct authorization endpoint. These changes improve the user experience by providing a seamless login flow and enhancing security measures in the authentication process.
There was a problem hiding this comment.
Actionable comments posted: 3
🤖 Fix all issues with AI agents
In `@src/pages/auth/callback.ts`:
- Around line 1-2: This file is missing the required file header metadata; add a
top-of-file comment block in src/pages/auth/callback.ts that includes copyright
notice, license, author(s), a short description of the module's purpose
(handling auth callback / PKCE flow), and document dependencies/requirements
such as its use of genCodeChallenge, genCodeVerifier, and genRandomString
imported from '@/utils/auth/pkce' as well as any environment or runtime
expectations; place this header before the import statements and ensure it
follows the project's header template/format.
- Line 6: Add a JSDoc block immediately above the exported public handler "GET"
(the declaration export const GET: APIRoute = async (context) => { ... }) that
documents the handler's purpose, the "context" parameter (describe shape or link
to APIRoute/context types), the return value (what response or Response/JSON it
returns), and any possible errors or edge cases it may throw or handle; include
`@param` for context, `@returns` for the response, and a brief usage/example line
showing how the route is invoked. Ensure the comment follows JSDoc syntax and
references the APIRoute contract so future readers know the expected types and
error behavior.
- Line 144: The forEach callback on cookieHeaders uses a concise arrow body
without braces; update it to use a block statement to match codebase style by
changing the callback for cookieHeaders.forEach to a block-bodied arrow function
and move the headers.append('Set-Cookie', cookie) call inside that block
(preserve the same behavior and variable names).
📜 Review details
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro
⛔ Files ignored due to path filters (1)
src/assets/docs/group-based-role-assignment/roles-and-permissions.pngis excluded by!**/*.png
📒 Files selected for processing (4)
public/js/pylon-widget.jssrc/pages/api/v1/users/support-hash.tssrc/pages/auth/callback.tssrc/pages/auth/login.ts
🚧 Files skipped from review as they are similar to previous changes (1)
- src/pages/auth/login.ts
🧰 Additional context used
📓 Path-based instructions (4)
**/*.{js,ts,py,go,java,tsx,jsx}
📄 CodeRabbit inference engine (CLAUDE.md)
SDK variable names must follow language-specific conventions: Node.js uses
scalekit, Python usesscalekit_client, Go usesscalekitClient, Java usesscalekitClient
Files:
src/pages/api/v1/users/support-hash.tspublic/js/pylon-widget.jssrc/pages/auth/callback.ts
**/*.{js,ts,tsx,jsx,py,java,cs,go,cpp,c,rb,php,swift,kt,scala,rs,m,mm,groovy,gradle,xml,json}
📄 CodeRabbit inference engine (.cursor/rules/comment-standards.mdc)
Comments should not duplicate the code - avoid comments that simply restate what the code does; comments should add value beyond what's obvious from reading the code
Files:
src/pages/api/v1/users/support-hash.tspublic/js/pylon-widget.jssrc/pages/auth/callback.ts
**/*.{js,ts,tsx,jsx,py,java,cs,go,cpp,c,rb,php,swift,kt,scala,rs,m,mm,groovy}
📄 CodeRabbit inference engine (.cursor/rules/comment-standards.mdc)
**/*.{js,ts,tsx,jsx,py,java,cs,go,cpp,c,rb,php,swift,kt,scala,rs,m,mm,groovy}: Good comments do not excuse unclear code - refactor the code to be self-explanatory instead of using comments to explain poorly written code; use better variable names, function names, and code structure
Comments should dispel confusion, not cause it - ensure comments clarify rather than obscure the code's purpose; avoid cryptic or joke comments
Explain unidiomatic code in comments - comment on code that might seem unnecessary or redundant and document why you chose a specific pattern over more common alternatives, especially when it deviates from team conventions
Provide links to the original source of copied code - always attribute code copied from external sources with URLs to Stack Overflow answers, GitHub repositories, or documentation
Include links to external references where helpful - reference standards, RFCs, and official documentation; link to relevant specifications when implementing protocols
Add comments when fixing bugs - document bug fixes with context about the issue, reference issue trackers and bug reports, and explain workarounds and their limitations
Use comments to mark incomplete implementations - use standard formats for TODO, FIXME, and NOTE comments with context about what needs to be done and reference issue trackers when possible
Always document public APIs with function/class comments - explain the purpose, parameters, return values, and exceptions; include usage examples for complex functions
Include file headers with copyright information, license, and authorship - provide a brief description of the file's purpose and document dependencies and requirements
Files:
src/pages/api/v1/users/support-hash.tspublic/js/pylon-widget.jssrc/pages/auth/callback.ts
**/*.{js,ts,tsx,jsx}
📄 CodeRabbit inference engine (.cursor/rules/comment-standards.mdc)
Use JSDoc standards for all function, class, and complex logic comments in JavaScript/TypeScript - include parameter descriptions (
@param), return values (@returns), types (@type), and descriptions; document exceptions and edge cases
Files:
src/pages/api/v1/users/support-hash.tspublic/js/pylon-widget.jssrc/pages/auth/callback.ts
🧠 Learnings (11)
📚 Learning: 2026-01-13T12:46:55.260Z
Learnt from: CR
Repo: scalekit-inc/developer-docs PR: 0
File: .cursorrules:0-0
Timestamp: 2026-01-13T12:46:55.260Z
Learning: Applies to **/*.mdx : Include context comments explaining what's happening in code: '// Extract encrypted tokens from request cookies', '// Decrypt the access token before validation'
Applied to files:
src/pages/api/v1/users/support-hash.tspublic/js/pylon-widget.jssrc/pages/auth/callback.ts
📚 Learning: 2026-01-13T12:47:33.407Z
Learnt from: CR
Repo: scalekit-inc/developer-docs PR: 0
File: .cursor/rules/comment-standards.mdc:0-0
Timestamp: 2026-01-13T12:47:33.407Z
Learning: Applies to **/*.{js,ts,tsx,jsx,py,java,cs,go,cpp,c,rb,php,swift,kt,scala,rs,m,mm,groovy} : Include file headers with copyright information, license, and authorship - provide a brief description of the file's purpose and document dependencies and requirements
Applied to files:
src/pages/api/v1/users/support-hash.tspublic/js/pylon-widget.js
📚 Learning: 2026-01-13T12:46:55.260Z
Learnt from: CR
Repo: scalekit-inc/developer-docs PR: 0
File: .cursorrules:0-0
Timestamp: 2026-01-13T12:46:55.260Z
Learning: Applies to **/*.mdx : Always include security comments in security-related code with pattern: '// Security: ALWAYS verify requests are from Scalekit before processing'
Applied to files:
src/pages/api/v1/users/support-hash.ts
📚 Learning: 2026-01-13T12:46:55.260Z
Learnt from: CR
Repo: scalekit-inc/developer-docs PR: 0
File: .cursorrules:0-0
Timestamp: 2026-01-13T12:46:55.260Z
Learning: Applies to **/*.mdx : Include configuration comments in code examples: '// Get the signing secret from Scalekit dashboard > Interceptors tab'
Applied to files:
src/pages/api/v1/users/support-hash.ts
📚 Learning: 2026-01-13T12:47:33.407Z
Learnt from: CR
Repo: scalekit-inc/developer-docs PR: 0
File: .cursor/rules/comment-standards.mdc:0-0
Timestamp: 2026-01-13T12:47:33.407Z
Learning: Applies to **/*.{js,ts,tsx,jsx} : Use JSDoc standards for all function, class, and complex logic comments in JavaScript/TypeScript - include parameter descriptions (param), return values (returns), types (type), and descriptions; document exceptions and edge cases
Applied to files:
src/pages/api/v1/users/support-hash.tspublic/js/pylon-widget.js
📚 Learning: 2026-01-13T12:47:33.407Z
Learnt from: CR
Repo: scalekit-inc/developer-docs PR: 0
File: .cursor/rules/comment-standards.mdc:0-0
Timestamp: 2026-01-13T12:47:33.407Z
Learning: Applies to **/*.{js,ts,tsx,jsx,py,java,cs,go,cpp,c,rb,php,swift,kt,scala,rs,m,mm,groovy} : Use comments to mark incomplete implementations - use standard formats for TODO, FIXME, and NOTE comments with context about what needs to be done and reference issue trackers when possible
Applied to files:
src/pages/api/v1/users/support-hash.tspublic/js/pylon-widget.js
📚 Learning: 2026-01-13T12:46:55.260Z
Learnt from: CR
Repo: scalekit-inc/developer-docs PR: 0
File: .cursorrules:0-0
Timestamp: 2026-01-13T12:46:55.260Z
Learning: Applies to **/*.mdx : Include todo/next step comments in code examples: '// TODO: Store user session (next guide covers this)', '// Next step: Create a session and log in the user'
Applied to files:
src/pages/api/v1/users/support-hash.ts
📚 Learning: 2026-01-13T12:47:33.407Z
Learnt from: CR
Repo: scalekit-inc/developer-docs PR: 0
File: .cursor/rules/comment-standards.mdc:0-0
Timestamp: 2026-01-13T12:47:33.407Z
Learning: Do not leave TODO comments without context - do not copy code without attribution; do not use comments to disable code (use version control instead)
Applied to files:
src/pages/api/v1/users/support-hash.tspublic/js/pylon-widget.js
📚 Learning: 2026-01-13T12:47:33.407Z
Learnt from: CR
Repo: scalekit-inc/developer-docs PR: 0
File: .cursor/rules/comment-standards.mdc:0-0
Timestamp: 2026-01-13T12:47:33.407Z
Learning: Applies to **/*.{js,ts,tsx,jsx,py,java,cs,go,cpp,c,rb,php,swift,kt,scala,rs,m,mm,groovy} : Add comments when fixing bugs - document bug fixes with context about the issue, reference issue trackers and bug reports, and explain workarounds and their limitations
Applied to files:
public/js/pylon-widget.js
📚 Learning: 2026-01-13T12:47:33.407Z
Learnt from: CR
Repo: scalekit-inc/developer-docs PR: 0
File: .cursor/rules/comment-standards.mdc:0-0
Timestamp: 2026-01-13T12:47:33.407Z
Learning: Applies to **/*.{js,ts,tsx,jsx,py,java,cs,go,cpp,c,rb,php,swift,kt,scala,rs,m,mm,groovy} : Always document public APIs with function/class comments - explain the purpose, parameters, return values, and exceptions; include usage examples for complex functions
Applied to files:
public/js/pylon-widget.js
📚 Learning: 2026-01-13T12:47:33.407Z
Learnt from: CR
Repo: scalekit-inc/developer-docs PR: 0
File: .cursor/rules/comment-standards.mdc:0-0
Timestamp: 2026-01-13T12:47:33.407Z
Learning: Applies to **/*.{js,ts,tsx,jsx,py,java,cs,go,cpp,c,rb,php,swift,kt,scala,rs,m,mm,groovy} : Explain unidiomatic code in comments - comment on code that might seem unnecessary or redundant and document why you chose a specific pattern over more common alternatives, especially when it deviates from team conventions
Applied to files:
public/js/pylon-widget.js
🧬 Code graph analysis (3)
src/pages/api/v1/users/support-hash.ts (1)
src/utils/auth/jwt.ts (1)
verifyJwt(196-222)
public/js/pylon-widget.js (2)
src/utils/auth/session-client.ts (1)
getSession(44-88)public/js/posthog.js (4)
session(23-23)uid(26-26)xoid(27-27)attempts(53-53)
src/pages/auth/callback.ts (4)
src/pages/auth/login.ts (2)
prerender(4-4)GET(6-56)src/pages/auth/session.ts (2)
prerender(4-4)GET(6-117)src/pages/auth/refresh.ts (1)
prerender(4-4)src/utils/auth/pkce.ts (3)
genCodeVerifier(42-42)genRandomString(42-42)genCodeChallenge(42-42)
🪛 Biome (2.3.13)
src/pages/auth/callback.ts
[error] 144-144: This callback passed to forEach() iterable method should not return a value.
Either remove this return or remove the returned value.
(lint/suspicious/useIterableCallbackReturn)
✏️ Tip: You can disable this entire section by setting review_details to false in your review settings.
| import type { APIRoute } from 'astro' | ||
| import { genCodeChallenge, genCodeVerifier, genRandomString } from '@/utils/auth/pkce' |
There was a problem hiding this comment.
Add the required file header metadata.
🔧 Proposed header
+/**
+ * Copyright (c) 2026 ScaleKit, Inc.
+ * License: [License]
+ * Authors: [Team/Author]
+ *
+ * Purpose: OAuth PKCE callback handler for ScaleKit auth.
+ * Dependencies: Astro APIRoute, PKCE utilities
+ */
import type { APIRoute } from 'astro'
import { genCodeChallenge, genCodeVerifier, genRandomString } from '@/utils/auth/pkce'As per coding guidelines: Include file headers with copyright information, license, and authorship - provide a brief description of the file's purpose and document dependencies and requirements.
🤖 Prompt for AI Agents
In `@src/pages/auth/callback.ts` around lines 1 - 2, This file is missing the
required file header metadata; add a top-of-file comment block in
src/pages/auth/callback.ts that includes copyright notice, license, author(s), a
short description of the module's purpose (handling auth callback / PKCE flow),
and document dependencies/requirements such as its use of genCodeChallenge,
genCodeVerifier, and genRandomString imported from '@/utils/auth/pkce' as well
as any environment or runtime expectations; place this header before the import
statements and ensure it follows the project's header template/format.
|
|
||
| export const prerender = false | ||
|
|
||
| export const GET: APIRoute = async (context) => { |
There was a problem hiding this comment.
Add JSDoc for the public GET handler.
📄 Example JSDoc
+/**
+ * GET /auth/callback
+ * Handles OAuth PKCE callback, exchanges code for tokens, and sets auth cookies.
+ * `@param` {import('astro').APIContext} context
+ * `@returns` {Promise<Response>}
+ */
export const GET: APIRoute = async (context) => {As per coding guidelines: Always document public APIs with function/class comments - explain the purpose, parameters, return values, and exceptions; include usage examples for complex functions; Use JSDoc standards for all function, class, and complex logic comments in JavaScript/TypeScript - include parameter descriptions (@param), return values (@returns), types (@type), and descriptions; document exceptions and edge cases.
📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| export const GET: APIRoute = async (context) => { | |
| /** | |
| * GET /auth/callback | |
| * Handles OAuth PKCE callback, exchanges code for tokens, and sets auth cookies. | |
| * `@param` {import('astro').APIContext} context | |
| * `@returns` {Promise<Response>} | |
| */ | |
| export const GET: APIRoute = async (context) => { |
🤖 Prompt for AI Agents
In `@src/pages/auth/callback.ts` at line 6, Add a JSDoc block immediately above
the exported public handler "GET" (the declaration export const GET: APIRoute =
async (context) => { ... }) that documents the handler's purpose, the "context"
parameter (describe shape or link to APIRoute/context types), the return value
(what response or Response/JSON it returns), and any possible errors or edge
cases it may throw or handle; include `@param` for context, `@returns` for the
response, and a brief usage/example line showing how the route is invoked.
Ensure the comment follows JSDoc syntax and references the APIRoute contract so
future readers know the expected types and error behavior.
- Introduced utility functions for managing authentication URLs and cookies, enhancing code organization and readability. - Replaced direct environment variable access with utility functions to streamline configuration retrieval. - Improved cookie management by centralizing PKCE and session cookie handling, ensuring consistent security practices. - Enhanced redirect handling with new utility functions to validate and normalize redirect paths, improving security against open redirect vulnerabilities. These changes enhance the maintainability and security of the authentication flow, providing a clearer structure for future enhancements.
There was a problem hiding this comment.
Actionable comments posted: 5
🤖 Fix all issues with AI agents
In `@src/pages/auth/callback.ts`:
- Around line 108-119: The HTML template in the auth callback interpolates
finalRedirectUrl directly (see the template string building in callback.ts)
which risks XSS; update the handler that constructs html to HTML-escape/encode
finalRedirectUrl before inserting it into the meta refresh, the script's
window.location.replace call, and the anchor text/href (or use a safe
serializer/encode function such as a small htmlEscape utility used in the same
module). Ensure the escaping function converts characters like &, <, >, ", ' and
/ into safe entities and use that escaped value everywhere finalRedirectUrl is
injected; keep normalizePostLoginRedirect but treat escaping here as
defense-in-depth.
In `@src/utils/auth/auth-config.ts`:
- Line 9: The getClientId helper currently returns an empty string when
SCALEKIT_CLIENT_ID is missing; update getClientId to detect a missing or empty
import.meta.env.SCALEKIT_CLIENT_ID and fail fast: either throw a clear Error
(e.g., "Missing SCALEKIT_CLIENT_ID environment variable") or log a visible
warning and exit during startup so OAuth never proceeds with an empty clientId;
locate and modify the getClientId function to perform this check and surface the
descriptive error instead of returning ''.
In `@src/utils/auth/auth-cookies.ts`:
- Around line 118-125: clearAllAuthCookies currently deletes 'sk_refresh_token'
with path '/' which doesn't match where the refresh token is set; update the
deletion call for 'sk_refresh_token' inside clearAllAuthCookies to use the same
path used when setting the cookie (i.e., '/auth/refresh') so the cookie is
actually removed; ensure other cookie deletions remain unchanged and reference
the sk_refresh_token identifier and clearAllAuthCookies function when making the
change.
In `@src/utils/auth/auth-redirects.ts`:
- Around line 16-31: normalizePostLoginRedirect allows protocol-relative URLs
like "//evil.com" because it only checks startsWith('/'); update the validation
in normalizePostLoginRedirect to treat any redirect that begins with '//' as
unsafe (set to '/') before further processing (and keep existing checks for
non-leading-slash values). Specifically, in normalizePostLoginRedirect check for
postLoginRedirect === '' or postLoginRedirect.startsWith('//') and coerce to '/'
(or default) so protocol-relative URLs cannot bypass the validation before
passing to toAbsoluteRedirectUrl.
In `@src/utils/auth/auth-tokens.ts`:
- Around line 10-11: parseTokenResponse currently calls response.json() directly
and will throw if the body is not valid JSON; update parseTokenResponse to wrap
the response.json() call in a try-catch, and on failure read response.text() and
throw a new, descriptive Error that includes response.status and a snippet of
the raw body (or otherwise return a well-documented failure shape). Reference
parseTokenResponse and the Response parameter so the change catches JSON parse
errors, includes HTTP status and body text for diagnostics, and preserves the
TokenData return on success.
🧹 Nitpick comments (5)
src/utils/auth/auth-redirects.ts (1)
1-34: Add JSDoc documentation for public API functions.These are public utilities used across the auth system. Per coding guidelines, public APIs should have JSDoc comments explaining purpose, parameters, return values, and edge cases.
📄 Example JSDoc for one function
+/** + * Validates and extracts a safe redirect path from a target URL. + * Prevents open redirect attacks by ensuring the redirect stays on the same origin. + * `@param` requestUrl - The current request URL (used to validate origin) + * `@param` redirectTarget - The redirect target to validate + * `@returns` The pathname if safe, null otherwise + */ export const getSafeRedirectPath = (requestUrl: URL, redirectTarget: string | null) => {As per coding guidelines: Always document public APIs with function/class comments - explain the purpose, parameters, return values, and exceptions.
src/utils/auth/auth-tokens.ts (1)
3-8: Consider adding timeout to prevent hung requests.The
fetchcall has no timeout, so a non-responsive token endpoint could cause requests to hang indefinitely. While callers could add their ownAbortController, centralizing timeout handling here would provide consistent protection.⏱️ Optional: Add configurable timeout
-export const requestToken = async (tokenUrl: string, body: URLSearchParams) => - fetch(tokenUrl, { +export const requestToken = async ( + tokenUrl: string, + body: URLSearchParams, + timeoutMs = 10_000, +) => { + const controller = new AbortController() + const timeoutId = setTimeout(() => controller.abort(), timeoutMs) + try { + return await fetch(tokenUrl, { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, body: body.toString(), + signal: controller.signal, }) + } finally { + clearTimeout(timeoutId) + } +}src/pages/auth/session.ts (2)
22-27: Redundant null check afterverifyJwt.Looking at the
verifyJwtimplementation (from relevant snippets), it throws an error on failure rather than returning null. The checkif (!verifiedAccessToken)after a successful await is unreachable.♻️ Simplify the verification flow
try { verifiedAccessToken = await verifyJwt(accessToken) - if (!verifiedAccessToken) { - return new Response(JSON.stringify({ authenticated: false }), { - status: 401, - headers: { 'Content-Type': 'application/json' }, - }) - } } catch { return new Response(JSON.stringify({ authenticated: false }), { status: 401,
38-49: Userinfo fetch lacks timeout protection.The fetch to the userinfo endpoint has no timeout, which could cause the session endpoint to hang if the userinfo service is unresponsive. While the error is caught, the request could still block for an extended period.
⏱️ Add AbortController timeout
if (userinfoUrl) { + const controller = new AbortController() + const timeoutId = setTimeout(() => controller.abort(), 5_000) try { const response = await fetch(userinfoUrl, { headers: { Authorization: `Bearer ${accessToken}` }, + signal: controller.signal, }) if (response.ok) { userInfo = (await response.json()) as Record<string, unknown> } } catch { userInfo = null + } finally { + clearTimeout(timeoutId) } }src/pages/auth/callback.ts (1)
1-18: Add file header and JSDoc for the public handler.Per coding guidelines, files should have headers with copyright/license information, and public APIs should have JSDoc documentation.
📄 Proposed additions
+/** + * `@file` OAuth PKCE callback handler for ScaleKit authentication. + * Exchanges authorization code for tokens, sets auth cookies, and redirects. + */ import type { APIRoute } from 'astro'And for the handler:
+/** + * Handles OAuth PKCE callback from the authorization server. + * Validates state, exchanges code for tokens, sets secure cookies, and redirects. + * `@param` context - Astro API context with request/response utilities + * `@returns` Response with auth cookies set and redirect to post-login destination + */ export const GET: APIRoute = async (context) => {As per coding guidelines: Include file headers with copyright information, license, and authorship; Always document public APIs with function/class comments.
📜 Review details
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (9)
src/pages/auth/callback.tssrc/pages/auth/login.tssrc/pages/auth/logout.tssrc/pages/auth/refresh.tssrc/pages/auth/session.tssrc/utils/auth/auth-config.tssrc/utils/auth/auth-cookies.tssrc/utils/auth/auth-redirects.tssrc/utils/auth/auth-tokens.ts
🚧 Files skipped from review as they are similar to previous changes (3)
- src/pages/auth/refresh.ts
- src/pages/auth/logout.ts
- src/pages/auth/login.ts
🧰 Additional context used
📓 Path-based instructions (4)
**/*.{js,ts,py,go,java,tsx,jsx}
📄 CodeRabbit inference engine (CLAUDE.md)
SDK variable names must follow language-specific conventions: Node.js uses
scalekit, Python usesscalekit_client, Go usesscalekitClient, Java usesscalekitClient
Files:
src/utils/auth/auth-config.tssrc/pages/auth/callback.tssrc/utils/auth/auth-cookies.tssrc/utils/auth/auth-redirects.tssrc/utils/auth/auth-tokens.tssrc/pages/auth/session.ts
**/*.{js,ts,tsx,jsx,py,java,cs,go,cpp,c,rb,php,swift,kt,scala,rs,m,mm,groovy,gradle,xml,json}
📄 CodeRabbit inference engine (.cursor/rules/comment-standards.mdc)
Comments should not duplicate the code - avoid comments that simply restate what the code does; comments should add value beyond what's obvious from reading the code
Files:
src/utils/auth/auth-config.tssrc/pages/auth/callback.tssrc/utils/auth/auth-cookies.tssrc/utils/auth/auth-redirects.tssrc/utils/auth/auth-tokens.tssrc/pages/auth/session.ts
**/*.{js,ts,tsx,jsx,py,java,cs,go,cpp,c,rb,php,swift,kt,scala,rs,m,mm,groovy}
📄 CodeRabbit inference engine (.cursor/rules/comment-standards.mdc)
**/*.{js,ts,tsx,jsx,py,java,cs,go,cpp,c,rb,php,swift,kt,scala,rs,m,mm,groovy}: Good comments do not excuse unclear code - refactor the code to be self-explanatory instead of using comments to explain poorly written code; use better variable names, function names, and code structure
Comments should dispel confusion, not cause it - ensure comments clarify rather than obscure the code's purpose; avoid cryptic or joke comments
Explain unidiomatic code in comments - comment on code that might seem unnecessary or redundant and document why you chose a specific pattern over more common alternatives, especially when it deviates from team conventions
Provide links to the original source of copied code - always attribute code copied from external sources with URLs to Stack Overflow answers, GitHub repositories, or documentation
Include links to external references where helpful - reference standards, RFCs, and official documentation; link to relevant specifications when implementing protocols
Add comments when fixing bugs - document bug fixes with context about the issue, reference issue trackers and bug reports, and explain workarounds and their limitations
Use comments to mark incomplete implementations - use standard formats for TODO, FIXME, and NOTE comments with context about what needs to be done and reference issue trackers when possible
Always document public APIs with function/class comments - explain the purpose, parameters, return values, and exceptions; include usage examples for complex functions
Include file headers with copyright information, license, and authorship - provide a brief description of the file's purpose and document dependencies and requirements
Files:
src/utils/auth/auth-config.tssrc/pages/auth/callback.tssrc/utils/auth/auth-cookies.tssrc/utils/auth/auth-redirects.tssrc/utils/auth/auth-tokens.tssrc/pages/auth/session.ts
**/*.{js,ts,tsx,jsx}
📄 CodeRabbit inference engine (.cursor/rules/comment-standards.mdc)
Use JSDoc standards for all function, class, and complex logic comments in JavaScript/TypeScript - include parameter descriptions (
@param), return values (@returns), types (@type), and descriptions; document exceptions and edge cases
Files:
src/utils/auth/auth-config.tssrc/pages/auth/callback.tssrc/utils/auth/auth-cookies.tssrc/utils/auth/auth-redirects.tssrc/utils/auth/auth-tokens.tssrc/pages/auth/session.ts
🧠 Learnings (11)
📚 Learning: 2026-01-13T12:46:55.260Z
Learnt from: CR
Repo: scalekit-inc/developer-docs PR: 0
File: .cursorrules:0-0
Timestamp: 2026-01-13T12:46:55.260Z
Learning: Applies to **/*.mdx : Include configuration comments in code examples: '// Get the signing secret from Scalekit dashboard > Interceptors tab'
Applied to files:
src/utils/auth/auth-config.tssrc/pages/auth/callback.tssrc/pages/auth/session.ts
📚 Learning: 2026-01-13T12:46:55.260Z
Learnt from: CR
Repo: scalekit-inc/developer-docs PR: 0
File: .cursorrules:0-0
Timestamp: 2026-01-13T12:46:55.260Z
Learning: Applies to **/*.mdx : Include context comments explaining what's happening in code: '// Extract encrypted tokens from request cookies', '// Decrypt the access token before validation'
Applied to files:
src/pages/auth/callback.tssrc/utils/auth/auth-cookies.tssrc/utils/auth/auth-tokens.tssrc/pages/auth/session.ts
📚 Learning: 2026-01-13T12:47:33.407Z
Learnt from: CR
Repo: scalekit-inc/developer-docs PR: 0
File: .cursor/rules/comment-standards.mdc:0-0
Timestamp: 2026-01-13T12:47:33.407Z
Learning: Applies to **/*.{js,ts,tsx,jsx,py,java,cs,go,cpp,c,rb,php,swift,kt,scala,rs,m,mm,groovy} : Include file headers with copyright information, license, and authorship - provide a brief description of the file's purpose and document dependencies and requirements
Applied to files:
src/pages/auth/callback.ts
📚 Learning: 2026-01-13T12:46:55.260Z
Learnt from: CR
Repo: scalekit-inc/developer-docs PR: 0
File: .cursorrules:0-0
Timestamp: 2026-01-13T12:46:55.260Z
Learning: Applies to **/*.mdx : Always include security comments in security-related code with pattern: '// Security: ALWAYS verify requests are from Scalekit before processing'
Applied to files:
src/pages/auth/callback.tssrc/pages/auth/session.ts
📚 Learning: 2026-01-13T12:47:33.407Z
Learnt from: CR
Repo: scalekit-inc/developer-docs PR: 0
File: .cursor/rules/comment-standards.mdc:0-0
Timestamp: 2026-01-13T12:47:33.407Z
Learning: Applies to **/*.{js,ts,tsx,jsx,py,java,cs,go,cpp,c,rb,php,swift,kt,scala,rs,m,mm,groovy} : Explain unidiomatic code in comments - comment on code that might seem unnecessary or redundant and document why you chose a specific pattern over more common alternatives, especially when it deviates from team conventions
Applied to files:
src/pages/auth/callback.tssrc/pages/auth/session.ts
📚 Learning: 2026-01-13T12:47:33.407Z
Learnt from: CR
Repo: scalekit-inc/developer-docs PR: 0
File: .cursor/rules/comment-standards.mdc:0-0
Timestamp: 2026-01-13T12:47:33.407Z
Learning: Applies to **/*.{js,ts,tsx,jsx,py,java,cs,go,cpp,c,rb,php,swift,kt,scala,rs,m,mm,groovy} : Add comments when fixing bugs - document bug fixes with context about the issue, reference issue trackers and bug reports, and explain workarounds and their limitations
Applied to files:
src/pages/auth/callback.tssrc/pages/auth/session.ts
📚 Learning: 2026-01-13T12:47:33.407Z
Learnt from: CR
Repo: scalekit-inc/developer-docs PR: 0
File: .cursor/rules/comment-standards.mdc:0-0
Timestamp: 2026-01-13T12:47:33.407Z
Learning: Applies to **/*.{js,ts,tsx,jsx} : Use JSDoc standards for all function, class, and complex logic comments in JavaScript/TypeScript - include parameter descriptions (param), return values (returns), types (type), and descriptions; document exceptions and edge cases
Applied to files:
src/pages/auth/callback.ts
📚 Learning: 2026-01-13T12:47:33.407Z
Learnt from: CR
Repo: scalekit-inc/developer-docs PR: 0
File: .cursor/rules/comment-standards.mdc:0-0
Timestamp: 2026-01-13T12:47:33.407Z
Learning: Applies to **/*.{js,ts,tsx,jsx,py,java,cs,go,cpp,c,rb,php,swift,kt,scala,rs,m,mm,groovy} : Always document public APIs with function/class comments - explain the purpose, parameters, return values, and exceptions; include usage examples for complex functions
Applied to files:
src/pages/auth/callback.ts
📚 Learning: 2026-01-13T12:47:04.673Z
Learnt from: CR
Repo: scalekit-inc/developer-docs PR: 0
File: CLAUDE.md:0-0
Timestamp: 2026-01-13T12:47:04.673Z
Learning: Applies to **/*.{md,mdx} : Include security comments in code examples explaining security threats and implications
Applied to files:
src/pages/auth/session.ts
📚 Learning: 2026-01-13T12:46:55.260Z
Learnt from: CR
Repo: scalekit-inc/developer-docs PR: 0
File: .cursorrules:0-0
Timestamp: 2026-01-13T12:46:55.260Z
Learning: Applies to **/*.mdx : Explain the 'why' in documentation with phrases like 'This prevents CSRF attacks by...' or 'Use this to validate that...'
Applied to files:
src/pages/auth/session.ts
📚 Learning: 2026-01-13T12:46:55.260Z
Learnt from: CR
Repo: scalekit-inc/developer-docs PR: 0
File: .cursorrules:0-0
Timestamp: 2026-01-13T12:46:55.260Z
Learning: Applies to **/*.mdx : Include todo/next step comments in code examples: '// TODO: Store user session (next guide covers this)', '// Next step: Create a session and log in the user'
Applied to files:
src/pages/auth/session.ts
🧬 Code graph analysis (3)
src/pages/auth/callback.ts (5)
src/utils/auth/auth-config.ts (5)
getTokenUrl(4-5)getClientId(9-9)getRedirectUri(11-12)getAuthorizeUrl(1-2)getScopes(14-15)src/utils/auth/pkce.ts (3)
genCodeVerifier(42-42)genRandomString(42-42)genCodeChallenge(42-42)src/utils/auth/auth-cookies.ts (5)
setPkceCookies(21-25)getTokenMaxAges(32-39)getSecureCookieFlag(11-11)buildAuthCookieHeaders(79-104)buildPkceClearCookieHeaders(106-110)src/utils/auth/auth-tokens.ts (2)
requestToken(3-8)parseTokenResponse(10-11)src/utils/auth/auth-redirects.ts (2)
normalizePostLoginRedirect(16-31)toAbsoluteRedirectUrl(33-34)
src/utils/auth/auth-tokens.ts (1)
src/utils/auth/auth-cookies.ts (1)
TokenData(3-9)
src/pages/auth/session.ts (2)
src/utils/auth/jwt.ts (1)
verifyJwt(196-222)src/utils/auth/auth-config.ts (1)
getUserinfoUrl(7-7)
🪛 Biome (2.3.13)
src/pages/auth/callback.ts
[error] 103-103: This callback passed to forEach() iterable method should not return a value.
Either remove this return or remove the returned value.
(lint/suspicious/useIterableCallbackReturn)
🔇 Additional comments (6)
src/utils/auth/auth-redirects.ts (1)
1-14: LGTM on security validation logic.
getSafeRedirectPathcorrectly validates same-origin redirects by comparing origins and checking the pathname starts with/. The try-catch handles malformed URL inputs gracefully.src/utils/auth/auth-config.ts (1)
1-20: LGTM on configuration structure.The module provides a clean, centralized way to access OAuth configuration with sensible defaults for Scalekit endpoints.
src/utils/auth/auth-cookies.ts (1)
1-77: LGTM on cookie security configuration.Good security practices applied:
httpOnly: trueprevents XSS access to tokenssecureflag based on environmentsameSite: 'strict'for refresh token (more sensitive)- Refresh token scoped to
/auth/refreshpath only- Appropriate default expiries (1h access, 30d refresh)
src/pages/auth/callback.ts (3)
103-103: Biome warning is a false positive.The
headers.append()method returnsvoid, so there's no return value being discarded. This lint error can be safely ignored. Alternatively, wrap in braces for explicit style consistency with other forEach usages in the codebase.
63-78: Token exchange lacks timeout and JSON parse error handling.The
requestTokenandparseTokenResponseutilities don't include timeout handling or JSON parse error protection. If the token endpoint is slow or returns malformed data, this could cause the request to hang or throw an unhandled exception.Consider whether timeout and error handling should be added to the utility functions in
auth-tokens.ts(as suggested in that file's review) or handled at each call site. If kept at call sites:⏱️ Example call-site protection
+ let tokenResponse: Response + try { tokenResponse = await requestToken( tokenUrl, new URLSearchParams({ grant_type: 'authorization_code', code, redirect_uri: redirectUri, client_id: clientId, code_verifier: codeVerifier, }), ) + } catch { + return context.redirect('/auth/login?error=token_exchange_failed') + } if (!tokenResponse.ok) { return context.redirect('/auth/login?error=token_exchange_failed') } - const tokenData = await parseTokenResponse(tokenResponse) + let tokenData + try { + tokenData = await parseTokenResponse(tokenResponse) + } catch { + return context.redirect('/auth/login?error=token_exchange_failed') + }
92-98: Good use of centralized cookie utilities.The refactored code properly uses
buildAuthCookieHeadersandbuildPkceClearCookieHeadersinstead of duplicating cookie logic. The comment explaining why manual headers are needed (Netlify middleware workaround) is helpful.
✏️ Tip: You can disable this entire section by setting review_details to false in your review settings.
- Updated the group method call to include an options object with workspaceId, improving the tracking of workspace associations. - This change ensures better identification and management of user groups within the PostHog analytics framework. These modifications enhance the accuracy of user group tracking, contributing to more effective data analysis and insights.
- Modified the Netlify adapter configuration to enable edge middleware support. - This change enhances the deployment capabilities by leveraging edge functions, improving performance and scalability. These updates ensure a more efficient handling of requests in the Scalekit application.
- Deleted the cookies.txt file, which contained outdated cookie information generated by libcurl. - This cleanup helps maintain a tidy codebase by removing unnecessary files that are no longer in use. These changes contribute to better organization and clarity within the project.
- Updated the .env.template to include Scalekit OAuth settings, ensuring proper configuration for the login flow. - Improved session handling in AuthValue.astro by adding logic to refresh tokens on 401 responses, enhancing user authentication reliability. - Added validation for SCALEKIT_AUTHORIZE_URL in support-hash.ts to ensure correct URL formatting, improving error handling and server configuration checks. These changes enhance the authentication flow and configuration management, providing a more robust and user-friendly experience in the Scalekit application.
- Added HTML and JavaScript escaping functions to prevent XSS attacks in the auth callback. - Updated the handling of the SCALEKIT_CLIENT_ID environment variable to throw an error if missing, ensuring proper configuration. - Modified the path for deleting the refresh token cookie to improve security practices. These changes enhance the security and reliability of the authentication process in the Scalekit application.
- Added checks to block protocol-relative URLs and empty strings in the redirect path, preventing potential security vulnerabilities. - This change ensures that only valid redirect paths are processed, enhancing the overall security of the authentication flow in the Scalekit application.
- Enhanced the `parseTokenResponse` function to include robust error handling for JSON parsing failures. - Added detailed error messages that include the HTTP status and a snippet of the response body for better diagnostics. - This change improves the reliability of token handling in the authentication flow, ensuring that errors are clearly communicated and easier to debug. These updates contribute to a more resilient authentication process in the Scalekit application.
- Added external dependencies to the Rollup configuration in `astro.config.mjs`, improving build performance by preventing unnecessary bundling of core Node.js modules. - Ensured proper structure in `tsconfig.json` by maintaining consistent formatting for compiler options and paths. These changes enhance the build process and maintain clarity in TypeScript configuration, contributing to a more efficient development environment in the Scalekit application.
- Removed unnecessary external dependencies from the Rollup configuration in `astro.config.mjs`, streamlining the build process. - Updated the Netlify adapter configuration to disable edge middleware, simplifying deployment settings. These changes enhance the build efficiency and maintain clarity in the Astro configuration for the Scalekit application.
* feat: initial point in setting up auth * Implement authentication middleware and session management features - Added middleware for handling authentication and session management, ensuring protected routes are accessible only to authenticated users. - Introduced new API routes for login, logout, and session verification, enhancing the authentication flow. - Created utility functions for PKCE (Proof Key for Code Exchange) to improve security during the OAuth process. - Added environment template for GitHub token and other configuration settings to streamline setup for developers. - Integrated new authentication components for user interface, including AuthCTA, AuthGate, and AuthValue, to manage user sessions effectively. This update significantly enhances the authentication capabilities of the Scalekit application, providing a robust framework for user management and security. * feat: preprender false for serversite true pages * feat: sets the localstorage to know deatils about hte user * feat: enhance AuthCTA component with dropdown menu for authenticated users - Added a dropdown menu to the AuthCTA component for users who are logged in, allowing access to the Dashboard and Sign out options. - Implemented event listeners for menu interactions, including opening and closing the menu on click and keyboard events. - Updated styles to manage visibility of the Sign in button and dropdown menu based on authentication state. - Improved accessibility with ARIA attributes for better screen reader support. This update significantly improves the user experience by providing a more intuitive interface for authenticated users. * fix: remove Dashboard link from AuthCTA component - Eliminated the Dashboard link from the AuthCTA dropdown menu to streamline the user interface for authenticated users. - This change enhances the focus on the Sign out option, improving the overall user experience. * feat: integrate Pylon widget for enhanced user interaction - Added scripts to load the Pylon widget, enabling real-time user engagement features. - Implemented logic to derive user information from local storage, enhancing personalization within the widget. - This update improves the overall user experience by providing tailored interactions based on user data. * chore: remove unused `repomix` dependency from package.json and pnpm-lock.yaml - Eliminated `repomix` from both `package.json` and `pnpm-lock.yaml` to streamline dependencies and reduce potential bloat. - This cleanup improves the overall project maintainability by ensuring only necessary packages are included. * feat: improve Pylon widget initialization and session handling - Refactored the Pylon widget script to use async functions for better session management. - Added logic to fetch session data from the server if no cached session is found, enhancing user experience. - Improved error handling during widget initialization to provide clearer debugging information. - This update enhances the reliability and responsiveness of the Pylon widget by ensuring user data is accurately derived and utilized. * chore: update .gitignore to include debug.log - Added debug.log to .gitignore to prevent logging files from being tracked in version control. - This change helps maintain a cleaner repository by excluding unnecessary log files. * refactor: update middleware and authentication flow for improved security and session handling - Changed output configuration in `astro.config.mjs` from 'static' to 'server' for better server-side rendering. - Removed unnecessary logging from `src/middleware.ts` to streamline the authentication process. - Enhanced the authentication flow by validating redirect URLs in `callback.ts` and `login.ts` to prevent open redirect attacks. - Improved error handling in `session.ts` to ensure proper responses for unauthorized access. - Cleaned up JWT utility functions in `jwt.ts` by removing debug logging, enhancing performance and security. These changes enhance the overall security and reliability of the authentication process within the application. * fix: enhance token validation and error handling in authentication flow - Added verification for received tokens in `callback.ts` to ensure a complete OAuth response. - Implemented cryptographic verification of the access token in `session.ts` to enhance security. - Improved error handling in `jwt.ts` for JWKS initialization failures, ensuring graceful degradation of JWT verification. These changes strengthen the authentication process by ensuring that only valid tokens are processed and providing clearer error handling for potential issues. * fix: enhance session validation and error handling in Pylon widget initialization - Implemented robust validation for session data to prevent injection of malicious properties and ensure proper structure. - Added sanitization for user email and name to remove potential HTML/script tags, enhancing security. - Improved error handling during session parsing to prevent widget initialization with invalid data. - Updated middleware to ensure access is denied if JWT verification fails, enhancing overall authentication security. These changes strengthen the integrity of user session management and improve the security of the Pylon widget integration. * fix: enhance JWT verification process and error handling - Introduced caching for JWKS by issuer URL to optimize performance and reduce redundant requests during JWT verification. - Updated the `verifyJwt` function to extract issuer and audience claims directly from the token, eliminating the need for environment variables. - Improved error handling for missing claims in the JWT, providing clearer feedback when verification fails. These changes strengthen the JWT verification process, enhance performance, and improve error reporting for better debugging. * fix: enhance logout process and session management - Updated the logout flow to extract the ID token from localStorage before clearing it, ensuring proper session termination. - Modified the logout endpoint to accept the ID token as a query parameter for improved session invalidation with Scalekit. - Included the raw ID token in the session response to facilitate logout operations. These changes strengthen the logout process and improve session management, enhancing overall security and user experience. * fix: remove client secret from token requests in callback and refresh endpoints - Eliminated the `client_secret` parameter from the token requests in both `callback.ts` and `refresh.ts` to enhance security by preventing sensitive information from being exposed. - This change aligns with best practices for OAuth implementations, ensuring that client secrets are not unnecessarily transmitted during token exchanges. These updates strengthen the security posture of the authentication flow by minimizing the risk of credential exposure. * fix: enhance session response with user and workspace identifiers - Added extraction of `uid` (user ID) and `xoid` (workspace ID) from ID token claims and access token payload to the session response. - Updated the `AuthSession` type to include optional `uid` and `xoid` properties for better session management. These changes improve the session response by providing essential identifiers, enhancing the overall user experience and session handling. * fix: enhance Pylon widget integration and session handling - Added a new Pylon widget script to initialize the chat widget with user session data, improving user interaction. - Implemented robust session validation and sanitization for user email and name to enhance security. - Introduced a new API endpoint to fetch email hashes for identity verification, ensuring accurate user identification. - Improved error handling during widget initialization and session fetching to provide clearer feedback. These changes strengthen the integration of the Pylon widget, enhance user experience, and improve overall security in session management. * fix: enhance session handling and PostHog integration - Introduced session management improvements by implementing a polling mechanism to identify users from session data. - Added functions to read session data from localStorage and reset PostHog identity when the session changes. - Enhanced the Pylon widget by ensuring user identifiers are correctly set during initialization. - Updated documentation to include the new external organization ID (xoid) in the session response. These changes strengthen user session handling and improve the integration with PostHog, enhancing overall user experience and data accuracy. * fix: improve session handling and UI synchronization - Enhanced session management by implementing a refresh mechanism for access tokens, ensuring users remain authenticated seamlessly. - Updated the `AuthCTA` component to periodically refresh the UI state based on session data, improving user experience. - Modified the session API to handle access token verification and expiry more effectively, ensuring accurate session responses. These changes strengthen session handling and enhance the user interface, providing a more reliable authentication experience. * fix: enhance dashboard button functionality and session management - Updated the Header component to include a dashboard button that is conditionally displayed based on user authentication status. - Implemented session management functions to read, write, and clear session data from localStorage, improving user experience. - Added a script to periodically refresh the dashboard button state, ensuring the UI remains in sync with the user's authentication status. These changes enhance the dashboard button's visibility and improve session handling, providing a more dynamic user interface. * fix: improve session management and cookie handling - Added a new cookies.txt file to manage HTTP cookies generated by the application. - Updated the logout process to return an intermediate page that clears localStorage before redirecting to Scalekit, enhancing user experience during logout. - Modified the refresh endpoint to scope the refresh token cookie to the '/auth/refresh' path, improving security by limiting cookie access. These changes enhance session management and improve cookie handling, providing a more secure and user-friendly authentication experience. * fix: update AuthCTA component for improved user profile display and logout functionality - Replaced user icon with a logout icon in the profile menu for better clarity. - Enhanced profile menu to display user name and email, improving user experience. - Added functions to normalize and retrieve user name and email from session data. - Updated styles for profile elements to enhance visual consistency and accessibility. These changes improve the user interface of the AuthCTA component, providing a clearer logout option and better user information display. * fix: enhance Pylon widget integration and support hash management - Introduced a new support hash mechanism to improve user identification and session management within the Pylon widget. - Updated the Pylon widget script to cache and retrieve the support hash from localStorage, enhancing performance and user experience. - Modified the API endpoint to return both support and email hashes for better identity verification. - Improved error handling and session validation during widget initialization to provide clearer feedback. These changes strengthen the integration of the Pylon widget, enhance user experience, and improve overall session management. * remove teh code samples * fix: enhance redirect handling in auth callback - Implemented logic to ensure the redirect URL is clean and absolute, preventing issues with query parameters in Netlify middleware mode. - Removed any query parameters or fragments from the redirect path to maintain a consistent and secure redirect experience. - Added checks to ensure the redirect URL starts with a '/', enhancing the robustness of the redirect process. These changes improve the reliability of the authentication callback by ensuring proper URL handling during redirects. * fix: enhance logging in middleware and auth callback - Added logging functionality to the middleware and auth callback to capture key events and data for debugging purposes. - Implemented fetch requests to send log data to a local ingestion endpoint, including details about the request and response flow. - Enhanced error handling by logging invalid state scenarios and cookie values, improving traceability during authentication processes. These changes improve the observability of the authentication flow, aiding in troubleshooting and performance monitoring. * refactor: streamline middleware and auth callback logic - Removed unnecessary logging functionality from the middleware and auth callback to simplify the codebase. - Updated the auth callback to use a client-side redirect, improving compatibility with Netlify's handling of query parameters. - Enhanced response handling by returning an HTML page for redirects, ensuring a smoother user experience. These changes improve code clarity and maintainability while enhancing the redirect process in the authentication flow. * debug: clean up the instrumentation code * chore: comment out support hash fetching logic for future implementation - Temporarily commented out the code responsible for fetching the support hash from the API. - Added a TODO note indicating the need for a method to retrieve the support hash on auth.scalekit.com. - This change prepares the code for future enhancements while maintaining current functionality. * chore: temporarily disable support hash fetching logic for API readiness - Commented out the code responsible for fetching the support hash from the API until the backend is ready for deployment. - Added TODO notes indicating the need to uncomment the code when the API is operational. - Updated the response handling to return a 503 status, indicating that the service is temporarily unavailable. These changes ensure that the code remains functional while awaiting backend readiness, maintaining clarity for future implementation. * fix: re-enable support hash fetching logic in Pylon widget - Uncommented the code responsible for fetching the support hash from the backend API, allowing for identity verification. - Updated the response handling to return the support hash or email hash as needed, improving user identification. - Added a minimal configuration for anonymous users to ensure the widget can load even without an authenticated session. These changes enhance the functionality of the Pylon widget by integrating support hash retrieval, improving user experience and session management. * fix: restore support hash fetching logic in Pylon widget - Uncommented the code for fetching the support hash from the backend API, enabling identity verification. - Enhanced response handling to return the appropriate support or email hash, improving user identification. - Ensured minimal configuration for anonymous users, allowing the widget to load without an authenticated session. These updates enhance the Pylon widget's functionality by re-integrating support hash retrieval, thereby improving user experience and session management. * fix: enhance OAuth error handling in auth callback - Added logic to handle OAuth error responses, specifically for 'login_required' scenarios. - Constructed a login URL without the prompt=none parameter to redirect users when they are not logged in. - Implemented PKCE (Proof Key for Code Exchange) support by generating code verifiers and challenges, improving security during the authentication process. - Updated the login URL to ensure it points to the correct authorization endpoint. These changes improve the user experience by providing a seamless login flow and enhancing security measures in the authentication process. * refactor: modularize authentication logic and improve cookie handling - Introduced utility functions for managing authentication URLs and cookies, enhancing code organization and readability. - Replaced direct environment variable access with utility functions to streamline configuration retrieval. - Improved cookie management by centralizing PKCE and session cookie handling, ensuring consistent security practices. - Enhanced redirect handling with new utility functions to validate and normalize redirect paths, improving security against open redirect vulnerabilities. These changes enhance the maintainability and security of the authentication flow, providing a clearer structure for future enhancements. * fix: enhance group tracking in PostHog integration - Updated the group method call to include an options object with workspaceId, improving the tracking of workspace associations. - This change ensures better identification and management of user groups within the PostHog analytics framework. These modifications enhance the accuracy of user group tracking, contributing to more effective data analysis and insights. * fix: update Netlify adapter configuration for edge middleware - Modified the Netlify adapter configuration to enable edge middleware support. - This change enhances the deployment capabilities by leveraging edge functions, improving performance and scalability. These updates ensure a more efficient handling of requests in the Scalekit application. * chore: remove deprecated cookies file - Deleted the cookies.txt file, which contained outdated cookie information generated by libcurl. - This cleanup helps maintain a tidy codebase by removing unnecessary files that are no longer in use. These changes contribute to better organization and clarity within the project. * fix: enhance Scalekit OAuth configuration and session handling - Updated the .env.template to include Scalekit OAuth settings, ensuring proper configuration for the login flow. - Improved session handling in AuthValue.astro by adding logic to refresh tokens on 401 responses, enhancing user authentication reliability. - Added validation for SCALEKIT_AUTHORIZE_URL in support-hash.ts to ensure correct URL formatting, improving error handling and server configuration checks. These changes enhance the authentication flow and configuration management, providing a more robust and user-friendly experience in the Scalekit application. * fix: enhance security and error handling in authentication flow - Added HTML and JavaScript escaping functions to prevent XSS attacks in the auth callback. - Updated the handling of the SCALEKIT_CLIENT_ID environment variable to throw an error if missing, ensuring proper configuration. - Modified the path for deleting the refresh token cookie to improve security practices. These changes enhance the security and reliability of the authentication process in the Scalekit application. * fix: enhance security in redirect path normalization - Added checks to block protocol-relative URLs and empty strings in the redirect path, preventing potential security vulnerabilities. - This change ensures that only valid redirect paths are processed, enhancing the overall security of the authentication flow in the Scalekit application. * fix: improve error handling in token response parsing - Enhanced the `parseTokenResponse` function to include robust error handling for JSON parsing failures. - Added detailed error messages that include the HTTP status and a snippet of the response body for better diagnostics. - This change improves the reliability of token handling in the authentication flow, ensuring that errors are clearly communicated and easier to debug. These updates contribute to a more resilient authentication process in the Scalekit application. * fix: update Astro configuration for external dependencies - Added external dependencies to the Rollup configuration in `astro.config.mjs`, improving build performance by preventing unnecessary bundling of core Node.js modules. - Ensured proper structure in `tsconfig.json` by maintaining consistent formatting for compiler options and paths. These changes enhance the build process and maintain clarity in TypeScript configuration, contributing to a more efficient development environment in the Scalekit application. * fix: update Netlify adapter configuration in Astro setup - Removed unnecessary external dependencies from the Rollup configuration in `astro.config.mjs`, streamlining the build process. - Updated the Netlify adapter configuration to disable edge middleware, simplifying deployment settings. These changes enhance the build efficiency and maintain clarity in the Astro configuration for the Scalekit application.
* feat: initial point in setting up auth * Implement authentication middleware and session management features - Added middleware for handling authentication and session management, ensuring protected routes are accessible only to authenticated users. - Introduced new API routes for login, logout, and session verification, enhancing the authentication flow. - Created utility functions for PKCE (Proof Key for Code Exchange) to improve security during the OAuth process. - Added environment template for GitHub token and other configuration settings to streamline setup for developers. - Integrated new authentication components for user interface, including AuthCTA, AuthGate, and AuthValue, to manage user sessions effectively. This update significantly enhances the authentication capabilities of the Scalekit application, providing a robust framework for user management and security. * feat: preprender false for serversite true pages * feat: sets the localstorage to know deatils about hte user * feat: enhance AuthCTA component with dropdown menu for authenticated users - Added a dropdown menu to the AuthCTA component for users who are logged in, allowing access to the Dashboard and Sign out options. - Implemented event listeners for menu interactions, including opening and closing the menu on click and keyboard events. - Updated styles to manage visibility of the Sign in button and dropdown menu based on authentication state. - Improved accessibility with ARIA attributes for better screen reader support. This update significantly improves the user experience by providing a more intuitive interface for authenticated users. * fix: remove Dashboard link from AuthCTA component - Eliminated the Dashboard link from the AuthCTA dropdown menu to streamline the user interface for authenticated users. - This change enhances the focus on the Sign out option, improving the overall user experience. * feat: integrate Pylon widget for enhanced user interaction - Added scripts to load the Pylon widget, enabling real-time user engagement features. - Implemented logic to derive user information from local storage, enhancing personalization within the widget. - This update improves the overall user experience by providing tailored interactions based on user data. * chore: remove unused `repomix` dependency from package.json and pnpm-lock.yaml - Eliminated `repomix` from both `package.json` and `pnpm-lock.yaml` to streamline dependencies and reduce potential bloat. - This cleanup improves the overall project maintainability by ensuring only necessary packages are included. * feat: improve Pylon widget initialization and session handling - Refactored the Pylon widget script to use async functions for better session management. - Added logic to fetch session data from the server if no cached session is found, enhancing user experience. - Improved error handling during widget initialization to provide clearer debugging information. - This update enhances the reliability and responsiveness of the Pylon widget by ensuring user data is accurately derived and utilized. * chore: update .gitignore to include debug.log - Added debug.log to .gitignore to prevent logging files from being tracked in version control. - This change helps maintain a cleaner repository by excluding unnecessary log files. * refactor: update middleware and authentication flow for improved security and session handling - Changed output configuration in `astro.config.mjs` from 'static' to 'server' for better server-side rendering. - Removed unnecessary logging from `src/middleware.ts` to streamline the authentication process. - Enhanced the authentication flow by validating redirect URLs in `callback.ts` and `login.ts` to prevent open redirect attacks. - Improved error handling in `session.ts` to ensure proper responses for unauthorized access. - Cleaned up JWT utility functions in `jwt.ts` by removing debug logging, enhancing performance and security. These changes enhance the overall security and reliability of the authentication process within the application. * fix: enhance token validation and error handling in authentication flow - Added verification for received tokens in `callback.ts` to ensure a complete OAuth response. - Implemented cryptographic verification of the access token in `session.ts` to enhance security. - Improved error handling in `jwt.ts` for JWKS initialization failures, ensuring graceful degradation of JWT verification. These changes strengthen the authentication process by ensuring that only valid tokens are processed and providing clearer error handling for potential issues. * fix: enhance session validation and error handling in Pylon widget initialization - Implemented robust validation for session data to prevent injection of malicious properties and ensure proper structure. - Added sanitization for user email and name to remove potential HTML/script tags, enhancing security. - Improved error handling during session parsing to prevent widget initialization with invalid data. - Updated middleware to ensure access is denied if JWT verification fails, enhancing overall authentication security. These changes strengthen the integrity of user session management and improve the security of the Pylon widget integration. * fix: enhance JWT verification process and error handling - Introduced caching for JWKS by issuer URL to optimize performance and reduce redundant requests during JWT verification. - Updated the `verifyJwt` function to extract issuer and audience claims directly from the token, eliminating the need for environment variables. - Improved error handling for missing claims in the JWT, providing clearer feedback when verification fails. These changes strengthen the JWT verification process, enhance performance, and improve error reporting for better debugging. * fix: enhance logout process and session management - Updated the logout flow to extract the ID token from localStorage before clearing it, ensuring proper session termination. - Modified the logout endpoint to accept the ID token as a query parameter for improved session invalidation with Scalekit. - Included the raw ID token in the session response to facilitate logout operations. These changes strengthen the logout process and improve session management, enhancing overall security and user experience. * fix: remove client secret from token requests in callback and refresh endpoints - Eliminated the `client_secret` parameter from the token requests in both `callback.ts` and `refresh.ts` to enhance security by preventing sensitive information from being exposed. - This change aligns with best practices for OAuth implementations, ensuring that client secrets are not unnecessarily transmitted during token exchanges. These updates strengthen the security posture of the authentication flow by minimizing the risk of credential exposure. * fix: enhance session response with user and workspace identifiers - Added extraction of `uid` (user ID) and `xoid` (workspace ID) from ID token claims and access token payload to the session response. - Updated the `AuthSession` type to include optional `uid` and `xoid` properties for better session management. These changes improve the session response by providing essential identifiers, enhancing the overall user experience and session handling. * fix: enhance Pylon widget integration and session handling - Added a new Pylon widget script to initialize the chat widget with user session data, improving user interaction. - Implemented robust session validation and sanitization for user email and name to enhance security. - Introduced a new API endpoint to fetch email hashes for identity verification, ensuring accurate user identification. - Improved error handling during widget initialization and session fetching to provide clearer feedback. These changes strengthen the integration of the Pylon widget, enhance user experience, and improve overall security in session management. * fix: enhance session handling and PostHog integration - Introduced session management improvements by implementing a polling mechanism to identify users from session data. - Added functions to read session data from localStorage and reset PostHog identity when the session changes. - Enhanced the Pylon widget by ensuring user identifiers are correctly set during initialization. - Updated documentation to include the new external organization ID (xoid) in the session response. These changes strengthen user session handling and improve the integration with PostHog, enhancing overall user experience and data accuracy. * fix: improve session handling and UI synchronization - Enhanced session management by implementing a refresh mechanism for access tokens, ensuring users remain authenticated seamlessly. - Updated the `AuthCTA` component to periodically refresh the UI state based on session data, improving user experience. - Modified the session API to handle access token verification and expiry more effectively, ensuring accurate session responses. These changes strengthen session handling and enhance the user interface, providing a more reliable authentication experience. * fix: enhance dashboard button functionality and session management - Updated the Header component to include a dashboard button that is conditionally displayed based on user authentication status. - Implemented session management functions to read, write, and clear session data from localStorage, improving user experience. - Added a script to periodically refresh the dashboard button state, ensuring the UI remains in sync with the user's authentication status. These changes enhance the dashboard button's visibility and improve session handling, providing a more dynamic user interface. * fix: improve session management and cookie handling - Added a new cookies.txt file to manage HTTP cookies generated by the application. - Updated the logout process to return an intermediate page that clears localStorage before redirecting to Scalekit, enhancing user experience during logout. - Modified the refresh endpoint to scope the refresh token cookie to the '/auth/refresh' path, improving security by limiting cookie access. These changes enhance session management and improve cookie handling, providing a more secure and user-friendly authentication experience. * fix: update AuthCTA component for improved user profile display and logout functionality - Replaced user icon with a logout icon in the profile menu for better clarity. - Enhanced profile menu to display user name and email, improving user experience. - Added functions to normalize and retrieve user name and email from session data. - Updated styles for profile elements to enhance visual consistency and accessibility. These changes improve the user interface of the AuthCTA component, providing a clearer logout option and better user information display. * fix: enhance Pylon widget integration and support hash management - Introduced a new support hash mechanism to improve user identification and session management within the Pylon widget. - Updated the Pylon widget script to cache and retrieve the support hash from localStorage, enhancing performance and user experience. - Modified the API endpoint to return both support and email hashes for better identity verification. - Improved error handling and session validation during widget initialization to provide clearer feedback. These changes strengthen the integration of the Pylon widget, enhance user experience, and improve overall session management. * remove teh code samples * fix: enhance redirect handling in auth callback - Implemented logic to ensure the redirect URL is clean and absolute, preventing issues with query parameters in Netlify middleware mode. - Removed any query parameters or fragments from the redirect path to maintain a consistent and secure redirect experience. - Added checks to ensure the redirect URL starts with a '/', enhancing the robustness of the redirect process. These changes improve the reliability of the authentication callback by ensuring proper URL handling during redirects. * fix: enhance logging in middleware and auth callback - Added logging functionality to the middleware and auth callback to capture key events and data for debugging purposes. - Implemented fetch requests to send log data to a local ingestion endpoint, including details about the request and response flow. - Enhanced error handling by logging invalid state scenarios and cookie values, improving traceability during authentication processes. These changes improve the observability of the authentication flow, aiding in troubleshooting and performance monitoring. * refactor: streamline middleware and auth callback logic - Removed unnecessary logging functionality from the middleware and auth callback to simplify the codebase. - Updated the auth callback to use a client-side redirect, improving compatibility with Netlify's handling of query parameters. - Enhanced response handling by returning an HTML page for redirects, ensuring a smoother user experience. These changes improve code clarity and maintainability while enhancing the redirect process in the authentication flow. * debug: clean up the instrumentation code * chore: comment out support hash fetching logic for future implementation - Temporarily commented out the code responsible for fetching the support hash from the API. - Added a TODO note indicating the need for a method to retrieve the support hash on auth.scalekit.com. - This change prepares the code for future enhancements while maintaining current functionality. * chore: temporarily disable support hash fetching logic for API readiness - Commented out the code responsible for fetching the support hash from the API until the backend is ready for deployment. - Added TODO notes indicating the need to uncomment the code when the API is operational. - Updated the response handling to return a 503 status, indicating that the service is temporarily unavailable. These changes ensure that the code remains functional while awaiting backend readiness, maintaining clarity for future implementation. * fix: re-enable support hash fetching logic in Pylon widget - Uncommented the code responsible for fetching the support hash from the backend API, allowing for identity verification. - Updated the response handling to return the support hash or email hash as needed, improving user identification. - Added a minimal configuration for anonymous users to ensure the widget can load even without an authenticated session. These changes enhance the functionality of the Pylon widget by integrating support hash retrieval, improving user experience and session management. * fix: restore support hash fetching logic in Pylon widget - Uncommented the code for fetching the support hash from the backend API, enabling identity verification. - Enhanced response handling to return the appropriate support or email hash, improving user identification. - Ensured minimal configuration for anonymous users, allowing the widget to load without an authenticated session. These updates enhance the Pylon widget's functionality by re-integrating support hash retrieval, thereby improving user experience and session management. * fix: enhance OAuth error handling in auth callback - Added logic to handle OAuth error responses, specifically for 'login_required' scenarios. - Constructed a login URL without the prompt=none parameter to redirect users when they are not logged in. - Implemented PKCE (Proof Key for Code Exchange) support by generating code verifiers and challenges, improving security during the authentication process. - Updated the login URL to ensure it points to the correct authorization endpoint. These changes improve the user experience by providing a seamless login flow and enhancing security measures in the authentication process. * refactor: modularize authentication logic and improve cookie handling - Introduced utility functions for managing authentication URLs and cookies, enhancing code organization and readability. - Replaced direct environment variable access with utility functions to streamline configuration retrieval. - Improved cookie management by centralizing PKCE and session cookie handling, ensuring consistent security practices. - Enhanced redirect handling with new utility functions to validate and normalize redirect paths, improving security against open redirect vulnerabilities. These changes enhance the maintainability and security of the authentication flow, providing a clearer structure for future enhancements. * fix: enhance group tracking in PostHog integration - Updated the group method call to include an options object with workspaceId, improving the tracking of workspace associations. - This change ensures better identification and management of user groups within the PostHog analytics framework. These modifications enhance the accuracy of user group tracking, contributing to more effective data analysis and insights. * fix: update Netlify adapter configuration for edge middleware - Modified the Netlify adapter configuration to enable edge middleware support. - This change enhances the deployment capabilities by leveraging edge functions, improving performance and scalability. These updates ensure a more efficient handling of requests in the Scalekit application. * chore: remove deprecated cookies file - Deleted the cookies.txt file, which contained outdated cookie information generated by libcurl. - This cleanup helps maintain a tidy codebase by removing unnecessary files that are no longer in use. These changes contribute to better organization and clarity within the project. * fix: enhance Scalekit OAuth configuration and session handling - Updated the .env.template to include Scalekit OAuth settings, ensuring proper configuration for the login flow. - Improved session handling in AuthValue.astro by adding logic to refresh tokens on 401 responses, enhancing user authentication reliability. - Added validation for SCALEKIT_AUTHORIZE_URL in support-hash.ts to ensure correct URL formatting, improving error handling and server configuration checks. These changes enhance the authentication flow and configuration management, providing a more robust and user-friendly experience in the Scalekit application. * fix: enhance security and error handling in authentication flow - Added HTML and JavaScript escaping functions to prevent XSS attacks in the auth callback. - Updated the handling of the SCALEKIT_CLIENT_ID environment variable to throw an error if missing, ensuring proper configuration. - Modified the path for deleting the refresh token cookie to improve security practices. These changes enhance the security and reliability of the authentication process in the Scalekit application. * fix: enhance security in redirect path normalization - Added checks to block protocol-relative URLs and empty strings in the redirect path, preventing potential security vulnerabilities. - This change ensures that only valid redirect paths are processed, enhancing the overall security of the authentication flow in the Scalekit application. * fix: improve error handling in token response parsing - Enhanced the `parseTokenResponse` function to include robust error handling for JSON parsing failures. - Added detailed error messages that include the HTTP status and a snippet of the response body for better diagnostics. - This change improves the reliability of token handling in the authentication flow, ensuring that errors are clearly communicated and easier to debug. These updates contribute to a more resilient authentication process in the Scalekit application. * fix: update Astro configuration for external dependencies - Added external dependencies to the Rollup configuration in `astro.config.mjs`, improving build performance by preventing unnecessary bundling of core Node.js modules. - Ensured proper structure in `tsconfig.json` by maintaining consistent formatting for compiler options and paths. These changes enhance the build process and maintain clarity in TypeScript configuration, contributing to a more efficient development environment in the Scalekit application. * fix: update Netlify adapter configuration in Astro setup - Removed unnecessary external dependencies from the Rollup configuration in `astro.config.mjs`, streamlining the build process. - Updated the Netlify adapter configuration to disable edge middleware, simplifying deployment settings. These changes enhance the build efficiency and maintain clarity in the Astro configuration for the Scalekit application.
Pending
Summary by CodeRabbit
New Features
Documentation
Chores