### Install Dependencies and Build Packages - Bash Source: https://github.com/lance0/latch/blob/master/TESTING_GUIDE.md Installs project dependencies using pnpm and builds all Latch packages including core library, CLI, and example app. Requires Node.js and pnpm; run from monorepo root. Outputs built artifacts for local use; no specific inputs beyond standard setup. ```bash pnpm install pnpm build ``` -------------------------------- ### Install and Build Latch Packages Source: https://github.com/lance0/latch/blob/master/llms.txt Commands to clone the Latch repository, install dependencies, build all packages, run tests within a specific package, and start the example application for development. ```bash git clone https://github.com/lance0/latch.git pnpm install pnpm build cd packages/latch && pnpm test pnpm dev ``` -------------------------------- ### Latch User Installation and Setup Source: https://github.com/lance0/latch/blob/master/llms.txt This details the initial steps for users integrating Latch into their projects. It covers installation via npm, configuration of environment variables, setting up the CLI, scaffolding common components like API routes or proxy files, validating the configuration, and integrating the LatchProvider and hooks into the application. ```bash 1. Install: `npm install @lance0/latch` 2. Configure: Create `.env.local` with Azure AD credentials 3. Setup CLI: `npx @lance0/latch-cli init` (interactive wizard) 4. Scaffold: `npx @lance0/latch-cli scaffold` (interactive - routes, proxy.ts, or auth wrapper) 5. Validate: `npx @lance0/latch-cli validate` (checks config) 6. Wrap app: Add `` to root layout 7. Use hooks: `useLatch()` for authentication state ``` -------------------------------- ### Run Development Server with pnpm Source: https://github.com/lance0/latch/blob/master/apps/example-commercial/README.md Starts the Next.js development server. This command should be run after all dependencies are installed and environment variables are configured. ```bash pnpm dev ``` -------------------------------- ### Run Development Server - Bash Source: https://github.com/lance0/latch/blob/master/TESTING_GUIDE.md Starts the Next.js dev server after setup for local testing. Requires pnpm and configured app; visit localhost:3000. Serves the app with hot reload; troubleshooting for module errors involves rebuilding and relinking. ```bash pnpm dev ``` -------------------------------- ### Install Dependencies with pnpm Source: https://github.com/lance0/latch/blob/master/apps/example-commercial/README.md Installs the necessary project dependencies using the pnpm package manager. Ensure pnpm is installed globally before running this command. ```bash pnpm install ``` -------------------------------- ### Initialize Latch CLI Wizard Source: https://github.com/lance0/latch/blob/master/docs/AUTHENTICATION_SETUP.md Command to run the Latch CLI wizard for initializing the project. The wizard guides the user through selecting the client type (Public Client or Confidential Client) and generates the appropriate configuration. ```bash npx @lance0/latch-cli init ``` -------------------------------- ### Latch CLI Scaffold Options Source: https://github.com/lance0/latch/blob/master/llms.txt Demonstrates the available options for the `latch scaffold` CLI command, used for generating project setup files. It lists commands for creating Next.js 16 compatible proxy files, authentication wrappers, copying API routes from examples, or performing a complete setup. An interactive menu is also mentioned for easier selection. ```bash `latch scaffold --type proxy` - Generate Next.js 16 compatible proxy.ts `latch scaffold --type wrapper` - Generate lib/auth.ts with recommended pattern `latch scaffold --type routes` - Copy API routes from examples `latch scaffold --type all` - Complete setup - Interactive menu for easy selection ``` -------------------------------- ### Copy API Routes for Latch Integration - Bash Source: https://github.com/lance0/latch/blob/master/TESTING_GUIDE.md Creates directory and copies Latch API route files from example app to new project. Depends on example-app source; run after app creation. Sets up /api/latch endpoints for auth callbacks; assumes TS files are compatible. ```bash mkdir -p app/api/latch cp /home/lance/latch/apps/example-app/app/api/latch/*.ts app/api/latch/ ``` -------------------------------- ### Run Diagnostics on Latch Setup Source: https://github.com/lance0/latch/blob/master/packages/latch-cli/README.md Executes diagnostic checks on the Latch setup, verifying installation, configuration, API routes, and the presence of the LatchProvider. ```bash latch doctor ``` -------------------------------- ### Update Latch Client Secret in Production Source: https://github.com/lance0/latch/blob/master/docs/AUTHENTICATION_SETUP.md This example demonstrates how to update the LATCH_CLIENT_SECRET in the production environment's .env.local file or secrets manager. This step is crucial during client secret rotation to ensure the application uses the newly generated secret for authentication. Always test thoroughly in staging first. ```env # Replace old secret with new secret LATCH_CLIENT_SECRET= ``` -------------------------------- ### Latch Client Mode Logging Source: https://github.com/lance0/latch/blob/master/docs/AUTHENTICATION_SETUP.md When LATCH_DEBUG is set to true, Latch provides startup logs indicating the current client mode. This allows for quick verification of the authentication flow being used. The logs clearly state whether the application is in 'Confidential' or 'Public (PKCE only)' mode. ```text [Latch] Client type: Confidential (with client_secret) # or [Latch] Client type: Public (PKCE only) ``` -------------------------------- ### Scaffold API Routes and Server Actions from Examples Source: https://github.com/lance0/latch/blob/master/packages/latch-cli/README.md Copies API routes and Server Actions from example applications. Can be used with or without specifying an example type. ```bash latch scaffold latch scaffold --example commercial ``` -------------------------------- ### Latch Environment Variables for Confidential Client Source: https://github.com/lance0/latch/blob/master/docs/AUTHENTICATION_SETUP.md Configuration for Latch using environment variables for the Confidential Client authentication mode. This mode requires a client secret and is typically used for server-side applications like Next.js. ```env # .env.local LATCH_CLIENT_ID=your-client-id LATCH_TENANT_ID=your-tenant-id LATCH_CLIENT_SECRET=your-client-secret # Include this! LATCH_CLOUD=commercial LATCH_SCOPES=openid profile User.Read LATCH_REDIRECT_URI=http://localhost:3000/api/latch/callback LATCH_COOKIE_SECRET= ``` -------------------------------- ### Copy Environment File (Bash) Source: https://github.com/lance0/latch/blob/master/apps/example-gcc-high/README.md Copies the example environment file to a local configuration file. This file will store sensitive credentials and cloud-specific settings. ```bash cp .env.example .env.local ``` -------------------------------- ### Install @lance0/latch-cli Globally or via npx Source: https://github.com/lance0/latch/blob/master/packages/latch-cli/README.md Instructions for installing the @lance0/latch-cli package globally using npm or for using it directly without installation via npx. ```bash # Global installation npm install -g @lance0/latch-cli # Or use with npx (no installation required) npx @lance0/latch-cli [command] ``` -------------------------------- ### Configure Environment Variables for Latch Source: https://github.com/lance0/latch/blob/master/apps/README.md Copies the example environment file and prompts the user to edit it with specific Azure AD configuration details. This is crucial for setting up the Latch authentication flow for a chosen cloud environment. ```bash cd example-commercial # or example-gcc-high cp .env.example .env.local # Edit .env.local with your Azure AD configuration ``` -------------------------------- ### Link Latch Package and Create Next.js App - Bash Source: https://github.com/lance0/latch/blob/master/TESTING_GUIDE.md Links @latch/core globally for use in new apps and creates a TypeScript Next.js project with Tailwind. Requires pnpm and Node.js; installs peer deps like Next.js 15 and React 19. Enables local development linking; no outputs beyond app structure. ```bash cd /home/lance/latch/packages/latch pnpm link --global cd ~ npx create-next-app@latest my-latch-test --typescript --tailwind --app --no-src-dir cd my-latch-test pnpm link --global @latch/core pnpm add next@^15.0.0 react@^19.0.0 react-dom@^19.0.0 node /home/lance/latch/packages/latch-cli/dist/index.js init ``` -------------------------------- ### Start OAuth Flow in TypeScript Source: https://github.com/lance0/latch/blob/master/TROUBLESHOOTING.md This TypeScript code demonstrates how to correctly initiate the Latch OAuth flow to avoid direct callback errors. It requires the LatchProvider context or API routes to be set up. The code redirects the user or handles sign-in; limitations include relying on browser cookies and PKCE timeouts. ```typescript // Always start the flow from /api/latch/start window.location.href = '/api/latch/start'; // Or use the button from LatchProvider const { signIn } = useLatch(); signIn(); // Handles the flow correctly ``` -------------------------------- ### Example .env.local File Generated by Latch CLI Source: https://github.com/lance0/latch/blob/master/packages/latch-cli/README.md An example of the .env.local file created by the `latch init` command, containing Latch configuration for Azure AD, cloud environment, OAuth, and cookie encryption. ```env # Latch Configuration - Azure Government GCC-High # Generated by @lance0/latch-cli on 2025-10-23 # Azure AD Application LATCH_CLIENT_ID=00000000-0000-0000-0000-000000000000 LATCH_TENANT_ID=11111111-1111-1111-1111-111111111111 LATCH_CLIENT_SECRET=your-client-secret-here # Only if Confidential Client # Cloud Environment LATCH_CLOUD=gcc-high # OAuth Configuration LATCH_SCOPES=openid profile User.Read LATCH_REDIRECT_URI=http://localhost:3000/api/latch/callback # Cookie Encryption Secret (NEVER commit this!) LATCH_COOKIE_SECRET= # Debug Mode (optional) LATCH_DEBUG=false # Next.js URL NEXTAUTH_URL=http://localhost:3000 ``` -------------------------------- ### Configure Environment Variables for Example App - Env Source: https://github.com/lance0/latch/blob/master/TESTING_GUIDE.md Sets up .env.local with Azure AD credentials and Latch config for commercial or government clouds. Depends on CLI-generated secret; replace placeholders with real values. Enables full auth flow; never commit to version control; supports scopes without .com for non-commercial clouds. ```env LATCH_CLIENT_ID= LATCH_TENANT_ID= LATCH_CLOUD=commercial # or gcc-high, dod LATCH_SCOPES=openid profile User.Read LATCH_REDIRECT_URI=http://localhost:3000/api/latch/callback LATCH_COOKIE_SECRET= ``` -------------------------------- ### Latch Environment Variables for Public Client (PKCE) Source: https://github.com/lance0/latch/blob/master/docs/AUTHENTICATION_SETUP.md Configuration for Latch using environment variables for the Public Client (PKCE) authentication mode. This mode does not use a client secret and is suitable for Single-Page Applications (SPAs) or when client secrets are not preferred. ```env # .env.local LATCH_CLIENT_ID=your-client-id LATCH_TENANT_ID=your-tenant-id # NO LATCH_CLIENT_SECRET - omit this line entirely LATCH_CLOUD=commercial LATCH_SCOPES=openid profile User.Read LATCH_REDIRECT_URI=http://localhost:3000/api/latch/callback LATCH_COOKIE_SECRET= ``` -------------------------------- ### Generate Cookie Secret Source: https://github.com/lance0/latch/blob/master/docs/AUTHENTICATION_SETUP.md Command to generate a secure, base64 encoded random string suitable for use as a cookie secret, as required by Latch configuration. ```bash openssl rand -base64 32 ``` -------------------------------- ### Latch Example App Directory Structure Source: https://github.com/lance0/latch/blob/master/llms.txt This snippet details the standard directory structure for Latch example applications. It highlights the organization of API routes for OAuth, server actions, protected pages, and the root layout containing the LatchProvider. It also points to the middleware and environment configuration file. ```tree apps/example-* ├── app/ │ ├── api/latch/ # Required OAuth routes │ │ ├── start/route.ts # Initiates OAuth flow with PKCE │ │ ├── callback/route.ts # Handles OAuth callback │ │ ├── session/route.ts # Returns current session │ │ ├── refresh/route.ts # Refreshes access token │ │ └── logout/route.ts # Clears session and logs out │ ├── actions/ # Server Actions examples │ │ ├── profile.ts # Read operations │ │ └── updateSettings.ts # Write operations │ ├── dashboard/ # Protected pages │ └── layout.tsx # Root layout with LatchProvider ├── middleware.ts # Route protection └── .env.example # Cloud-specific configuration template ``` -------------------------------- ### Set LATCH_CLOUD Options in Bash Environment Source: https://github.com/lance0/latch/blob/master/TROUBLESHOOTING.md This Bash example demonstrates valid LATCH_CLOUD values for Azure cloud configurations. It depends on the Latch project being initialized with environment variables. The snippet outputs environment variable settings; common limitations involve case-sensitivity and exact matching to predefined values. ```bash # Valid options (case-sensitive): LATCH_CLOUD=commercial # Azure Public Cloud LATCH_CLOUD=gcc-high # Azure Government GCC-High LATCH_CLOUD=dod # Azure Government DoD ``` -------------------------------- ### Install Latch with npm Source: https://github.com/lance0/latch/blob/master/docs/SERVER_ACTIONS.md Installs the latest version of the Latch package using npm. This is the first step to enable Latch authentication in your Next.js project. ```bash npm install @lance0/latch@latest ``` -------------------------------- ### Copy Example Routes for Latch Authentication Source: https://github.com/lance0/latch/blob/master/README.md Copies the necessary Latch authentication routes from the example app to your application's API directory. This provides basic functionality for handling authentication flows. ```bash cp -r node_modules/@lance0/latch/../../apps/example-app/app/api/latch app/api/ ``` -------------------------------- ### Implement Root Layout with LatchProvider - TSX Source: https://github.com/lance0/latch/blob/master/TESTING_GUIDE.md Wraps the app layout with LatchProvider for React context in Next.js. Depends on @latch/core/react import; enhances auth state management. Provides children to authenticated components; requires proper env setup for full functionality. ```tsx import { LatchProvider } from '@latch/core/react'; export default function RootLayout({ children }) { return ( {children} ); } ``` -------------------------------- ### Clone and Develop Latch Locally Source: https://github.com/lance0/latch/blob/master/README.md Instructions for cloning the Latch repository and setting up the development environment locally using pnpm, including installation and building the project. ```bash git clone https://github.com/lance0/latch.git cd latch pnpm install pnpm build ``` -------------------------------- ### Check Latch Client Mode with .env.local Source: https://github.com/lance0/latch/blob/master/docs/AUTHENTICATION_SETUP.md This bash command checks the presence of LATCH_CLIENT_SECRET in the .env.local file to determine if the application is running in Confidential Client or Public Client (PKCE) mode. If the secret is present, it indicates Confidential Client mode; otherwise, it's Public Client mode. This helps in diagnosing authentication flow issues. ```bash # Check your .env.local file cat .env.local | grep LATCH_CLIENT_SECRET # If present → Confidential Client mode # If absent → Public Client (PKCE) mode ``` -------------------------------- ### Debug LATCH_TOKEN_EXCHANGE_FAILED in Bash Source: https://github.com/lance0/latch/blob/master/TROUBLESHOOTING.md This Bash example provides debugging steps for token exchange failures by verifying credentials and enabling debug mode. It requires Azure Portal access and Latch debug settings. The output includes error logs; limitations depend on Azure AD service status and correct registration details. ```bash # 1. Verify Client ID matches Azure AD exactly LATCH_CLIENT_ID= # 2. Check redirect URI is registered # Azure Portal → App Registrations → Authentication # 3. Enable debug mode to see full error LATCH_DEBUG=true # 4. Check Azure AD service status # https://status.azure.com ``` -------------------------------- ### Install @lance0/latch Package Source: https://github.com/lance0/latch/blob/master/packages/latch/README.md Commands to add the @lance0/latch package to your project using different package managers (pnpm, npm, yarn). ```bash pnpm add @lance0/latch # or npm install @lance0/latch # or yarn add @lance0/latch ``` -------------------------------- ### Install Latch and Uninstall NextAuth.js Source: https://github.com/lance0/latch/blob/master/docs/MIGRATION_FROM_NEXTAUTH.md This command removes the existing NextAuth.js package and installs the Latch package. It's the first step in migrating your authentication system. ```bash npm uninstall next-auth npm install @lance0/latch ``` -------------------------------- ### Install Latch Package (Bash) Source: https://github.com/lance0/latch/blob/master/docs/MIGRATION_FROM_MSAL.md This snippet shows how to uninstall MSAL packages and install the Latch package using npm. It's the initial step in migrating your application's authentication. ```bash npm uninstall @azure/msal-browser @azure/msal-react npm install @lance0/latch ``` -------------------------------- ### GET /api/latch/start Source: https://github.com/lance0/latch/blob/master/docs/API_REFERENCE.md Initiates the OAuth 2.0 PKCE flow by redirecting the user to Azure AD for authentication. It generates and stores necessary PKCE parameters and state. ```APIDOC ## GET /api/latch/start ### Description Starts the OAuth flow by redirecting the user to Azure AD. This endpoint generates PKCE verifier and challenge, along with a random state and nonce. It stores these securely in an encrypted cookie with a 10-minute expiry before redirecting to the Azure AD authorize endpoint. ### Method GET ### Endpoint /api/latch/start ### Query Parameters #### Query Parameters - **returnTo** (string) - Optional - URL to redirect to after successful sign-in. ### Request Example ```html Sign In ``` ### Response This endpoint performs a redirect and does not return a response body in the traditional sense. ``` -------------------------------- ### Developing with Latch Source: https://github.com/lance0/latch/blob/master/README.md Contains commands for common development tasks in a Latch project, such as starting the development server, performing type checking, linting, and building the project. ```bash # Start development server pnpm dev # Type check pnpm typecheck # Lint pnpm lint # Build pnpm build ``` -------------------------------- ### Initiate Latch Authentication Source: https://github.com/lance0/latch/blob/master/docs/ARCHITECTURE.md Starts the Latch authentication process by generating PKCE parameters and redirecting the user to Azure AD for authentication. ```APIDOC ## GET /api/latch/start ### Description Initiates the Latch authentication flow. This endpoint generates necessary PKCE parameters (code verifier, challenge, state, nonce), stores them in an encrypted cookie, and redirects the user to the Azure AD authorization endpoint. ### Method GET ### Endpoint /api/latch/start ### Parameters #### Query Parameters - **returnTo** (string) - Optional - The URL to redirect the user to after successful authentication. ### Request Example GET /api/latch/start?returnTo=/dashboard ### Response #### Success Response (302 Redirect) - **Location**: Redirects to the Azure AD authorization URL. ### Azure AD URL Structure ``` https://login.microsoftonline.us/{tenant}/oauth2/v2.0/authorize?client_id={clientId}&response_type=code&redirect_uri={redirectUri}&scope=openid%20profile%20User.Read&state={state}&nonce={nonce}&code_challenge={challenge}&code_challenge_method=S256&response_mode=query ``` #### PKCE Data Stored in Cookie (Encrypted) ```json { "codeVerifier": "...", "state": "...", "nonce": "...", "returnTo": "/dashboard" } ``` ``` -------------------------------- ### Calling an Authenticated Azure Function Source: https://github.com/lance0/latch/blob/master/docs/ON_BEHALF_OF_FLOW.md This code example demonstrates how to make a POST request to an Azure Function API endpoint. It includes setting the 'Authorization' header with the obtained function token and sending a JSON payload. ```typescript const response = await fetch('https://my-func.azurewebsites.us/api/process', { method: 'POST', headers: { 'Authorization': `Bearer ${functionToken}`, 'Content-Type': 'application/json' }, body: JSON.stringify({ data: '...' }) }); ``` -------------------------------- ### Call Custom Downstream API with OBO Token Source: https://github.com/lance0/latch/blob/master/docs/ON_BEHALF_OF_FLOW.md Shows how to get an OBO token for a custom downstream API using its Application ID URI or client ID and specified scopes. The obtained token is then used to call the API. ```typescript import { oboTokenForApi } from '@lance0/latch'; export async function GET(request: NextRequest) { // Get OBO token for your downstream API const apiToken = await oboTokenForApi(request, { audience: 'api://my-downstream-api', // App ID URI or client ID scopes: ['api://my-downstream-api/.default'] // Or specific scopes }); // Call downstream API const response = await fetch('https://my-api.example.com/data', { headers: { Authorization: `Bearer ${apiToken}` } }); return NextResponse.json(await response.json()); } ``` -------------------------------- ### Initialize Latch Configuration with Interactive Wizard Source: https://github.com/lance0/latch/blob/master/packages/latch-cli/README.md Initiates an interactive wizard to set up Latch configuration. The wizard prompts for cloud environment, Azure AD credentials, client type, redirect URI, and scopes, then creates a .env.local file. ```bash npx @lance0/latch-cli init ``` -------------------------------- ### Generate LATCH_COOKIE_SECRET in Bash Source: https://github.com/lance0/latch/blob/master/TROUBLESHOOTING.md This Bash script generates a secure cookie secret using OpenSSL and sets the LATCH_COOKIE_SECRET environment variable. It depends on OpenSSL being installed on the system. The output is a secure secret in .env; limitations include not committing the secret to version control for security. ```bash # Generate a secure secret openssl rand -base64 32 # Add to .env (NEVER commit to git) LATCH_COOKIE_SECRET=your-generated-secret-here ``` -------------------------------- ### Test Latch Session Endpoint with curl Source: https://github.com/lance0/latch/blob/master/TROUBLESHOOTING.md This snippet demonstrates how to test the Latch session endpoint using curl. It sends a GET request to `http://localhost:3000/api/latch/session` and includes a `latch_id` cookie. The expected response is a 200 status code with user data if authenticated, or a 401 if not. ```bash # Test session endpoint curl -i http://localhost:3000/api/latch/session \ -H "Cookie: latch_id=" # Should return 200 with user data or 401 if not authenticated ``` -------------------------------- ### Configure Latch for Government Clouds Source: https://github.com/lance0/latch/blob/master/docs/AUTHENTICATION_SETUP.md This configuration snippet shows how to set the LATCH_CLOUD environment variable for Azure Government clouds (GCC-High, DoD). This is necessary to ensure Latch uses the correct portal URL for these specific government environments. The value can be set to 'gcc-high' or 'dod'. ```env LATCH_CLOUD=gcc-high # or 'dod' ``` -------------------------------- ### Configure Environment Variables for Latch Source: https://github.com/lance0/latch/blob/master/apps/example-commercial/README.md Sets up the local environment variables required for Latch authentication with Azure AD. This involves copying a template file and populating it with specific Azure AD and Latch configuration details. ```bash cp .env.example .env.local ``` ```env LATCH_CLIENT_ID=your-client-id LATCH_TENANT_ID=your-tenant-id LATCH_CLOUD=commercial LATCH_SCOPES=openid profile email User.Read offline_access LATCH_REDIRECT_URI=http://localhost:3000/api/latch/callback LATCH_COOKIE_SECRET=$(openssl rand -base64 32) ``` -------------------------------- ### Test CLI Init Wizard - Bash Source: https://github.com/lance0/latch/blob/master/TESTING_GUIDE.md Runs the init wizard to create .env.local with Azure AD config prompts for cloud, client ID, tenant ID, redirect URI, and scopes. Requires test directory; uses fake UUIDs for simulation. Outputs populated .env.local file; validates inputs like UUID format. ```bash mkdir ../latch-test cd ../latch-test node ../latch/packages/latch-cli/dist/index.js init cat .env.local ``` -------------------------------- ### Get App-Only Token for Server-to-Server Calls in TypeScript Source: https://github.com/lance0/latch/blob/master/docs/ON_BEHALF_OF_FLOW.md Illustrates obtaining an application-only token for background jobs or server-to-server scenarios without user context. This approach uses client credentials flow and avoids OBO when user delegation is not needed. Suitable for tasks without user identity, but not for user-specific permissions. ```typescript // ❌ DON'T use OBO for background jobs // Use application permissions with client credentials flow const appToken = await getAppOnlyToken(); ``` -------------------------------- ### Read Latch Client Secret from Azure Key Vault Source: https://github.com/lance0/latch/blob/master/docs/AUTHENTICATION_SETUP.md This TypeScript code snippet shows how to retrieve the LATCH_CLIENT_SECRET from Azure Key Vault instead of a local .env file. It utilizes the '@azure/keyvault-secrets' SDK to fetch the secret value, which can then be set as an environment variable. This approach enhances security by centralizing secret management. ```typescript // Read from Key Vault instead of .env import { SecretClient } from '@azure/keyvault-secrets'; const client = new SecretClient(vaultUrl, credential); const secret = await client.getSecret('latch-client-secret'); process.env.LATCH_CLIENT_SECRET = secret.value; ``` -------------------------------- ### Enable HTTPS for Production in Bash Source: https://github.com/lance0/latch/blob/master/TROUBLESHOOTING.md This Bash configuration ensures HTTPS is used in production to allow secure cookies. It relies on NODE_ENV setting and proxy headers. No explicit inputs/outputs; it's environment setup. Works behind proxies like Vercel if headers are correctly set; limitations include manual header verification for proxies. ```bash # Ensure your production environment uses HTTPS # Latch automatically enables `secure` cookies when NODE_ENV=production # If behind a proxy (Vercel, CloudFlare, etc): # Ensure X-Forwarded-Proto header is set ``` -------------------------------- ### MSAL Initialization vs Latch Configuration Source: https://github.com/lance0/latch/blob/master/docs/MIGRATION_FROM_MSAL.md Compares the initialization process for MSAL, which requires explicit configuration and application instantiation, with Latch, which relies on environment variables for configuration. ```typescript const msalConfig = { auth: { clientId: '...', authority: '...', redirectUri: '...', }, cache: { cacheLocation: 'sessionStorage', }, system: { allowNativeBroker: false, } }; const pca = new PublicClientApplication(msalConfig); await pca.initialize(); ``` ```env LATCH_CLIENT_ID=... LATCH_TENANT_ID=... LATCH_CLOUD=commercial ``` -------------------------------- ### Manual .env.local Configuration for Latch Source: https://github.com/lance0/latch/blob/master/packages/latch/README.md Example of manual configuration for Latch by creating a .env.local file. This includes Azure AD details, cookie encryption secret, and optional confidential client mode settings. ```env # Azure AD Configuration LATCH_CLIENT_ID=your-client-id LATCH_TENANT_ID=your-tenant-id LATCH_CLOUD=commercial # or gcc-high, dod # Cookie Encryption (generate with: npx @lance0/latch-cli generate-secret) LATCH_COOKIE_SECRET=your-base64-secret-here # Optional: Confidential Client Mode # LATCH_CLIENT_SECRET=your-client-secret # Optional: Custom Configuration # LATCH_SCOPES=openid profile User.Read # LATCH_REDIRECT_URI=http://localhost:3000/api/latch/callback ``` -------------------------------- ### Build and Run @lance0/latch-cli Locally in Monorepo Source: https://github.com/lance0/latch/blob/master/packages/latch-cli/README.md Commands to build the @lance0/latch-cli package and run its commands locally from the root of a monorepo using pnpm. ```bash # From root pnpm --filter @lance0/latch-cli build # Run locally node packages/latch-cli/dist/index.js generate-secret node packages/latch-cli/dist/index.js init ``` -------------------------------- ### Obtain OBO Token for Microsoft Graph in TypeScript Source: https://github.com/lance0/latch/blob/master/docs/ON_BEHALF_OF_FLOW.md This example demonstrates how to use the Latch OBO module to acquire an On-Behalf-Of token for calling Microsoft Graph from a Next.js API route. It requires an incoming request with a valid user token and depends on the @lance0/latch/obo import. Outputs a token for downstream API calls, but limits to delegated permissions only. ```typescript import { oboTokenForGraph } from '@lance0/latch/obo'; export async function GET(request: NextRequest) { const graphToken = await oboTokenForGraph(request); // Use token to call Microsoft Graph... } ``` -------------------------------- ### Get Authenticated Session in Next.js Server Components (TypeScript) Source: https://context7.com/lance0/latch/llms.txt This example demonstrates how to retrieve the authenticated user session within a Next.js Server Component. It uses `getServerSession` from the '@lance0/latch' package, which requires a cookie secret for decryption. If the user is not authenticated, they are redirected to the login page. The authenticated user's details (sub, email, name) are then accessible. ```typescript // app/dashboard/page.tsx import { getServerSession } from '@lance0/latch'; import { redirect } from 'next/navigation'; export default async function DashboardPage() { const session = await getServerSession(process.env.LATCH_COOKIE_SECRET!); if (!session.isAuthenticated) { redirect('/api/latch/start?returnTo=/dashboard'); } // session.user is guaranteed to exist here const { sub, email, name } = session.user; return (

Dashboard

User ID: {sub}

Email: {email}

Name: {name}

); } ``` -------------------------------- ### Running Latch Tests Source: https://github.com/lance0/latch/blob/master/README.md This snippet outlines the commands used for running tests within a Latch project. It includes options for standard tests, tests with code coverage, and tests with a UI. ```bash # Run tests pnpm test # Run tests with coverage pnpm test:coverage # Run tests with UI pnpm test:ui ``` -------------------------------- ### Latch Authentication Flow Steps Source: https://github.com/lance0/latch/blob/master/llms.txt This outlines the sequence of events during the Latch authentication process. It starts with user sign-in, redirection to the Latch API for initiating the OAuth flow with PKCE, Azure AD authentication, callback handling, token exchange and verification, and finally session storage and redirection. ```text 1. User clicks sign in → redirected to `/api/latch/start` 2. PKCE code verifier/challenge generated, stored in encrypted cookie 3. Redirected to Azure AD with PKCE challenge 4. User authenticates with Azure AD 5. Azure redirects to `/api/latch/callback` with authorization code 6. Exchange code for tokens using PKCE verifier 7. Verify ID token with JWKS 8. Store user info and refresh token in encrypted cookies 9. Redirect to app with authenticated session ``` -------------------------------- ### Latch Testing Commands Source: https://github.com/lance0/latch/blob/master/llms.txt Provides the command-line instructions for running tests within the Latch project. It includes commands for executing all tests, running tests in watch mode, and performing TypeScript type checking. These commands are executed from the `packages/latch` directory. ```bash cd packages/latch pnpm test # Run all tests pnpm test:watch # Watch mode pnpm typecheck # TypeScript check ``` -------------------------------- ### Latch Scope Configuration for GCC-High Source: https://github.com/lance0/latch/blob/master/apps/README.md Illustrates correct and incorrect ways to configure LATCH_SCOPES for Azure Government (GCC-High). It shows how Latch can auto-expand scopes or how to explicitly define the .us Graph API endpoint. ```env # ❌ WRONG for GCC-High LATCH_SCOPES=https://graph.microsoft.com/User.Read # ✅ CORRECT for GCC-High LATCH_SCOPES=User.Read # Latch auto-expands to .us endpoint # Or explicitly: LATCH_SCOPES=https://graph.microsoft.us/User.Read ``` -------------------------------- ### Configure Environment Variables (.env.local) Source: https://github.com/lance0/latch/blob/master/apps/example-gcc-high/README.md Sets up environment variables for Latch authentication in Azure Government Cloud. This includes client ID, tenant ID, cloud environment, scopes, redirect URI, and a cookie secret for secure session management. ```env LATCH_CLIENT_ID=your-client-id LATCH_TENANT_ID=your-tenant-id LATCH_CLOUD=gcc-high LATCH_SCOPES=openid profile email User.Read offline_access LATCH_REDIRECT_URI=http://localhost:3000/api/latch/callback LATCH_COOKIE_SECRET=$(openssl rand -base64 32) ``` -------------------------------- ### Initiate OAuth 2.0 PKCE Flow with Azure AD (TypeScript) Source: https://context7.com/lance0/latch/llms.txt This TypeScript code snippet defines the GET handler for the OAuth flow start endpoint. It retrieves configuration, generates PKCE parameters (code verifier, challenge, state, nonce), validates the return URL, encrypts PKCE data into a cookie, and constructs the Azure AD authorization URL. Dependencies include several functions from '@lance0/latch' and Next.js server components. It takes no direct input parameters other than those from the request URL and configuration, and outputs a redirect response to the Azure AD authorization endpoint. ```typescript import { NextRequest, NextResponse } from 'next/server'; import { getLatchConfig, getAzureEndpoints, validateScopes, generateCodeVerifier, generateCodeChallenge, generateState, generateNonce, seal, validateReturnUrl, COOKIE_NAMES, COOKIE_OPTIONS, type PKCEData, } from '@lance0/latch'; export async function GET(request: NextRequest) { const config = getLatchConfig(); const endpoints = getAzureEndpoints(config.cloud, config.tenantId); // Validate scopes match cloud environment (prevents .com scopes in .us cloud) validateScopes(config.scopes || [], config.cloud); // Generate PKCE parameters for secure authorization const codeVerifier = generateCodeVerifier(); // 43-char random string const codeChallenge = await generateCodeChallenge(codeVerifier); // SHA256 hash const state = generateState(); // CSRF protection const nonce = generateNonce(); // Replay attack prevention // Validate returnTo URL prevents open redirect attacks const returnTo = request.nextUrl.searchParams.get('returnTo'); const validatedReturnTo = validateReturnUrl(returnTo, new URL(request.url).origin); // Store PKCE data in encrypted cookie (10-min expiry) const pkceData: PKCEData = { codeVerifier, state, nonce, returnTo: validatedReturnTo, }; const sealedPkce = await seal(pkceData, config.cookieSecret!); // Use ! as cookieSecret is expected to be defined // Build Azure AD authorization URL const authUrl = new URL(endpoints.authorizeUrl); authUrl.searchParams.set('client_id', config.clientId); authUrl.searchParams.set('response_type', 'code'); authUrl.searchParams.set('redirect_uri', config.redirectUri!); // Use ! as redirectUri is expected to be defined authUrl.searchParams.set('scope', config.scopes?.join(' ') || ''); authUrl.searchParams.set('state', state); authUrl.searchParams.set('nonce', nonce); authUrl.searchParams.set('code_challenge', codeChallenge); authUrl.searchParams.set('code_challenge_method', 'S256'); authUrl.searchParams.set('response_mode', 'query'); const response = NextResponse.redirect(authUrl.toString()); response.cookies.set(COOKIE_NAMES.PKCE_DATA, sealedPkce, { ...COOKIE_OPTIONS, maxAge: 60 * 10, // 10 minutes }); return response; } ```