Skip to content

Core Server Module

The packages/core/src/server directory houses a collection of server-side modules crucial for the application's backend operations. These modules handle tasks ranging from third-party API interactions and security to request handling and utility functions. Below is a breakdown of the modules, grouped by their primary area of responsibility.

Monday.com Integration

This group of modules facilitates communication with the Monday.com platform.

  • monday-api.ts: This file provides a foundational MondayApiClient class. It is a generic client designed to interact with the Monday.com GraphQL API (v2). The client handles the construction of HTTP POST requests, including authentication via an API token, and processes responses, throwing errors if the API returns issues or GraphQL errors.
  • monday.service.ts: Building upon the MondayApiClient, this service offers more specialised functionality for interacting with Monday.com. The MondayService class is tailored for specific operations, such as creating new contacts within a designated CRM board. It manages the retrieval of the Monday.com API key from environment variables and encapsulates the logic for formatting data according to the specific requirements of the CRM board's columns. It also includes a lazy-loading pattern for the service instance to ensure it's initialised only when needed and can handle potential initialisation failures gracefully during build time.

API Authentication and Security

These modules are central to securing the application's API endpoints.

  • api-auth.ts: This module is responsible for the validation of API keys. The validateApiKey function checks a provided API key against active keys stored in a Supabase database. It retrieves encrypted keys, decrypts them using the encryption.ts module, and if a match is found, updates a last_used_at timestamp for the key. It returns whether the key is valid, the associated user ID, and any error messages.
  • api-middleware.ts: This file provides SvelteKit middleware, requireApiKey, to protect API routes. The middleware first checks if a user is authenticated via a standard session. If no session exists, it attempts to extract an API key from the request headers (supporting x-api-key or the Authorization: Bearer scheme). It then uses validateApiKey from api-auth.ts to verify the key. Access is granted or denied based on the validation outcome.
  • encryption.ts: This module supplies essential encryption and decryption services using the AES-GCM algorithm. It includes encrypt and decrypt functions, along with helper utilities for converting data between hexadecimal strings and Uint8Array byte arrays (hexToBytes, bytesToHex), importing cryptographic keys (getKey), and generating cryptographically secure random strings (generateRandomString). A key feature is the lazy loading of the PRIVATE_ENCRYPTION_KEY from environment variables, ensuring it's accessed only when required and after environment bindings are available in serverless environments.

HTTP Utilities

This category contains general-purpose utilities for handling HTTP-related tasks.

  • response-utils.ts: This module exports a single utility function, cloneResponse. Its purpose is to create a new Response object that is a deep copy of an original Response (body stream, status, status text, and headers). This is particularly useful for ensuring compatibility across different JavaScript runtimes, such as between Cloudflare Miniflare (used during local development with Wrangler) and the Node.js runtime used by SvelteKit, which may have distinct global Response constructors.

Email Services

This module is dedicated to sending emails, both to administrators and application users, utilising the Resend email platform.

  • mailer.ts: This file provides functionalities for dispatching emails. It includes:
    • sendAdminEmail: A function to send notification emails to a pre-configured administrator email address. It gracefully handles scenarios where Resend API keys are not configured.
    • sendUserEmail: A function designed to send emails to application users. Before sending, it performs several crucial checks: verifies the user's email address is confirmed (checking both email_confirmed_at and user_metadata.email_verified via a Supabase admin client), and checks if the user has unsubscribed from emails by looking up their profile in the Supabase database.
    • sendTemplatedEmail: A core function that handles the actual sending of emails via Resend. It supports sending emails with directly provided plaintext or HTML bodies. Alternatively, it can use Handlebars (.hbs) templates for both HTML and plaintext versions of an email. It attempts to load these templates (e.g., template_name_text.hbs, template_name_html.hbs) from an emails/ subdirectory. The function ensures that email sending is skipped if API keys are missing or if no email content (from direct input or templates) can be generated. It relies on environment variables for API keys and sender addresses, fetched via runtimeEnv.ts.

Cross-Cutting Utilities

These modules offer general-purpose functionalities utilised across various server-side operations.

  • runtimeEnv.ts: This utility module provides a robust, runtime-agnostic method for accessing environment variables. The getEnv(name: string) function is designed to work consistently across different JavaScript execution environments:

    • Cloudflare Workers / Durable Objects: It checks for globalThis.__workerEnv, which is expected to be populated by the execution environment.
    • Node.js / SvelteKit: It falls back to process.env if __workerEnv is not found.
    • Vite (dev/build): It further falls back to import.meta.env for variables injected by Vite during development or build processes. A fallback mechanism also copies process.env to globalThis.__workerEnv in non-worker runtimes if __workerEnv isn't initially set, ensuring getEnv() works during SvelteKit build/prerender phases.
  • load_helpers.ts: This module contains the load_helper asynchronous function, designed to consistently retrieve user session and user data in SvelteKit load functions, whether on the server or in the browser.

    • On the server, it uses the server_session passed in (typically populated by hooks like authGuard).
    • In the browser (isBrowser() === true), it explicitly calls supabase.auth.getSession() to fetch the current session.
    • It then attempts to retrieve the full user object using supabase.auth.getUser().
    • It includes a workaround for a Supabase auth client warning (suppressGetSessionWarning) related to getSession calls.
    • It returns an object containing the session and user, or null for both if a session/user cannot be established.

Module Exports

  • index.ts: This file acts as the primary CJS-compatible export point for all modules within the packages/core/src/server directory. It re-exports all the functionalities from the aforementioned files, providing a consolidated and convenient way for other parts of the application to import these server-side utilities.