### Install and Initialize Authentication Kit via npm Source: https://www.transcodes.io/docs/authentication-cluster/installation-guide Installs the SDK package and initializes it within the application code. This approach uses named exports rather than the global window object. ```bash npm install @bigstrider/transcodes-sdk ``` ```javascript import { init } from '@bigstrider/transcodes-sdk'; await init({ projectId: 'YOUR_PROJECT_ID' }); // Optional: await init({ projectId: 'YOUR_PROJECT_ID', customUserId: 'uid_xxx', debug: true }); ``` -------------------------------- ### SDK Setup and Configuration Source: https://www.transcodes.io/docs/quick-integration Instructions on how to load the Transcodes.io SDK using either a CDN script tag or npm, and how to set up environment variables for project identification. ```APIDOC ## SDK Setup and Configuration This section details the two primary methods for integrating the Transcodes.io SDK into your project: using a CDN script tag or via npm. ### Option A: Load the SDK via CDN Script This method involves adding a script tag to your HTML file. The exact script URL depends on your project setup and whether you are building a Progressive Web App (PWA). **For Vite (React, Vue, Vanilla JS) - Authentication Toolkit Cluster:** ```html ``` **For Web App Toolkit Cluster (PWA) - Requires Manifest and Service Worker:** ```html ``` **Service Worker (sw.js) for PWA:** 1. Download `sw.js` from the Transcodes Dashboard (Web App Cluster → Installation Guide). 2. Place it in your project's public directory (e.g., `public/sw.js` for Vite and Next.js) so it's served at the root. **For Next.js:** Use the `next/script` component with `strategy="beforeInteractive"` and the same CDN URLs. For PWAs, include the manifest in `` and place `sw.js` in the `public/` directory. ### Option B: Load the SDK via npm This method avoids script tags and requires calling `await init({ projectId })` from your client entry point. Note that PWA install flows cannot be solely npm-based at this time. ### Set Environment Variables Configure your project's environment variables to include your Transcodes.io Project ID. **For Vite (React, Vue, Vanilla JS):** Create or update a `.env` file: ```env VITE_TRANSCODES_PROJECT_ID=proj_abc123xyz ``` **For Next.js:** Create or update a `.env.local` file: ```env NEXT_PUBLIC_TRANSCODES_PROJECT_ID=proj_abc123xyz ``` ``` -------------------------------- ### Initialize Authentication Kit via HTML/CDN Source: https://www.transcodes.io/docs/authentication-cluster/installation-guide Loads the Authentication Kit using a script tag. This method provides access to the global 'transcodes' API and is recommended for standard web implementations. ```html ``` -------------------------------- ### Framework Examples for Passkey Login Source: https://www.transcodes.io/docs/demonstration/history-log/step-2-passkey-events Provides examples of implementing Passkey login event tracking within different JavaScript frameworks. Each example shows how to integrate the `transcodes.openAuthLoginModal` and `transcodes.trackUserAction` functions into framework-specific event handlers. ```javascript const handleLogin = async () => { const result = await transcodes.openAuthLoginModal(); if (result.success) { await transcodes.trackUserAction({ tag: 'user:login', metadata: { method: 'passkey' }, }); } }; ``` ```javascript const handleLogin = async () => { const result = await transcodes.openAuthLoginModal(); if (result.success) { await transcodes.trackUserAction({ tag: 'user:login', metadata: { method: 'passkey' }, }); } }; ``` ```javascript loginBtn.addEventListener('click', async () => { const result = await transcodes.openAuthLoginModal(); if (result.success) { await transcodes.trackUserAction({ tag: 'user:login', metadata: { method: 'passkey' }, }); } }); ``` -------------------------------- ### Framework Examples for Admin Access MFA Source: https://www.transcodes.io/docs/demonstration/history-log/step-3-mfa-events This section provides examples of implementing MFA for admin access within different JavaScript frameworks: React, Vue, and Vanilla JS. All examples follow a similar pattern of initiating MFA, checking for success, tracking the action, and then redirecting the user. ```javascript const handleAdminAccess = async () => { const mfaResult = await transcodes.openAuthIdpModal({ resource: 'admin', action: 'read', }); if (mfaResult.success && mfaResult.payload[0]?.success) { await transcodes.trackUserAction({ tag: 'admin:access', severity: 'high', metadata: { action: 'read' }, }); window.location.href = '/admin'; } }; ``` ```javascript const handleAdminAccess = async () => { const mfaResult = await transcodes.openAuthIdpModal({ resource: 'admin', action: 'read', }); if (mfaResult.success && mfaResult.payload[0]?.success) { await transcodes.trackUserAction({ tag: 'admin:access', severity: 'high', metadata: { action: 'read' }, }); window.location.href = '/admin'; } }; ``` ```javascript adminBtn.addEventListener('click', async () => { const mfaResult = await transcodes.openAuthIdpModal({ resource: 'admin', action: 'read', }); if (mfaResult.success && mfaResult.payload[0]?.success) { await transcodes.trackUserAction({ tag: 'admin:access', severity: 'high', metadata: { action: 'read' }, }); window.location.href = '/admin'; } }); ``` -------------------------------- ### Opening Modals and Checking Authentication Source: https://www.transcodes.io/docs/quick-integration Guides on how to trigger the authentication login modal and how to check the current authentication status of the user. ```APIDOC ## Opening Modals and Checking Authentication This section covers how to programmatically open authentication-related modals and how to verify if a user is currently authenticated. ### Open Login Modal Trigger the Transcodes.io login modal to initiate the authentication process. **Using CDN (`window.transcodes`):** ```javascript const result = await transcodes.openAuthLoginModal({ projectId: 'proj_abc123xyz', }); if (result.success) { const { token, member } = result.payload[0]; console.log('Logged in as:', member?.email); } ``` **Using npm (named exports):** ```javascript import { openAuthLoginModal } from '@bigstrider/transcodes-sdk'; const result = await openAuthLoginModal({ webhookNotification: false }); if (result.success) { const { token, member } = result.payload[0]; console.log('Logged in as:', member?.email); } ``` ### Check Authentication Status The `isAuthenticated()` method is asynchronous and requires the `await` keyword. **Using CDN:** ```javascript const isAuth = await transcodes.token.isAuthenticated(); ``` **Using npm:** ```javascript import { isAuthenticated } from '@bigstrider/transcodes-sdk'; const isAuth = await isAuthenticated(); ``` ``` -------------------------------- ### Install and Initialize SDK via npm Source: https://www.transcodes.io/docs/demonstration/stepup-mfa/import-cdn This snippet demonstrates how to install the Transcodes SDK using npm and then initialize it within your application. Replace 'YOUR_PROJECT_ID' with your project's unique identifier. After initialization, you can import and use other APIs like 'openAuthIdpModal'. ```bash npm install @bigstrider/transcodes-sdk ``` ```javascript import { init } from '@bigstrider/transcodes-sdk'; await init({ projectId: 'YOUR_PROJECT_ID' }); ``` -------------------------------- ### Install Transcodes SDK Source: https://www.transcodes.io/docs Command to install the Transcodes SDK package via the npm registry for use in modern JavaScript/TypeScript projects. ```bash npm install @bigstrider/transcodes-sdk ``` -------------------------------- ### Configure PWA Manifest and Service Worker via HTML Source: https://www.transcodes.io/docs/web-app-cluster/installation-guide Add these tags to your document head or early load script to link the PWA manifest and initialize the web worker. This is required for PWA installability features and cannot be achieved through the npm SDK alone. ```html ``` -------------------------------- ### Implement Custom PWA Install Button Source: https://www.transcodes.io/docs/web-app-cluster/widget This snippet demonstrates how to define a custom HTML button that triggers the PWA installation prompt. The element must have an ID that matches the configuration in the widget settings to allow the SDK to attach the click event listener. ```html ``` -------------------------------- ### Vanilla JS Example: Login Button Source: https://www.transcodes.io/docs/demonstration/passkey-login/call-login-modal A Vanilla JavaScript example demonstrating how to attach an event listener to a login button. When clicked, it opens the passkey login modal and updates the UI with the user's email upon successful authentication. ```javascript const loginBtn = document.getElementById('login-btn'); loginBtn.addEventListener('click', async () => { const result = await transcodes.openAuthLoginModal({}); if (result.success) { const member = result.payload[0].member; document.getElementById('member-name').textContent = member?.email ?? ''; } }); ``` -------------------------------- ### Handle SDK Events with Practical Examples Source: https://www.transcodes.io/docs/api-reference/events Implementation examples for handling specific SDK events like authentication changes, token refreshes, expirations, and error logging. ```typescript // Handle AUTH_STATE_CHANGED transcodes.on('AUTH_STATE_CHANGED', (payload) => { if (payload.isAuthenticated) { console.log('Member signed in'); } else { console.log('Member signed out'); } }); // Handle TOKEN_REFRESHED transcodes.on('TOKEN_REFRESHED', (payload) => { apiClient.setToken(payload.accessToken); }); // Handle TOKEN_EXPIRED transcodes.on('TOKEN_EXPIRED', (payload) => { window.location.href = '/login'; }); // Handle ERROR transcodes.on('ERROR', (payload) => { console.error(`[${payload.context}] ${payload.code}: ${payload.message}`); }); ``` -------------------------------- ### Handle Async Authentication and SDK Methods Source: https://www.transcodes.io/docs/quick-integration Corrects common mistakes regarding asynchronous authentication checks and method naming conventions. ```javascript // Correct usage of async authentication check if (await isAuthenticated()) { // Proceed with authenticated logic } // Correct usage of signOut await signOut({ webhookNotification: false }); ``` -------------------------------- ### Install JWT Verification Dependencies Source: https://www.transcodes.io/docs/demonstration/passkey-login/server-side Lists the necessary packages to install for various programming languages to support local JWT verification. ```bash npm install jsonwebtoken jwks-rsa ``` ```bash pip install pyjwt cryptography ``` ```xml io.jsonwebtoken jjwt-api 0.12.5 io.jsonwebtoken jjwt-impl 0.12.5 runtime io.jsonwebtoken jjwt-jackson 0.12.5 runtime ``` ```bash go get github.com/golang-jwt/jwt/v5 ``` ```bash composer require firebase/php-jwt ``` ```bash gem install jwt ``` -------------------------------- ### Integrate MFA Modal in Frontend Frameworks Source: https://www.transcodes.io/docs/demonstration/stepup-mfa/call-mfa-modal Examples of integrating the MFA modal into React, Vue, and Vanilla JS applications. Each example handles loading states and conditional navigation based on verification success. ```react import { useState } from 'react'; function AdminButton() { const [loading, setLoading] = useState(false); const handleAdminAccess = async () => { setLoading(true); try { const mfaResult = await transcodes.openAuthIdpModal({ resource: 'admin', action: 'read' }); if (mfaResult.success && mfaResult.payload[0]?.success) { window.location.href = '/admin'; } } finally { setLoading(false); } }; return ; } ``` ```vue ``` ```javascript const adminBtn = document.getElementById('admin-btn'); adminBtn.addEventListener('click', async () => { adminBtn.disabled = true; try { const mfaResult = await transcodes.openAuthIdpModal({ resource: 'admin', action: 'read' }); if (mfaResult.success && mfaResult.payload[0]?.success) window.location.href = '/admin'; } finally { adminBtn.disabled = false; } }); ``` -------------------------------- ### Handling Authentication Events and Signing Out Source: https://www.transcodes.io/docs/quick-integration Information on subscribing to authentication state changes and how to sign a user out of the application. ```APIDOC ## Handling Authentication Events and Signing Out This section explains how to subscribe to real-time changes in authentication status and how to implement the sign-out functionality. ### Subscribe to Auth Events Listen for changes in the authentication state. The `on` method returns an unsubscribe function. **Using CDN:** ```javascript const unsubscribe = transcodes.on('AUTH_STATE_CHANGED', (payload) => { console.log('Auth state:', payload.isAuthenticated); }); // To stop listening: unsubscribe(); ``` **Using npm:** ```javascript import { on } from '@bigstrider/transcodes-sdk'; const unsubscribe = on('AUTH_STATE_CHANGED', (payload) => { console.log('Auth state:', payload.isAuthenticated); }); // To stop listening: unsubscribe(); ``` ### Sign Out Log the user out of the application. **Using CDN:** ```javascript await transcodes.token.signOut(); ``` **Using npm:** ```javascript import { signOut } from '@bigstrider/transcodes-sdk'; await signOut({ webhookNotification: false }); ``` ``` -------------------------------- ### Initialize and Use Transcodes SDK Source: https://www.transcodes.io/docs/quick-integration Demonstrates the named exports available in the @bigstrider/transcodes-sdk package for managing authentication, user sessions, and event listeners. ```typescript import { init, openAuthLoginModal, isAuthenticated, getCurrentMember, signOut, on } from '@bigstrider/transcodes-sdk'; // Usage example await init({ projectId: 'your-id' }); if (await isAuthenticated()) { const member = await getCurrentMember(); console.log(member); } ``` -------------------------------- ### Get Build Information for Dynamic Transcodes SDK Source: https://www.transcodes.io/docs/api-reference/init-config Retrieves build information for the Dynamic Transcodes SDK, including the build timestamp. ```typescript transcodes.getBuildInfo(): TranscodesBuildInfo ``` ```typescript interface TranscodesBuildInfo { buildTimestamp: string; } ``` -------------------------------- ### Configure TypeScript Definitions Source: https://www.transcodes.io/docs/quick-integration Instructions for setting up TypeScript support by downloading the SDK definitions and updating the tsconfig.json file. ```bash curl -o transcodes.d.ts https://cdn.transcodes.link/types/transcodes.d.ts ``` ```json { "compilerOptions": { "typeRoots": ["./node_modules/@types", "./types"] }, "include": ["src", "types"] } ``` -------------------------------- ### Configure Content Security Policy (CSP) Source: https://www.transcodes.io/docs/quick-integration Provides a template for setting up CSP headers to allow the Transcodes SDK and API domains. ```html ``` -------------------------------- ### TypeScript Configuration Example (tsconfig.json) Source: https://www.transcodes.io/docs/api-reference/types An example `tsconfig.json` configuration demonstrating how to include custom type definitions, such as those for transcodes.io, into your project's type resolution paths. ```json { "compilerOptions": { "typeRoots": ["./node_modules/@types", "./types"] }, "include": ["src", "types"] } ``` -------------------------------- ### Check if PWA is Installed Source: https://www.transcodes.io/docs/api-reference/init-config Determines if the Progressive Web App (PWA) associated with the Transcodes SDK is installed on the user's device. ```typescript transcodes.isPwaInstalled(): boolean ``` -------------------------------- ### Initialize SDK via npm Provider Source: https://www.transcodes.io/docs/quick-integration/nextjs Install the Transcodes SDK package and initialize it within a client-side provider component to manage authentication state across the application. ```bash npm install @bigstrider/transcodes-sdk ``` ```tsx 'use client'; import { useEffect, useState, type ReactNode } from 'react'; import { init } from '@bigstrider/transcodes-sdk'; export function TranscodesInitProvider({ children }: { children: ReactNode }) { const [ready, setReady] = useState(false); useEffect(() => { void init({ projectId: process.env.NEXT_PUBLIC_TRANSCODES_PROJECT_ID!, }).then(() => setReady(true)); }, []); if (!ready) return null; return <>{children}; } ``` -------------------------------- ### Verify Transcodes SDK Initialization in Browser Console Source: https://www.transcodes.io/docs/demonstration/passkey-login/import-cdn This snippet shows how to verify that the Transcodes SDK has been loaded and initialized correctly by logging the global `transcodes` object to the browser console. This confirms the availability of SDK functions like `openAuthLoginModal`. ```javascript console.log(transcodes); // e.g. openAuthLoginModal, token, on, trackUserAction, … ``` -------------------------------- ### CDN SDK API Overview Source: https://www.transcodes.io/docs/quick-integration A comprehensive list of available methods and properties for the Transcodes.io SDK when used via CDN (`window.transcodes`). ```APIDOC ## CDN SDK API Overview (`window.transcodes`) This section provides a reference for the methods available through the `window.transcodes` object when using the SDK via a CDN. ### Token Management - `transcodes.token.getCurrentMember(): Promise`: Retrieves the currently logged-in member's data. - `transcodes.token.getAccessToken(): Promise`: Fetches the current access token. - `transcodes.token.hasToken(): boolean`: Checks if a token exists locally. - `transcodes.token.isAuthenticated(): Promise`: Asynchronously checks if the user is authenticated. - `transcodes.token.signOut(options?: { webhookNotification?: boolean }): Promise`: Signs the user out. Optionally sends a webhook notification. ### Member Information - `transcodes.member.get(params): Promise>`: Fetches member data based on provided parameters. ### Modals - `transcodes.openAuthLoginModal(params): Promise>`: Opens the authentication login modal. - `transcodes.openAuthConsoleModal(params?): Promise>`: Opens the authentication console modal. - `transcodes.openAuthAdminModal(params): Promise>`: Opens the authentication admin modal. - `transcodes.openAuthIdpModal(params): Promise>`: Opens the authentication Identity Provider modal. ### Event Handling - `transcodes.on(event, callback): () => void`: Subscribes to SDK events. Returns an unsubscribe function. - `transcodes.off(event, callback): void`: Unsubscribes from SDK events. ### User Action Tracking - `transcodes.trackUserAction(event, options?): Promise`: Tracks a user-initiated action within the application. ``` -------------------------------- ### Integrate Transcodes via npm SDK Source: https://www.transcodes.io/docs/introduction Install the official SDK and initialize it within a bundled application environment. This approach provides more control over configuration, such as disabling webhook notifications. ```bash npm install @bigstrider/transcodes-sdk ``` ```javascript import * as Transcodes from '@bigstrider/transcodes-sdk'; await Transcodes.init({ projectId: '{PROJECT_ID}' }); const result = await Transcodes.openAuthLoginModal({ webhookNotification: false }); ``` -------------------------------- ### Handle Account Without MFA using Transcodes.io SDK (JavaScript) Source: https://www.transcodes.io/docs/demonstration/stepup-mfa/handle-mfa-response This snippet demonstrates how to check if a signed-in member has MFA set up and prompt them to configure it if they haven't. It uses the `transcodes.openAuthIdpModal` function to initiate an authentication flow and `transcodes.openAuthConsoleModal` to open the MFA setup panel. ```javascript const mfaResult = await transcodes.openAuthIdpModal({ resource: 'sensitive_action', action: 'delete', forceStepUp: true, }); if (!mfaResult.success || !mfaResult.payload[0]?.success) { // Redirect to MFA setup in console panel alert('Please set up MFA first'); await transcodes.openAuthConsoleModal(); // Opens console panel for MFA setup } ``` -------------------------------- ### React App Setup with Protected Routes Source: https://www.transcodes.io/docs/quick-integration/react Sets up the main React application using React Router and AuthProvider. It defines routes for the home page and a protected dashboard page, ensuring only authenticated users can access the dashboard. ```typescript import { BrowserRouter, Routes, Route } from 'react-router-dom'; import { AuthProvider } from './context/AuthContext'; import { ProtectedRoute } from './components/ProtectedRoute'; import { HomePage } from './pages/HomePage'; import { DashboardPage } from './pages/DashboardPage'; function App() { return ( } /> } /> ); } export default App; ``` -------------------------------- ### Load Transcodes SDK for PWA via HTML/CDN Source: https://www.transcodes.io/docs/demonstration/passkey-login/import-cdn This snippet shows how to load the Transcodes SDK for a Progressive Web App (PWA) using CDN links for the web worker and manifest. Ensure you also serve a `sw.js` file at the root. Replace `{YOUR_PROJECT_ID}` with your actual project ID. ```html ``` -------------------------------- ### Example Metadata JSON for User Creation Source: https://www.transcodes.io/docs/authentication-cluster/audit-logs This snippet demonstrates the expected JSON format for the Metadata field when adding a new user. The Metadata field requires valid JSON to ensure successful form submission. ```json { "department": "sales", "plan": "pro" } ``` -------------------------------- ### Transcodes.io SDK API Overview (CDN) Source: https://www.transcodes.io/docs/quick-integration Provides an overview of the available methods for the Transcodes.io SDK when accessed via CDN (`window.transcodes`). Includes token management, member retrieval, modal interactions, event handling, and user action tracking. ```javascript // Token transcodes.token.getCurrentMember(): Promise transcodes.token.getAccessToken(): Promise transcodes.token.hasToken(): boolean transcodes.token.isAuthenticated(): Promise // async! transcodes.token.signOut(options?: { webhookNotification?: boolean }): Promise // Member transcodes.member.get(params): Promise> // Modals transcodes.openAuthLoginModal(params): Promise> transcodes.openAuthConsoleModal(params?): Promise> transcodes.openAuthAdminModal(params): Promise> transcodes.openAuthIdpModal(params): Promise> // Events transcodes.on(event, callback): () => void transcodes.off(event, callback): void // Audit transcodes.trackUserAction(event, options?): Promise ``` -------------------------------- ### React Example: Login Button Source: https://www.transcodes.io/docs/demonstration/passkey-login/call-login-modal A React component that displays a login button. Clicking the button triggers the passkey login modal. If successful, it updates the component state to show a welcome message with the user's email. ```javascript import { useState } from 'react'; function LoginButton() { const [member, setMember] = useState(null); const handleLogin = async () => { const result = await transcodes.openAuthLoginModal({}); if (result.success) { setMember(result.payload[0].member); } }; return (
{member ? (

Welcome, {member.email}!

) : ( )}
); } ``` -------------------------------- ### Vue Example: Login Button Source: https://www.transcodes.io/docs/demonstration/passkey-login/call-login-modal A Vue 3 component using the Composition API to handle passkey login. It displays a login button and, upon successful authentication, shows a welcome message with the user's email. ```javascript ``` -------------------------------- ### Implement Auth State Handling in Frontend Frameworks Source: https://www.transcodes.io/docs/demonstration/passkey-login/listen-state Provides implementation patterns for managing authentication state in React, Vue, and Vanilla JS. These examples show how to attach and clean up event listeners to prevent memory leaks. ```react import { useState, useEffect } from 'react'; function useAuth() { const [member, setMember] = useState(null); const [isAuthenticated, setIsAuthenticated] = useState(false); useEffect(() => { const handleAuthChange = (payload) => { setIsAuthenticated(payload.isAuthenticated); setMember(payload.member || null); }; transcodes.on('AUTH_STATE_CHANGED', handleAuthChange); return () => transcodes.off('AUTH_STATE_CHANGED', handleAuthChange); }, []); return { member, isAuthenticated }; } ``` ```vue ``` ```javascript function updateUI(payload) { const memberElement = document.getElementById('member-info'); if (payload.isAuthenticated) { memberElement.textContent = `Welcome, ${payload.member?.email}!`; } else { memberElement.textContent = 'Please sign in'; } } transcodes.on('AUTH_STATE_CHANGED', updateUI); ``` -------------------------------- ### Securely Get Access Token (JavaScript) Source: https://www.transcodes.io/docs/introduction/architecture Demonstrates the recommended method for obtaining an access token using the Transcodes SDK. It emphasizes letting the SDK handle token storage automatically for enhanced security, avoiding manual storage in cookies or custom solutions. ```javascript // Recommended: Let the SDK handle storage automatically const token = await transcodes.token.getAccessToken(); ``` -------------------------------- ### Open Login Modal (npm) Source: https://www.transcodes.io/docs/quick-integration Opens the Transcodes.io authentication login modal using the npm package. This method uses named exports and does not require a project ID if configured via environment variables. It returns authentication results. ```javascript import { openAuthLoginModal } from '@bigstrider/transcodes-sdk'; const result = await openAuthLoginModal({ webhookNotification: false }); if (result.success) { const { token, member } = result.payload[0]; console.log('Logged in as:', member?.email); } ``` -------------------------------- ### Implement Step-up MFA for Sensitive Actions (JavaScript) Source: https://www.transcodes.io/docs/demonstration/stepup-mfa/prerequisites This JavaScript code snippet demonstrates how to implement step-up MFA for accessing sensitive resources like an admin panel. It first checks if the user is authenticated and then uses `transcodes.openAuthIdpModal` to trigger the MFA verification process for a specific resource and action. The user must be signed in before this function can be called. ```javascript async function accessAdminPanel() { // Step 1: Check if user is authenticated const isAuth = await transcodes.token.isAuthenticated(); if (!isAuth) { // Not logged in - redirect to login await transcodes.openAuthLoginModal(); return; } // Step 2: Require MFA for admin access const mfaResult = await transcodes.openAuthIdpModal({ resource: 'admin', action: 'read', }); if (mfaResult.success && mfaResult.payload[0]?.success) { // MFA verified - show admin panel showAdminPanel(); } } ``` -------------------------------- ### Integrate Transcodes Authentication via CDN or npm SDK Source: https://www.transcodes.io/docs This snippet demonstrates how to initialize and trigger the Transcodes authentication modal. It supports both direct CDN inclusion for simple setups and npm SDK installation for modular application architectures. ```html ``` ```javascript const result = await transcodes.openAuthIdpModal({ resource: 'users', action: 'delete', }); ``` ```typescript import * as Transcodes from '@bigstrider/transcodes-sdk'; await Transcodes.init({ projectId: 'proj_abc123xyz' }); const result = await Transcodes.openAuthIdpModal({ resource: 'users', action: 'delete', }); ``` -------------------------------- ### Load SDK via CDN Source: https://www.transcodes.io/docs/demonstration/stepup-mfa/import-cdn This snippet shows how to load the Transcodes.io Authentication Toolkit SDK using a script tag from a CDN. Ensure you replace '{YOUR_PROJECT_ID}' with your actual project ID. This method is suitable for quick integration. ```html ``` -------------------------------- ### Initialize and Handle Authentication with Transcodes SDK Source: https://www.transcodes.io/docs/demonstration/passkey-login Demonstrates how to trigger the authentication modal and listen for authentication state changes. This implementation requires the Transcodes SDK to be initialized via CDN or npm. ```javascript // After SDK load (CDN: transcodes — npm: import { openAuthLoginModal, on } from '…') const result = await transcodes.openAuthLoginModal({}); if (result.success) { const member = result.payload[0].member; console.log('Welcome!', member?.email); } transcodes.on('AUTH_STATE_CHANGED', (payload) => { if (payload.isAuthenticated) { console.log('Member signed in:', payload.member?.email); } }); ``` -------------------------------- ### Initialize Authentication and Event Handling in JavaScript Source: https://www.transcodes.io/docs/quick-integration/vanilla Demonstrates how to initialize the Transcodes SDK, handle authentication state changes via events, and manage login/sign-out flows using the DOM. ```javascript const PROJECT_ID = import.meta.env.VITE_TRANSCODES_PROJECT_ID; let isAuthenticated = false; let isLoading = true; let memberId = null; let member = null; const app = document.getElementById('app'); async function startApp() { isAuthenticated = await transcodes.token.isAuthenticated(); isLoading = false; render(); transcodes.on('AUTH_STATE_CHANGED', (payload) => { isAuthenticated = payload.isAuthenticated; if (!isAuthenticated) { memberId = null; member = null; } render(); }); transcodes.on('ERROR', (payload) => { console.error('Transcodes error:', payload.code, payload.message); }); } async function handleLogin() { try { const result = await transcodes.openAuthLoginModal({ projectId: PROJECT_ID }); if (result.success && result.payload.length > 0) { member = result.payload[0].member; } } catch (error) { console.error('Login error:', error); } } async function handleSignOut() { await transcodes.token.signOut(); } ``` -------------------------------- ### Initialize Transcodes SDK in JavaScript Source: https://www.transcodes.io/docs/quick-integration/vanilla Demonstrates how to bootstrap an application by initializing the Transcodes SDK with a project ID. It ensures that application logic is executed only after the SDK initialization promise resolves. ```javascript import { init, openAuthLoginModal, isAuthenticated, getCurrentMember, signOut, on, } from '@bigstrider/transcodes-sdk'; const PROJECT_ID = import.meta.env.VITE_TRANSCODES_PROJECT_ID; async function bootstrap() { await init({ projectId: PROJECT_ID }); await startApp(); } bootstrap(); ``` -------------------------------- ### Sign Out (npm) Source: https://www.transcodes.io/docs/quick-integration Signs the user out of Transcodes.io using the npm package. This is an asynchronous operation. ```javascript import { signOut } from '@bigstrider/transcodes-sdk'; await signOut({ webhookNotification: false }); ``` -------------------------------- ### Open Login Modal Basic Usage Source: https://www.transcodes.io/docs/demonstration/passkey-login/call-login-modal Initiates the passkey login modal and handles the response. It checks for success and logs the member's email if authentication is successful. Dependencies include the transcodes SDK. ```javascript const result = await transcodes.openAuthLoginModal({}); if (result.success) { const member = result.payload[0].member; console.log('Welcome!', member?.email); } ``` -------------------------------- ### Init & Config API Source: https://www.transcodes.io/docs/api-reference Enables dynamic SDK initialization and configuration with methods like `init()`, `setConfig()`, and `isInitialized()`. Differentiates between static and dynamic API usage. ```APIDOC ## Init & Config API ### Description Dynamic SDK: `init()`, `setConfig()`, `isInitialized()`. Static vs Dynamic API differences. ### Methods - `init(config)` - `setConfig(config)` - `isInitialized()` ``` -------------------------------- ### Sign Out (CDN) Source: https://www.transcodes.io/docs/quick-integration Signs the user out of Transcodes.io using the CDN method. This is an asynchronous operation. ```javascript await transcodes.token.signOut(); ``` -------------------------------- ### Perform Authenticated API Requests Source: https://www.transcodes.io/docs/quick-integration/vanilla Example of using a fetch utility to retrieve data from protected endpoints. ```javascript async function loadUserData() { try { const data = await fetchWithAuth('/user/profile'); console.log('User data:', data); } catch (error) { console.error('Failed to load user data:', error); } } ``` -------------------------------- ### Server-Side Verification of MFA Token Source: https://www.transcodes.io/docs/demonstration/stepup-mfa/handle-mfa-response Provides an example of how to verify the access token received from the client on the server-side to ensure the user has completed MFA. ```APIDOC ## Server-Side Verification On your server, you must verify the access token sent by the client. This token acts as proof that the user has successfully completed the MFA challenge. ### Endpoint `/api/admin/settings` (Example POST endpoint) ### Method `POST` ### Request Headers - **Authorization** (string) - Required - Bearer token obtained from `transcodes.token.getAccessToken()`. - **Content-Type** (string) - Required - `application/json` ### Request Body - **setting** (string) - Example field for the setting to update. ### Server-Side Logic Example (Node.js / Express) ```javascript // Node.js / Express app.post('/api/admin/settings', async (req, res) => { // Verify access token (user is logged in and completed MFA) const accessToken = req.headers.authorization?.split(' ')[1]; const user = await verifyAccessToken(accessToken); // Implement your JWT verification logic here if (!user) { return res.status(401).json({ error: 'Unauthorized' }); } // Proceed with sensitive action await updateSettings(req.body); res.json({ success: true }); }); // Placeholder for JWT verification function async function verifyAccessToken(token) { // Implement your JWT verification logic using the token // This typically involves decoding the token and checking its signature and expiry // Return user information if valid, otherwise null return { userId: 'user123' }; // Example user object } // Placeholder for updating settings async function updateSettings(settings) { console.log('Updating settings:', settings); // Implement your actual settings update logic } ``` ``` -------------------------------- ### Initialize and Open Authentication Modals Source: https://www.transcodes.io/docs/introduction/why-transcodes Demonstrates how to integrate Transcodes authentication using either a CDN script or the npm SDK. These methods allow developers to trigger login and account management modals without building custom backend auth routes. ```html ``` ```javascript import { init, openAuthLoginModal, openAuthConsoleModal } from '@bigstrider/transcodes-sdk'; await init({ projectId: 'YOUR_PROJECT_ID' }); await openAuthLoginModal({}); await openAuthConsoleModal(); ``` -------------------------------- ### Verify JWT Token Locally Source: https://www.transcodes.io/docs/demonstration/passkey-login/server-side Provides implementation examples for verifying JWT tokens using the public key retrieved from the Transcodes JWKS endpoint. ```javascript const jwt = require('jsonwebtoken'); const jwksClient = require('jwks-rsa'); const client = jwksClient({ jwksUri: 'https://cdn.transcodes.link/{YOUR_PROJECT_ID}/jwks.json', cache: true, cacheMaxAge: 86400000, }); function getKey(header, callback) { client.getSigningKey(header.kid, (err, key) => { const signingKey = key.getPublicKey(); callback(null, signingKey); }); } async function verifyToken(token) { return new Promise((resolve, reject) => { jwt.verify(token, getKey, { algorithms: ['RS256'], issuer: '' }, (err, decoded) => { if (err) reject(err); else resolve(decoded); }); }); } ``` ```python import jwt import requests from functools import lru_cache @lru_cache(maxsize=1) def get_public_keys(): response = requests.get('/v1/.well-known/jwks.json') return response.json() def verify_token(token: str) -> dict: jwks = get_public_keys() unverified_header = jwt.get_unverified_header(token) kid = unverified_header['kid'] public_key = None for key in jwks['keys']: if key['kid'] == kid: public_key = jwt.algorithms.RSAAlgorithm.from_jwk(key) break if not public_key: raise ValueError('Public key not found') return jwt.decode(token, public_key, algorithms=['RS256'], issuer='') ``` -------------------------------- ### Implement MFA Protection Patterns Source: https://www.transcodes.io/docs/demonstration/stepup-mfa/call-mfa-modal Common usage patterns for protecting sensitive application areas or specific user actions. Demonstrates conditional logic to ensure MFA verification before proceeding. ```javascript async function openAdminPanel() { const mfaResult = await transcodes.openAuthIdpModal({ resource: 'admin', action: 'read', }); if (!mfaResult.success || !mfaResult.payload[0]?.success) { alert('MFA verification required to access admin panel'); return; } window.location.href = '/admin'; } async function deleteAccount() { const mfaResult = await transcodes.openAuthIdpModal({ resource: 'users', action: 'delete', forceStepUp: true, }); if (mfaResult.success && mfaResult.payload[0]?.success) { await api.deleteAccount(); } } ``` -------------------------------- ### Member API - Get Member Source: https://www.transcodes.io/docs/api-reference/member Retrieves member information from the server. You can fetch members by project ID, member ID, or email. You can also specify which fields to return. ```APIDOC ## GET /members ### Description Retrieves member information from the server. Supports fetching by project ID, member ID, or email, and allows specifying returned fields. ### Method GET ### Endpoint /members ### Parameters #### Query Parameters - **projectId** (string) - Optional - Project ID. - **memberId** (string) - Optional - Member ID to fetch. - **email** (string) - Optional - Email address to search. - **fields** (string) - Optional - Comma-separated fields to return. ### Request Example ```json { "projectId": "proj_xxx", "memberId": "mbr_xxx", "email": "member@example.com", "fields": "id,email,name" } ``` ### Response #### Success Response (200) - **success** (boolean) - Indicates if the request was successful. - **payload** (array) - An array of Member objects. - **error** (string) - Error message if the request failed. - **message** (string) - Additional message about the response. - **status** (number) - HTTP status code. #### Response Example ```json { "success": true, "payload": [ { "id": "mbr_xxx", "projectId": "proj_xxx", "name": "John Doe", "email": "member@example.com", "role": "user", "metadata": {}, "createdAt": "2023-01-01T12:00:00Z", "updatedAt": "2023-01-01T12:00:00Z" } ], "status": 200 } ``` ``` -------------------------------- ### Token API Interface (TypeScript) Source: https://www.transcodes.io/docs/api-reference/types Defines the interface for interacting with the token-related functionalities, such as retrieving the current member, getting the access token, checking authentication status, and signing out. ```typescript interface TokenAPI { getCurrentMember(): Promise; getAccessToken(): Promise; hasToken(): boolean; isAuthenticated(): Promise; signOut(options?: { webhookNotification?: boolean }): Promise; } ``` -------------------------------- ### Initialize Dynamic Transcodes SDK Source: https://www.transcodes.io/docs/api-reference/init-config Initializes the Dynamic Transcodes SDK using the provided project ID. This function must be called before other Dynamic SDK methods. ```typescript await transcodes.init({ projectId: 'proj_abc123xyz', }); ``` -------------------------------- ### Configure Environment Variables Source: https://www.transcodes.io/docs/quick-integration/nextjs Define the required Transcodes project ID in your local environment configuration file. ```bash NEXT_PUBLIC_TRANSCODES_PROJECT_ID=proj_abc123xyz ``` -------------------------------- ### Import Transcodes SDK Functions Source: https://www.transcodes.io/docs/quick-integration/react This snippet demonstrates how to import named exports from the Transcodes SDK after it has been installed via npm and initialized. These functions can then be used in your React components. ```typescript import { openAuthLoginModal, isAuthenticated, getCurrentMember, signOut, on, } from '@bigstrider/transcodes-sdk'; ``` -------------------------------- ### Verify MFA Token Server-Side Source: https://www.transcodes.io/docs/demonstration/stepup-mfa/handle-mfa-response Example of an Express route handler that validates the access token to ensure the user has completed the required MFA before performing sensitive operations. ```javascript app.post('/api/admin/settings', async (req, res) => { const accessToken = req.headers.authorization?.split(' ')[1]; const user = await verifyAccessToken(accessToken); if (!user) { return res.status(401).json({ error: 'Unauthorized' }); } await updateSettings(req.body); res.json({ success: true }); }); ``` -------------------------------- ### Basic User Action Tracking - JavaScript Source: https://www.transcodes.io/docs/api-reference/audit Demonstrates the basic usage of trackUserAction to log a user login event with associated metadata. This is a fundamental example for initiating audit trails. ```javascript await transcodes.trackUserAction({ tag: 'user:login', metadata: { method: 'passkey' }, }); ``` -------------------------------- ### Check Authentication Status (npm) Source: https://www.transcodes.io/docs/quick-integration Checks if the user is currently authenticated using the Transcodes.io SDK via the npm package. This is an asynchronous operation and requires the `await` keyword. ```javascript import { isAuthenticated } from '@bigstrider/transcodes-sdk'; const isAuth = await isAuthenticated(); ``` -------------------------------- ### Check Authentication Status (CDN) Source: https://www.transcodes.io/docs/quick-integration Checks if the user is currently authenticated using the Transcodes.io SDK via the CDN method. This is an asynchronous operation and requires the `await` keyword. ```javascript const isAuth = await transcodes.token.isAuthenticated(); ``` -------------------------------- ### Check if Dynamic Transcodes SDK is Initialized Source: https://www.transcodes.io/docs/api-reference/init-config Checks whether the Dynamic Transcodes SDK has been successfully initialized. If not, it demonstrates how to initialize it. ```typescript if (transcodes.isInitialized()) { const member = await transcodes.token.getCurrentMember(); } else { await transcodes.init({ projectId: 'proj_xxx' }); } ```