🔒 Enterprise-Grade Security | ✅ Zero Vulnerabilities | 🚀 Production-Ready
The official TypeScript SDK for Marvin CMS. A modern, workspace-first SDK for building applications that integrate with Marvin.
The Marvin SDK has undergone a comprehensive security audit and achieved zero security vulnerabilities. All 20 identified issues have been fixed, including:
- ✅ 8 HIGH priority vulnerabilities eliminated
- ✅ 7 MEDIUM priority security issues resolved
- ✅ 5 LOW priority code quality improvements implemented
View Complete Security Audit →
- 🔐 Token Sanitization - Automatic redaction of sensitive data in logs/errors
- 🛡️ Input Validation - Path injection, XSS, and SSRF prevention
- 📧 Email Validation - RFC 5322 compliant validation
- 📁 File Upload Security - Size, type, and filename validation
- 🔄 Network Resilience - Automatic retry with exponential backoff
- 🔒 CSRF Protection - Session authentication security
- ✅ Type Safety - 100% TypeScript with zero
anytypes
View Security Best Practices →
Marvin is becoming a platform, not simply a CMS. This SDK is the primary way to integrate with Marvin across:
- Static Site Generators (Astro, Next.js, Nuxt)
- Server Applications (Express, Fastify, Hono)
- CLI Tools & Build Scripts
- Automation (n8n, GitHub Actions)
- AI Agents & Custom Integrations
The SDK provides:
- 🎯 Workspace-First Architecture - Work with Marvin concepts (Workspace, Entry, Collection)
- 🚀 Performance Optimized - Built-in caching for build-time usage
- 📘 Fully Typed - Complete TypeScript support
- 🔄 Backwards Compatible - Works with existing publishing APIs
- 🎨 Object-Oriented - Rich objects instead of raw JSON
- 🔒 Enterprise Security - Production-ready with comprehensive security features
npm install @inneropen/marvin-sdk@^2.0.1Latest stable version: v2.0.1 with complete security fixes and enterprise-grade quality.
The SDK provides three distinct entry points for different use cases:
Read-only access to published content (frontends, websites)
import { createMarvinClient } from '@inneropen/marvin-sdk/publish';Auth: Site client tokens (MARVIN_SITE_CLIENT_TOKEN)
Full CRUD admin operations (backend, CLI, automation)
import { createPlatformClient } from '@inneropen/marvin-sdk/platform';Auth: User tokens (MARVIN_USER_TOKEN) or session cookies
Public registration, login, password reset
import { createAuthClient } from '@inneropen/marvin-sdk';Auth: None required (public endpoints)
📚 See complete authentication guide →
MARVIN_API_URL=https://marvin.example.com
MARVIN_SITE_CLIENT_TOKEN=your-site-client-token
MARVIN_WORKSPACE_SLUG=your-workspaceimport { createMarvinClient } from '@inneropen/marvin-sdk/publish';
const marvin = createMarvinClient();// Get workspace
const workspace = await marvin.getWorkspace();
console.log(workspace.site?.title);
// Get entries
const entries = await marvin.entries.list();
// Get a specific entry
const entry = await marvin.entry('about-us');
console.log(entry.title, entry.contentMarkdown);
// Get collection entries
const projects = await marvin.collection('projects');
const projectEntries = await projects.entries();import { createPlatformClient } from '@inneropen/marvin-sdk/platform';
// From environment (MARVIN_USER_TOKEN)
const platform = createPlatformClient();
// Or explicit token
const platform = createPlatformClient({
userToken: 'your-user-token'
});
// Full CRUD operations
await platform.entries.create({
title: 'New Post',
content: 'Content here...',
collection_id: collectionId
});
await platform.entries.update(entryId, {
title: 'Updated Title'
});
await platform.entries.delete(entryId);Everything starts with the Workspace:
const workspace = await marvin.getWorkspace();
// Access workspace modules
workspace.entries // Entries module
workspace.collections // Collections module
workspace.assets // Assets module
workspace.renderers // Renderers module (entry type rendering metadata)
workspace.site // Site configuration (cached)The SDK is organized into focused modules:
@marvin/sdk
├── client/ → Core client & HTTP
├── workspaces/ → Workspace object
├── entries/ → Entries module
├── collections/ → Collections module
├── assets/ → Assets module
├── renderers/ → Renderers module (entry type rendering metadata)
├── auth/ → Authentication (future)
├── types/ → TypeScript types
└── utils/ → Cache & utilities
The SDK supports three API styles:
const workspace = await marvin.getWorkspace();
const entries = await workspace.entries.list();
const collection = await workspace.collections.get('featured');const entry = await marvin.entry('about');
const projects = await marvin.projects();
const pages = await marvin.pages();// Still works! (Deprecated but supported)
const site = await marvin.getSite();
const entries = await marvin.getEntries();
const entry = await marvin.getEntry('about');The workspace is the root object representing your Marvin workspace.
const workspace = await marvin.getWorkspace();
// Cached site configuration
workspace.site?.title
workspace.site?.description
// Access modules
workspace.entries.list()
workspace.collections.get('slug')
workspace.assets.images()
workspace.resources.list()Marvin has four first-class content primitives:
- Entries - Content you create (pages, blog posts, projects)
- Collections - Organize and group entries
- Assets - Binary files and media (images, videos, documents)
- Resources - Reusable structured objects (fabrics, tools, suppliers, APIs)
Rich entry objects with methods and properties:
const entry = await marvin.entry('about-us');
// Properties
entry.title
entry.slug
entry.contentMarkdown
entry.metadata
entry.publishedAt
// Relationships
entry.assets // MarvinAsset[]
entry.collections // MarvinCollection[]
entry.resources // MarvinResource[]
// Methods (future)
await entry.relatedEntries()Collections as first-class objects:
const collection = await marvin.collection('projects');
// Properties
collection.name
collection.slug
collection.isSmart
collection.smartRules
// Methods
const entries = await collection.entries();
// Future
await collection.assets()
await collection.metadata()Resources are reusable structured objects referenced by entries:
const resource = await marvin.resource('kuroki-s022');
// Properties
resource.name
resource.slug
resource.resourceType // 'fabric', 'tool', 'supplier', etc.
resource.description
resource.externalId
resource.url
resource.metadata
// Methods
const entries = await resource.entries(); // Entries that reference this resource
// Future
await resource.assets()Examples of Resources:
- Fabrics (denim, canvas, etc.)
- Tools (sewing machine, cutting tool)
- Suppliers (fabric mills, button manufacturers)
- Git repositories
- APIs and services
- Books and documents
Note: Resources are not binary files. Use Assets for media files.
// src/pages/[slug].astro
---
import { marked } from 'marked';
import { createMarvinClient } from '@/lib/marvin';
const marvin = createMarvinClient();
export async function getStaticPaths() {
const pages = await marvin.pages();
return pages.map((page) => ({
params: { slug: page.slug },
props: { page },
}));
}
const { page } = Astro.props;
const contentHtml = marked.parse(page.contentMarkdown ?? '');
---
<article>
<h1>{page.title}</h1>
<div set:html={contentHtml} />
</article>// app/blog/page.tsx
import { createMarvinClient } from '@/lib/marvin';
const marvin = createMarvinClient();
export default async function BlogPage() {
const posts = await marvin.posts();
return (
<div>
{posts.map((post) => (
<article key={post.id}>
<h2>{post.title}</h2>
<p>{post.summary}</p>
</article>
))}
</div>
);
}import express from 'express';
import { createMarvinClient } from './marvin-sdk';
const app = express();
const marvin = createMarvinClient();
app.get('/api/posts', async (req, res) => {
const posts = await marvin.posts();
res.json(posts);
});
app.get('/api/posts/:slug', async (req, res) => {
const entry = await marvin.entry(req.params.slug);
res.json(entry.toJSON());
});#!/usr/bin/env node
import { createMarvinClient } from '@marvin/sdk';
const marvin = createMarvinClient();
async function main() {
await marvin.initialize();
console.log('Site:', marvin.site?.title);
const entries = await marvin.entries.list();
console.log(`Found ${entries.length} entries`);
for (const entry of entries) {
console.log(`- ${entry.title} (${entry.status})`);
}
}
main().catch(console.error);const marvin = createMarvinClient({
autoInitialize: true,
});
// Site is preloaded
console.log(marvin.site?.title);const marvin = createMarvinClient();
await marvin.initialize();
// Now site is cached
console.log(marvin.site?.title);const marvin = createMarvinClient({
cacheDuration: 10 * 60 * 1000, // 10 minutes
});Quick access to common content types:
// Pages
const pages = await marvin.pages();
const about = await marvin.entry('about');
// Blog posts
const posts = await marvin.posts({ limit: 10 });
// Projects
const projects = await marvin.projects();
// Collections
const featured = await marvin.collection('featured');
const entries = await featured.entries();
// Assets
const images = await marvin.assets.images();
const videos = await marvin.assets.videos();
// Resources
const resources = await marvin.resources.list();
const fabric = await marvin.resource('kuroki-s022');
const entries = await fabric.entries();Create a new Marvin client instance.
Config Options:
apiUrl?: string- API URL (default:process.env.MARVIN_API_URL)siteClientToken?: string- Site client token (default:process.env.MARVIN_SITE_CLIENT_TOKEN)workspaceSlug?: string- Workspace slug (default:process.env.MARVIN_WORKSPACE_SLUG)autoInitialize?: boolean- Auto-initialize on creation (default:false)cacheDuration?: number- Cache duration in ms (default:300000/ 5 min)
Initialize the SDK and preload workspace data.
Get the workspace object.
Get basic workspace information (name and slug only).
Returns:
{
slug: string;
name: string;
}Get a single entry by slug (returns Entry object).
Get a single collection by slug (returns Collection object).
Get all pages.
Get all blog posts.
Get all projects.
The workspace slug (string).
Site configuration (cached after initialize()).
Get workspace info (name and slug).
Load/reload site configuration from the API.
Entries module.
Collections module.
Assets module.
Get all entries with optional filtering.
Options:
entryType?: string- Filter by entry type slugcollection?: string- Filter by collection slugstatus?: string- Filter by status (default:'published')limit?: number- Max resultsoffset?: number- Pagination offset
Get a single entry (returns Entry object).
Get all pages.
Get all blog posts.
Get all projects.
Properties:
id,title,slug,summary,descriptioncontentMarkdown- Raw Markdown contentmetadata- Custom metadata objectstatus,publishedAt,createdAt,updatedAtentryTypeId,entryTypeassets- Array of related assetscollections- Array of related collections
Methods:
entry.toJSON()- Get raw entry data
Get all collections.
Get a single collection (returns Collection object).
Get entries in a collection.
Properties:
id,name,slug,descriptionicon,color,sortOrderisSmart,smartRulescreatedAt,updatedAt
Methods:
collection.entries()- Get entries in collectioncollection.toJSON()- Get raw collection data
Get all assets.
Options:
type?: string- Filter by typelimit?: number- Max resultsoffset?: number- Pagination offset
Get all images.
Get all videos.
Get all documents.
Get all resources.
Options:
resourceType?: string- Filter by resource typelimit?: number- Max resultsoffset?: number- Pagination offset
Get a single resource (returns Resource object).
Get entries that reference a resource.
Properties:
id,name,slugresourceType- Type of resource (fabric, tool, supplier, etc.)description,externalId,urlmetadata- Custom metadata objectcreatedAt,updatedAt
Methods:
resource.entries()- Get entries that reference this resourceresource.toJSON()- Get raw resource data
Get all entry types with their rendering and capability metadata.
Returns: PublishedEntryType[]
interface PublishedEntryType {
slug: string;
name: string;
isRendered: boolean;
rendering?: {
renderer?: string;
package?: string;
version?: string;
config?: Record<string, unknown>;
};
capabilities?: {
publishable?: boolean;
submittable?: boolean;
routable?: boolean;
};
}Example:
const workspace = await marvin.getWorkspace();
const renderers = await workspace.renderers.list();
const rendered = renderers.filter(r => r.isRendered);
console.log(`${rendered.length} entry types have renderers`);The SDK uses these Marvin publishing API endpoints:
| Endpoint | Method | Purpose | Status |
|---|---|---|---|
/api/publish/{workspace} |
GET | Workspace info (name, slug) | ✅ Implemented |
/api/publish/{workspace}/site |
GET | Site configuration | ✅ Implemented |
/api/publish/{workspace}/entries |
GET | List entries | ✅ Implemented |
/api/publish/{workspace}/entries/{slug} |
GET | Get entry | ✅ Implemented |
/api/publish/{workspace}/collections |
GET | List collections | ✅ Implemented |
/api/publish/{workspace}/collections/{slug} |
GET | Get collection | ✅ Implemented |
/api/publish/{workspace}/collections/{slug}/entries |
GET | Collection entries | ✅ Implemented |
/api/publish/{workspace}/assets |
GET | List assets | ✅ Implemented |
/api/publish/{workspace}/assets/{slug} |
GET | Get asset metadata | ✅ Implemented |
/api/publish/{workspace}/resources |
GET | List resources | ✅ Implemented |
/api/publish/{workspace}/resources/{slug} |
GET | Get resource | ✅ Implemented |
/api/publish/{workspace}/resources/{slug}/entries |
GET | Resource entries | ✅ Implemented |
/api/publish/{workspace}/entry-types |
GET | List entry types (renderers) | ✅ Implemented |
Query Parameters:
- Entries:
entry_type,collection,slug,updated_since,page,limit - Assets:
type(MIME type prefix),limit,offset - Resources:
resource_type,limit,offset
The SDK includes comprehensive security protections:
- Path Injection Prevention - Validates all path parameters to prevent
../attacks - Email Validation - RFC 5322 compliant email format checking
- Webhook URL Validation - SSRF prevention for webhook endpoints
- File Upload Validation - Size limits (10MB), type checking, and filename sanitization
- Form Submission Validation - XSS prevention with script tag detection
- Token Sanitization - Automatic redaction of sensitive data in debug logs and errors
- Tokens, passwords, secrets, API keys automatically masked
- Recursive sanitization for nested objects and arrays
- Email Password Security - Passwords never returned in API responses
- CSRF Protection - Session authentication with CSRF token support
- Retry Logic - Automatic exponential backoff for transient failures (3 retries, configurable)
- Timeout Limits - Maximum 2-minute timeout to prevent resource exhaustion
- Error Handling - Comprehensive error types with actionable messages
Complete Security Documentation →
Always use site client tokens, never user tokens.
Get a site client token:
- Log into Marvin
- Go to Settings → Publishing → Site Clients
- Create a new client
- Copy the token
Never expose tokens in browser code:
// ✅ Good - Server/build time
const marvin = createMarvinClient();
// ❌ Bad - Browser code with exposed token
<script>
const marvin = createMarvinClient({
siteClientToken: '{TOKEN}' // DON'T DO THIS!
});
</script>- Environment Variables - Never commit tokens to version control
- Token Rotation - Regenerate user tokens periodically
- Debug Mode - Tokens are automatically sanitized in logs, but still use caution
- Input Validation - The SDK validates all inputs, but validate on your side too
- HTTPS Only - Always use HTTPS in production (enforced by default)
- CSRF Tokens - Enable CSRF protection for browser-based admin UIs
Complete Authentication Guide →
The SDK architecture supports future expansion:
- ✅ Publishing - Implemented
- 🔜 Authentication - User authentication
- 🔜 Users - User management
- 🔜 Workspaces - Workspace management
- 🔜 Events - Event streams
- 🔜 Webhooks - Webhook management
- 🔜 Search - Full-text search
- 🔜 AI - AI-powered features
The SDK is inspired by:
Simple to start, powerful as you grow.
Consumers think in Marvin concepts (Workspace, Entry, Collection), not raw REST endpoints.
Make sure your .env file exists with all required variables.
- Verify your site client token is valid
- Check that you're using a site client token, not a user token
- Ensure the token hasn't expired
Make sure your tsconfig.json includes:
{
"compilerOptions": {
"moduleResolution": "bundler",
"types": ["node"]
}
}MIT - Part of the Marvin project.
- 🔒 Security Audit Report - Complete security fixes (20 issues resolved)
- 📋 Security Fixes Summary - Key improvements and migration guide
- 🔐 Authentication Guide - Complete auth documentation and security best practices
⚠️ Error Handling Guide - Comprehensive error handling patterns- 🧪 Testing Guide - Testing strategy and security test examples
- 🔄 Migration Guide v2.0 - Upgrade from v1.x to v2.0
- 📖 Full Documentation
- 🚀 Quick Start Guide
- 🐛 Report Issues
- 🔒 Security Policy - Vulnerability reporting and security policy