Skip to main content
Docs · Delivery & integrations

Allure Training OS Integration Guide

Updated

Example guide for integrating the Allure Connect SCORM API with TrainingOS. Allure Training OS is a normal LMS/client consumer of the public Connect API; do not add private backend behavior for this integration.

Table of Contents

Overview

This guide covers using the same SCORM API contract any LMS/client uses to enable:

  • SCORM package upload and management
  • Session creation and tracking
  • Learner progress monitoring
  • Completion and score reporting

Connect-owned contract (do this; don’t substitute)

Allure Training OS should treat Connect as the runtime, not unzip the original Storyline package into the LMS.

  1. Embed the full launch_url from POST /api/v1/packages/{id}/launch (includes ?token=). Do not iframe package launcher.html or /player/{sessionId} without the token. Use dispatch when the LMS must import a ZIP — that ZIP is a Connect shell (index.html → /player/dispatch/{id}), not the publisher’s launcher.html.
  2. Read progress from GET /api/v1/sessions/{id} root fields: package_id, progress_percent (alias progress), completion_status, cmi_data. Nested session.package_id is not the partner contract (use session.packageId or root package_id).
  3. Poll GET for in-progress percent. Webhooks fire on terminal session events only (session.completed / session.failed / session.suspended). There is no session.progress event.
  4. Resume with the same session_id on launch (or iframe launch_url from POST /api/v1/sessions/{id}/refresh-token). Refresh-token does not write CMI.
  5. Capability / verified skills is an Enterprise Outcomes surface. Completing a video-only SCORM course is exposure, not a verified skill. Do not productize “skills obtained” on Starter/Growth from completions alone.
  6. YouTube and Vimeo embeds in Storyline/Captivate-hosted packages are supported. The hosted player CSP frame-src allowlists www.youtube.com, www.youtube-nocookie.com, and player.vimeo.com. Captivate YouTube embeds also load the IFrame API, so script-src allowlists www.youtube.com and s.ytimg.com. If a slide video is blank and the browser console shows a CSP frame-src or script-src violation for another host, that provider is not allowlisted — see Security overview and Common issues.

Prerequisites

  • Allure Training OS account with admin access
  • SCORM API account and API key
  • Node.js/TypeScript development environment
  • Understanding of REST APIs

Setup

1. Get API Credentials

  1. Sign in to Connect and select the workspace used by your integration.
  2. Open Build → API keys.
  3. Confirm the LIVE/TEST mode matches the intended integration.
  4. Select New API key and choose the required public_api scope.
  5. Copy the Account ID from the Connect credentials card as your CONNECT_TENANT_ID, and store the API key server-side.

2. Environment Variables

Add to your Allure Training OS .env file:

bash
CONNECT_API_BASE_URL=https://app.allureconnect.com
CONNECT_API_KEY=scorm_your-api-key-here
CONNECT_TENANT_ID=your-tenant-uuid

3. Install Dependencies

No special dependencies required - use native fetch or your preferred HTTP client.

Core Integration

TypeScript Client Class

Create a reusable client class:

typescript
// lib/scorm-api-client.ts
export class ScormAPIClient {
  private apiKey: string;
  private baseUrl: string;
  private tenantId: string;

  constructor() {
    this.apiKey = process.env.CONNECT_API_KEY!;
    this.baseUrl = process.env.CONNECT_API_BASE_URL!;
    this.tenantId = process.env.CONNECT_TENANT_ID!;
  }

  private async request(
    path: string,
    options: RequestInit = {}
  ): Promise<Response> {
    const url = `${this.baseUrl}${path}`;
    const headers = {
      Authorization: `Bearer ${this.apiKey}`,
      ...options.headers,
    };

    return this.fetchWithRetry(url, { ...options, headers });
  }

  private async fetchWithRetry(
    url: string,
    options: RequestInit,
    maxRetries = 3
  ): Promise<Response> {
    for (let attempt = 0; attempt < maxRetries; attempt++) {
      try {
        const response = await fetch(url, options);

        // Don't retry client errors (4xx)
        if (response.ok || (response.status >= 400 && response.status < 500)) {
          return response;
        }

        // Retry server errors (5xx) with exponential backoff
        if (attempt < maxRetries - 1) {
          const delay = Math.pow(2, attempt) * 1000; // 1s, 2s, 4s
          await new Promise(resolve => setTimeout(resolve, delay));
        }
      } catch (error) {
        if (attempt === maxRetries - 1) throw error;
        await new Promise(resolve => setTimeout(resolve, Math.pow(2, attempt) * 1000));
      }
    }
    throw new Error('Max retries exceeded');
  }

  /**
   * Presigned flow: mint → PUT bytes to R2 → process.
   * Prefer running this from a **backend** so API keys never ship to browsers.
   *
   * **Types:** In the browser, `file` is a `File` from `<input type="file">`. On **Node.js**,
   * there is no global `File`—use a `Buffer` / `ReadableStream` with `fetch` for the PUT (same
   * headers as `required_put_headers`), or a polyfill such as `undici`/`formdata-node` if you
   * need `File`-like ergonomics. Adapt `file.name` / `file.size` from your source accordingly.
   */
  async uploadPackage(file: File, uploadedBy: string) {
    const mint = await this.request('/api/v1/packages/upload-url', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        tenant_id: this.tenantId,
        uploaded_by: uploadedBy,
        filename: file.name,
        file_size: file.size,
      }),
    });
    if (!mint.ok) {
      throw new Error(`Mint upload URL failed: ${mint.statusText}`);
    }
    const ticket = (await mint.json()) as {
      presigned_url: string;
      required_put_headers: Record<string, string>;
      storage_path: string;
    };

    const put = await fetch(ticket.presigned_url, {
      method: 'PUT',
      headers: ticket.required_put_headers,
      body: file,
    });
    if (!put.ok) {
      throw new Error(`Upload to storage failed: ${put.status}`);
    }

    const proc = await this.request('/api/v1/packages/process', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        tenant_id: this.tenantId,
        uploaded_by: uploadedBy,
        storage_path: ticket.storage_path,
        original_filename: file.name,
      }),
    });
    if (!proc.ok) {
      throw new Error(`Process failed: ${proc.statusText}`);
    }
    return proc.json();
  }

  async listPackages(page = 1, limit = 20) {
    const url = `/api/v1/packages?tenant_id=${this.tenantId}&page=${page}&limit=${limit}`;
    const response = await this.request(url);
    return response.json();
  }

  async getPackage(packageId: string) {
    const response = await this.request(`/api/v1/packages/${packageId}`);
    return response.json();
  }

  async launchSession(packageId: string, userId: string, sessionId?: string) {
    const response = await this.request(`/api/v1/packages/${packageId}/launch`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        user_id: userId,
        session_id: sessionId || crypto.randomUUID(),
      }),
    });
    return response.json();
  }

  async getSession(sessionId: string) {
    const response = await this.request(`/api/v1/sessions/${sessionId}`);
    return response.json();
  }

  async updateSession(sessionId: string, updates: any, maxRetries = 3) {
    for (let attempt = 0; attempt < maxRetries; attempt++) {
      const session = await this.getSession(sessionId);

      const payload = {
        version: session.version,
        cmi_data: {
          ...session.cmi_data,
          ...updates.cmi_data,
        },
        ...updates,
      };

      const response = await this.request(`/api/v1/sessions/${sessionId}`, {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(payload),
      });

      if (response.ok) {
        return response.json();
      }

      if (response.status === 409 && attempt < maxRetries - 1) {
        console.log(`Version conflict, retrying... (${attempt + 1}/${maxRetries})`);
        continue;
      }

      throw new Error(`Update failed: ${response.status}`);
    }
    throw new Error('Max retries exceeded');
  }
}

export const scormAPI = new ScormAPIClient();

Upload Flow

typescript
// services/scorm-upload.ts
import { scormAPI } from '@/lib/scorm-api-client';

export async function uploadScormPackage(
  file: File,
  userId: string
): Promise<{ packageId: string; title: string }> {
  try {
    const pkg = await scormAPI.uploadPackage(file, userId);
    
    // Store package ID in TrainingOS database
    await savePackageToDatabase({
      scormPackageId: pkg.id,
      title: pkg.title,
      version: pkg.version,
      uploadedBy: userId,
    });

    return {
      packageId: pkg.id,
      title: pkg.title,
    };
  } catch (error) {
    console.error('SCORM upload failed:', error);
    throw new Error('Failed to upload SCORM package');
  }
}

Launch Flow

typescript
// services/scorm-launch.ts
import { scormAPI } from '@/lib/scorm-api-client';

export async function launchScormCourse(
  packageId: string,
  userId: string
): Promise<{ sessionId: string; playerUrl: string }> {
  try {
    // Check for existing incomplete session
    const existingSession = await findIncompleteSession(packageId, userId);
    
    if (existingSession) {
      // Prefer a fresh signed launch_url from the API (token-bound), not a guessed player path
      const resume = await scormAPI.launchSession(packageId, userId, existingSession.id);
      return {
        sessionId: resume.session_id,
        playerUrl: resume.launch_url,
      };
    }

    // Create new session
    const launch = await scormAPI.launchSession(packageId, userId);
    
    return {
      sessionId: launch.session_id,
      playerUrl: launch.launch_url,
    };
  } catch (error) {
    console.error('SCORM launch failed:', error);
    throw new Error('Failed to launch SCORM course');
  }
}

Progress Tracking

typescript
// services/scorm-tracking.ts
import { scormAPI } from '@/lib/scorm-api-client';

export async function trackScormProgress(sessionId: string) {
  const session = await scormAPI.getSession(sessionId);

  // Update TrainingOS database
  await updateCourseProgress({
    sessionId,
    packageId: session.package_id,
    progressPercent: session.progress_percent,
    completionStatus: session.completion_status,
    successStatus: session.success_status,
    score: session.score?.scaled,
    timeSpent: session.time_spent_seconds,
  });

  return {
    packageId: session.package_id,
    progressPercent: session.progress_percent,
    completed: session.completion_status === 'completed' || session.completion_status === 'passed',
    passed: session.success_status === 'passed',
    score: session.score?.scaled,
    timeSpent: session.time_spent_seconds,
  };
}

// Poll for completion
export function pollScormCompletion(
  sessionId: string,
  onComplete: (result: any) => void
) {
  const interval = setInterval(async () => {
    try {
      const progress = await trackScormProgress(sessionId);
      
      if (progress.completed) {
        clearInterval(interval);
        onComplete(progress);
      }
    } catch (error) {
      console.error('Progress tracking failed:', error);
      clearInterval(interval);
    }
  }, 5000); // Poll every 5 seconds

  return () => clearInterval(interval);
}

Advanced Features

Webhook Integration

Subscribe to package processing events:

typescript
// Setup webhook
await scormAPI.request('/api/v1/webhooks', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({
    tenant_id: process.env.CONNECT_TENANT_ID,
    url: 'https://trainingos.com/api/webhooks/scorm',
    secret: process.env.WEBHOOK_SECRET,
    eventScope: 'packages',
  }),
});

// Webhook handler in TrainingOS
export async function POST(request: Request) {
  // Prefer X-Connect-Signature ("sha256=<hex>"); fall back to legacy header
  const connectSig = request.headers.get('X-Connect-Signature');
  const signature = connectSig ? connectSig.replace(/^sha256=/, '') : request.headers.get('X-Allure-Signature');
  const body = await request.text();
  
  // Verify signature
  const expectedSignature = createHmac('sha256', process.env.WEBHOOK_SECRET!)
    .update(body)
    .digest('hex');
  
  if (signature !== expectedSignature) {
    return new Response('Invalid signature', { status: 401 });
  }

  const event = JSON.parse(body);
  
  if (event.event === 'package.version_activated') {
    await handlePackageProcessed(event.data);
  }

  return new Response('OK');
}

Version Management

Upload new revisions while keeping a stable package id: same as uploadPackage, but include package_id on the /api/v1/packages/process body.

typescript
// Add to ScormAPIClient (same mint + PUT as uploadPackage, different process body):
async updatePackageVersion(existingPackageId: string, file: File, uploadedBy: string) {
  const mint = await this.request('/api/v1/packages/upload-url', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({
      tenant_id: this.tenantId,
      uploaded_by: uploadedBy,
      filename: file.name,
      file_size: file.size,
    }),
  });
  if (!mint.ok) throw new Error(`Mint failed: ${mint.statusText}`);
  const ticket = (await mint.json()) as {
    presigned_url: string;
    required_put_headers: Record<string, string>;
    storage_path: string;
  };
  const put = await fetch(ticket.presigned_url, {
    method: 'PUT',
    headers: ticket.required_put_headers,
    body: file,
  });
  if (!put.ok) throw new Error('Storage PUT failed');
  const proc = await this.request('/api/v1/packages/process', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({
      tenant_id: this.tenantId,
      uploaded_by: uploadedBy,
      storage_path: ticket.storage_path,
      original_filename: file.name,
      package_id: existingPackageId,
    }),
  });
  if (!proc.ok) throw new Error(`Process failed: ${proc.statusText}`);
  return proc.json();
}

Error Handling

Version Conflicts

Always handle 409 conflicts when updating sessions:

typescript
async function updateSessionWithRetry(
  sessionId: string,
  updates: any
): Promise<any> {
  try {
    return await scormAPI.updateSession(sessionId, updates);
  } catch (error) {
    if (error.message.includes('409')) {
      // Retry with fresh data
      return updateSessionWithRetry(sessionId, updates);
    }
    throw error;
  }
}

Rate Limiting

Handle 429 rate limit errors:

typescript
private async handleRateLimit(response: Response): Promise<Response> {
  if (response.status === 429) {
    const retryAfter = parseInt(
      response.headers.get('Retry-After') || '60'
    );
    console.log(`Rate limited. Waiting ${retryAfter} seconds...`);
    
    await new Promise(resolve => setTimeout(resolve, retryAfter * 1000));
    
    // Retry the request
    return this.request(response.url);
  }
  return response;
}

Best Practices

  1. Cache Package Data: Store package metadata in Allure Training OS to reduce API calls
  2. Use Webhooks: Subscribe to events instead of polling when possible
  3. Handle Errors Gracefully: Implement retry logic for transient failures
  4. Monitor Quotas: Track package and storage usage
  5. Version Management: Use package versioning for updates
  6. Session Resumption: Check for existing incomplete sessions before creating new ones

Production Checklist

  • [ ] Environment variables configured
  • [ ] API client implemented with error handling
  • [ ] Version conflict handling (409 errors)
  • [ ] Retry logic for server errors (500/503)
  • [ ] Rate limit handling (429 errors)
  • [ ] Upload flow tested with real SCORM packages
  • [ ] Session creation and tracking tested
  • [ ] Concurrent user scenarios tested
  • [ ] Completion tracking implemented
  • [ ] Score reporting working
  • [ ] Webhook integration (optional but recommended)
  • [ ] Monitoring and alerting configured

Use the interactive OpenAPI reference to verify current request and response schemas.