Session class for managing authenticated contexts

This class represents an authenticated session in the Mosaia platform. It manages the current context including user identity, organization membership, client information, and permissions.

Features:

  • Identity management
  • Context switching
  • Permission tracking
  • Relationship access
  • Client authentication

Sessions provide access to:

  • Current user profile
  • Active organization
  • Organization membership
  • OAuth client context
  • Permission scopes

The session maintains the active context for:

  • API requests
  • Resource access
  • Permission checks
  • Identity verification

Basic session usage:

import { Session } from 'mosaia-node-sdk';

// Create authenticated session
const session = new Session({
user: {
id: 'user-123',
name: 'John Developer',
email: 'john@example.com'
},
org: {
id: 'org-456',
name: 'Tech Corp'
}
});

// Access session context
const user = session.user;
const org = session.org;

console.log(`${user.name} @ ${org.name}`);

Permission checking:

// Check access and permissions
const perms = session.permissions;
if (perms?.canManageUsers) {
// Add team member
const orgUser = session.orgUser;
await orgUser.orgs.create({
user: 'new-user',
permission: 'member'
});
}

// Switch organization context
session.org = newOrg;
session.orgUser = newOrgUser;

// Verify client
const client = session.client;
if (client?.isActive()) {
console.log('Client authenticated');
console.log('Scopes:', client.scopes);
}

Hierarchy (View Summary)

Constructors

  • Creates a new authenticated session

    Initializes a session with the provided authentication context. The session manages the current user's identity, organization membership, and access permissions.

    Parameters

    • data: Partial<SessionInterface>

      Session data including: - user: Current user details - org: Active organization - org_user: Organization membership - client: OAuth client context - permissions: Access permissions

    Returns Session

    Basic user session:

    const session = new Session({
    user: {
    id: 'user-123',
    name: 'Jane Developer',
    email: 'jane@example.com'
    }
    });

    Full organization context:

    const session = new Session({
    user: {
    id: 'user-123',
    name: 'Jane Developer'
    },
    org: {
    id: 'org-456',
    name: 'Tech Corp'
    },
    org_user: {
    permission: 'admin'
    },
    client: {
    id: 'client-789',
    name: 'Web Dashboard'
    },
    permissions: {
    canManageUsers: true,
    canManageApps: true
    }
    });

Accessors

  • get user(): null | User

    Get the current authenticated user

    This getter provides access to the current user's profile and identity information. It returns a User instance that can be used to access and manage user-specific data.

    Returns null | User

    User instance for the authenticated user, or null if not available

    When user data is malformed

    Basic user access:

    const user = session.user;
    if (user) {
    console.log(`Authenticated as: ${user.name}`);
    console.log(`Email: ${user.email}`);
    console.log(`Status: ${user.isActive() ? 'Active' : 'Inactive'}`);
    } else {
    console.log('Not authenticated');
    }

    Profile management:

    async function updateUserProfile(session: Session) {
    const user = session.user;
    if (!user) {
    throw new Error('Not authenticated');
    }

    // Update profile
    user.update({
    name: 'Updated Name',
    metadata: {
    title: 'Senior Developer',
    department: 'Engineering'
    }
    });

    await user.save();
    console.log('Profile updated successfully');
    }
  • set user(user: UserInterface): void

    Set the current authenticated user

    This setter updates the current user context in the session. It's typically used when switching users or updating user information after authentication changes.

    Parameters

    • user: UserInterface

      Complete user data including: - id: User's unique identifier - name: User's full name - email: User's email address - metadata: Additional user data

    Returns void

    Basic user switch:

    session.user = {
    id: 'user-123',
    name: 'New User',
    email: 'new@example.com'
    };

    Detailed user context:

    session.user = {
    id: 'user-456',
    name: 'Jane Smith',
    email: 'jane@example.com',
    metadata: {
    title: 'Engineering Manager',
    department: 'R&D',
    location: 'San Francisco',
    timezone: 'America/Los_Angeles'
    }
    };

    // Verify switch
    const user = session.user;
    console.log(`Switched to: ${user.name}`);
  • get org(): null | Organization

    Get the current active organization

    This getter provides access to the current organization context in the session. It returns an Organization instance that can be used to access and manage organization-specific resources.

    Returns null | Organization

    Organization instance for active organization, or null if not available

    When organization data is malformed

    Basic organization access:

    const org = session.org;
    if (org) {
    console.log(`Organization: ${org.name}`);
    console.log(`Description: ${org.short_description}`);
    console.log(`Status: ${org.isActive() ? 'Active' : 'Inactive'}`);
    } else {
    console.log('No organization context');
    }

    Resource management:

    async function manageOrgResources(session: Session) {
    const org = session.org;
    if (!org) {
    throw new Error('No organization context');
    }

    // Access organization resources
    const [agents, apps, models] = await Promise.all([
    org.agents.get(),
    org.apps.get(),
    org.models.get()
    ]);

    console.log('Organization Resources:');
    console.log(`- ${agents.length} AI agents`);
    console.log(`- ${apps.length} applications`);
    console.log(`- ${models.length} models`);
    }
  • set org(org: OrganizationInterface): void

    Set the current active organization

    This setter updates the current organization context in the session. It's typically used when switching between organizations or updating organization information.

    Parameters

    • org: OrganizationInterface

      Complete organization data including: - id: Organization's unique identifier - name: Organization name - short_description: Brief description - metadata: Additional organization data

    Returns void

    Basic organization switch:

    session.org = {
    id: 'org-123',
    name: 'New Organization',
    short_description: 'Updated context'
    };

    Detailed organization context:

    session.org = {
    id: 'org-456',
    name: 'Enterprise Corp',
    short_description: 'Global enterprise solutions',
    long_description: 'Leading provider of enterprise AI solutions',
    metadata: {
    industry: 'technology',
    size: 'enterprise',
    region: 'global',
    features: ['agents', 'apps', 'models']
    }
    };

    // Update related context
    session.orgUser = {
    permission: 'admin',
    metadata: {
    role: 'organization-admin'
    }
    };
  • get orgUser(): null | OrgUser

    Get the current organization membership

    This getter provides access to the current user's membership and role within the active organization. It returns an OrgUser instance that manages the relationship between user and organization.

    Returns null | OrgUser

    OrgUser instance for current membership, or null if not available

    When relationship data is malformed

    Basic membership check:

    const membership = session.orgUser;
    if (membership) {
    console.log(`Role: ${membership.permission}`);
    console.log(`Active: ${membership.isActive()}`);
    } else {
    console.log('No organization membership');
    }

    Permission management:

    async function checkAccess(session: Session) {
    const membership = session.orgUser;
    if (!membership) {
    throw new Error('No organization access');
    }

    // Check permissions
    const perms = session.permissions;
    if (perms?.canManageUsers) {
    // Manage team
    const team = await membership.orgs.get();
    console.log('Team Members:');
    team.forEach(member => {
    console.log(`- ${member.user.name} (${member.permission})`);
    });
    } else {
    console.log('Insufficient permissions');
    }
    }
  • set orgUser(orgUser: OrgUserInterface): void

    Set the current organization membership

    This setter updates the current user's membership and role within the active organization. It's typically used when switching roles or updating membership details.

    Parameters

    • orgUser: OrgUserInterface

      Complete membership data including: - org: Organization reference - user: User reference - permission: Access level - metadata: Additional membership data

    Returns void

    Basic role update:

    session.orgUser = {
    org: 'org-123',
    user: 'user-456',
    permission: 'admin'
    };

    Detailed membership update:

    session.orgUser = {
    org: 'org-123',
    user: 'user-456',
    permission: 'member',
    metadata: {
    department: 'engineering',
    title: 'Senior Developer',
    start_date: new Date().toISOString(),
    access_level: 'full',
    teams: ['frontend', 'platform']
    }
    };

    // Verify membership
    const membership = session.orgUser;
    if (membership?.isActive()) {
    console.log('Membership updated successfully');
    }
  • get client(): null | Client

    Get the current OAuth client

    This getter provides access to the current OAuth client context in the session. It returns a Client instance that manages authentication and authorization for external applications.

    Returns null | Client

    Client instance for current OAuth client, or null if not available

    When client data is malformed

    Basic client access:

    const client = session.client;
    if (client) {
    console.log(`Client: ${client.name}`);
    console.log(`ID: ${client.client_id}`);
    console.log(`Status: ${client.isActive() ? 'Active' : 'Inactive'}`);
    } else {
    console.log('No client context');
    }

    Client verification:

    async function verifyClient(session: Session) {
    const client = session.client;
    if (!client) {
    throw new Error('No client context');
    }

    // Check client configuration
    console.log('Client Configuration:');
    console.log(`Name: ${client.name}`);
    console.log(`ID: ${client.client_id}`);
    console.log(`Redirect URIs: ${client.redirect_uris.join(', ')}`);
    console.log(`Scopes: ${client.scopes.join(', ')}`);

    if (client.metadata?.type === 'service-account') {
    console.log('Service Account Details:');
    console.log(`Service: ${client.metadata.service}`);
    console.log(`Environment: ${client.metadata.environment}`);
    }
    }
  • set client(client: ClientInterface): void

    Set the current OAuth client

    This setter updates the current OAuth client context in the session. It's typically used when switching clients or updating client configuration for authentication.

    Parameters

    • client: ClientInterface

      Complete client data including: - id: Client's unique identifier - name: Client application name - client_id: OAuth client ID - client_secret: OAuth client secret - redirect_uris: Authorized redirect URIs - scopes: Authorized scopes - metadata: Additional client data

    Returns void

    Basic client update:

    session.client = {
    id: 'client-123',
    name: 'Web Dashboard',
    client_id: 'client-id',
    redirect_uris: ['https://app.example.com/callback']
    };

    Service account setup:

    session.client = {
    id: 'client-456',
    name: 'Background Service',
    client_id: process.env.SERVICE_CLIENT_ID,
    client_secret: process.env.SERVICE_CLIENT_SECRET,
    grant_types: ['client_credentials'],
    scopes: ['service:full'],
    metadata: {
    type: 'service-account',
    service: 'data-processor',
    environment: 'production',
    rate_limit: 1000
    }
    };

    // Verify client
    const client = session.client;
    if (client?.isActive()) {
    console.log('Client configured successfully');
    }
  • get permissions(): null | SessionPermissionsInterface

    Get the current session permissions

    This getter provides access to the current session's permission set. It returns a permissions object that defines what actions the current user can perform within the active organization context.

    Returns null | SessionPermissionsInterface

    Permission object defining allowed actions, or null if not available

    When permission data is malformed

    Basic permission check:

    const perms = session.permissions;
    if (perms) {
    console.log('User Permissions:');
    console.log(`- Manage Users: ${perms.canManageUsers}`);
    console.log(`- Manage Apps: ${perms.canManageApps}`);
    console.log(`- Manage Models: ${perms.canManageModels}`);
    } else {
    console.log('No permission data available');
    }

    Permission-based operations:

    async function performAdminTask(session: Session) {
    const perms = session.permissions;
    if (!perms) {
    throw new Error('No permission data');
    }

    // Check admin capabilities
    const canManageTeam = perms.canManageUsers;
    const canConfigureApps = perms.canManageApps;
    const canDeployModels = perms.canManageModels;

    if (canManageTeam && canConfigureApps && canDeployModels) {
    console.log('Full administrative access');

    // Perform admin tasks
    const org = session.org;
    if (org) {
    const [users, apps, models] = await Promise.all([
    org.orgs.get(),
    org.apps.get(),
    org.models.get()
    ]);

    console.log('Resource Summary:');
    console.log(`- ${users.length} team members`);
    console.log(`- ${apps.length} applications`);
    console.log(`- ${models.length} AI models`);
    }
    } else {
    console.log('Limited permissions:');
    console.log(`- Team management: ${canManageTeam}`);
    console.log(`- App configuration: ${canConfigureApps}`);
    console.log(`- Model deployment: ${canDeployModels}`);
    }
    }

Methods

  • Check if the entity is active

    This method checks the active status of the entity. Most entities in the system can be active or inactive, which affects their availability and usability in the platform.

    Returns boolean

    True if the entity is active, false otherwise

    const user = new User(userData);
    if (user.isActive()) {
    // Perform operations with active user
    } else {
    console.log('User is inactive');
    }
  • Convert model instance to interface data

    This method serializes the model instance to a plain object that matches the interface type. This is useful for:

    • Sending data to the API
    • Storing data in a database
    • Passing data between components
    • Debugging model state

    Returns SessionInterface

    The model data as a plain object matching the interface type

    const user = new User({
    email: 'user@example.com',
    firstName: 'John'
    });

    const data = user.toJSON();
    console.log(data); // { email: '...', firstName: '...' }

    // Use with JSON.stringify
    const json = JSON.stringify(user);
  • Convert model instance to API payload

    This method creates a payload suitable for API requests by:

    • Converting the model to a plain object
    • Removing read-only fields (like 'id')
    • Ensuring proper data format for the API

    Returns Partial<SessionInterface>

    A clean object suitable for API requests

    const user = new User({
    id: '123', // Will be removed from payload
    email: 'new@example.com',
    firstName: 'John'
    });

    const payload = user.toAPIPayload();
    // payload = { email: '...', firstName: '...' }
    // Note: 'id' is removed as it's read-only

    await apiClient.POST('/users', payload);
  • Update model data with new values

    This method updates the model's data and instance properties with new values. It performs a shallow merge of the updates with existing data, allowing for partial updates of the model's properties.

    Parameters

    Returns void

    const user = new User({
    email: 'old@example.com',
    firstName: 'John'
    });

    // Update multiple properties
    user.update({
    email: 'new@example.com',
    lastName: 'Doe'
    });

    // Save changes to API
    await user.save();

    This method only updates the local model instance. To persist changes to the API, call save after updating.

  • Save the model instance to the API

    This method persists the current state of the model to the API using a PUT request. It requires the model to have an ID (existing instance). For new instances, use the collection's create method instead.

    The method:

    1. Validates the model has an ID
    2. Sends current data to the API
    3. Updates local instance with API response

    Returns Promise<SessionInterface>

    Promise resolving to the updated model data

    When model has no ID

    When API request fails

    const user = new User({
    id: '123',
    email: 'user@example.com'
    });

    // Update and save
    user.update({ firstName: 'John' });
    await user.save();

    Error handling:

    try {
    await user.save();
    } catch (error) {
    if (error.message.includes('ID is required')) {
    // Handle missing ID error
    } else {
    // Handle API errors
    }
    }
  • Delete the model instance from the API

    This method permanently deletes the model instance from the API and clears the local data. This operation cannot be undone.

    The method:

    1. Validates the model has an ID
    2. Sends DELETE request to the API
    3. Clears local instance data on success

    Returns Promise<void>

    Promise that resolves when deletion is successful

    When model has no ID

    When API request fails

    Basic deletion:

    const user = await users.get({}, 'user-id');
    if (user) {
    await user.delete();
    // User is now deleted and instance is cleared
    }

    Error handling:

    try {
    await user.delete();
    console.log('User deleted successfully');
    } catch (error) {
    if (error.message.includes('ID is required')) {
    console.error('Cannot delete - no ID');
    } else {
    console.error('Deletion failed:', error.message);
    }
    }