8.5 KiB
8.5 KiB
Entity Types
The serving endpoint currently handles multiple distinct entity models within the platform. According to the route registrations in server/src/products/serving/index.ts, these are the primary operational entities managed by the system:
1. Content Entities
- Posts (
db-posts.ts): Primary content entities. Used in feeds and can be exported in various formats (PDF, JSON, HTML, Markdown, Rich HTML). - Pages (
pages-crud.ts): Standalone pages within the platform. Supports full version control (PageVersions), email rendering, and multiple export formats. - Categories (
db-categories.ts): Taxonomies for grouping and filtering items. IncludesCategoryItemsfor linking entities to a category.
2. Media & Engagement Entities
- Pictures (
db-pictures.ts): Standalone media assets supporting versioning, linking/unlinking, and batch uploads. - Comments (
db-pictures.ts): User engagement texts, typically attached to media or content, with support for toggling likes.
3. Structural Entities
- Types (
db-types.ts): Dynamically managed content definitions or data schemas. - Layouts (
db-layouts.ts): View templates and rendering layouts for the front-end or app components.
4. Internationalization (i18n) Entities
- Translations & Widget Translations (
db-i18n.ts): Granular text records mapped to UI components. - Glossaries & Glossary Terms (
db-i18n.ts): Translation dictionaries and terminology synchronization mappings (e.g., DeepL integration).
5. User Entities (db-user.ts)
- Profiles: The public-facing identity (
profilestable), storing fields likeusername,display_name,bio, andavatar_url. This entity relies on a centralized in-memory cache for high-performance reading and augmentation across the application. - User Secrets: Secure configurations (
user_secretstable) such asapi_keys,variables,shipping_addresses, andvendor_profiles. The API ensuresapi_keysare dynamically masked (showing only the last 4 characters) when served. - Admin Users: Management entities that bundle Supabase Auth identities with their respective
profilesand settings, allowing backend user lifecycle management.
6. Access Control (ACL) Entities (db-acl.ts)
- ACL Settings: A resource-agnostic wrapper used to define access rules. It delegates to specific backends (
IAclBackend, e.g., memory/VFS or Supabase DB) and encapsulates the owner andAclEntrydefinitions (which specifyuserIdorgroup, scoped to apathwith allowedpermissions). - Global ACL Groups: Hierarchical roles persisted in the database (
acl_groups), supporting relationships viaparent_id. - Group Memberships: Maps users to Global Groups (
acl_group_members). The ACL engine consolidates these explicit memberships with virtual identities (e.g., anonymous, authenticated, registered, admin) and local resource groups to evaluate effective permissions dynamically.
7. Platform Integration Entities (endpoints/products.ts)
- Products: Platform-level features or logical product definitions (
productstable). Each product holds anid,name,slug,description, and a flexiblesettingsJSON object (supporting logic likeenabled,default_cost_units, anddefault_rate_limit). Their administrative endpoints support full CRUD operations. Notably, deleting a product automatically removes any associatedproduct-aclrecords from theresource_acltable.
8. Contacts & Integrations Entities (products/contacts/index.ts)
- Contacts: The primary address book entity (
contactstable), storing fields likename,organization,emails,phone, andaddress. Supports bulk operations and bidirectional data exchange formats (including parsing and serialization for vCard). - Contact Groups & Memberships: Organizational buckets (
contact_groups) and their associated mapping table (contact_group_members) used to categorize constraints. - Mailboxes (IMAP Integration): Configuration records enabling automated connection to external email servers for contact harvesting. Includes specific OAuth2 handling for Gmail alongside traditional IMAP credential setups.
9. Server Middleware Layers (index.ts & middleware/)
The Polymech server pipeline implements a layered middleware architecture to enforce security, monitoring, and authentication before requests reach the endpoints.
- Content Security & CORS (
csp.ts): Sets up strict Content Security Policies, secure HTTP headers, and intercepts OPTIONS preflight requests globally. - Security & Blocking Pipeline:
- AutoBan Middleware (
autoBan.ts): Applied globally (*). Acts as an intrusion detection system (IDS) that catches directory traversal probes and enforces rate-limit bans across all HTTP traffic. - Blocklist Middleware (
blocklist.ts): Applied specifically to/api/*to enforce absolute IP or user-based blocklists before API logic is executed.
- AutoBan Middleware (
- Analytics (
analytics.ts): Traps requests globally (*) for telemetry, observability, and usage metric tracking. - Authentication & Authorization (
auth.ts):- Optional Authentication: By default, checks for a
Bearertoken or?token=query parameter (e.g., for SSE) and validates it against Supabase via an aggressive cache. Routes registered in thePublicEndpointRegistry(and the core/api/productsroute) bypass authentication requirements entirely. - Admin Enforcement: Intercepts requests meant for the
AdminEndpointRegistry. Requires a valid session payload and queriesuser_rolesto strictly enforce theadmincapability.
- Optional Authentication: By default, checks for a
- Content Compression: Global
hono/compressusage that is augmented with custom streaming logic to seamlessly gzip specialized, heavy geometry and vector assets (e.g.,model/stl,model/obj,vnd.dxf).
10. Product Tiering / Monetization (Freemium, Pro) via ACL Middleware [Proposed Architecture]
To seamlessly integrate subscription tiers on the server-side without overhauling existing database models, the platform can leverage the new ACL engine and middleware layers:
- ACL Group Hierarchy For Tiers: Instead of building custom licensing tables, product tiers map directly to Global ACL Groups utilizing inheritance.
tier:freemium(assigned automatically to registered users).tier:pro(inherits capabilities fromfreemium).- Upon webhook confirmation (e.g., Stripe payment), the user is upserted into the
tier:progroup viaacl_group_members.
- Product-Level Resource Gating: The
resource_acltable links an existing Product (from theproductstable, e.g.,contactsmodule) to a tier group (tier:pro) with explicitaccesspermissions. - Server Middleware Gating (
productAclMiddleware.ts): A dedicated middleware sits afterauth.ts(souserIdanduser.groupsare resolved).- Using the
IAclBackend, it evaluates if the user's combined implicit/explicit groups trigger anALLOWfor the requested API route. If denied, it handles the403 Payment/Upgrade Requiredresponse universally, keeping endpoint code clean.
- Using the
- Dynamic Rate Limits: The
products.settingsJSON (which holdsdefault_rate_limit) can be parsed by middleware. TheapiRateLimitercan then dynamically adjust throttles based on the user's tier, heavily restricting Freemium traffic while allowing Pro users unhindered access.
Example Integration Flow: Upgrading a User from Free to Pro
- Transaction Event: A user completes a checkout, and the external payment processor (e.g., Stripe) fires a secure webhook (like
checkout.session.completed) to the backend (POST /api/webhooks/billing). - Signature Verification: The server intercepts the webhook payload and validates its cryptographic signature.
- Identity Resolution: The server maps the external
customer_idfrom the payload back to the core Supabaseuser_id. - ACL Upsertion: The backend inserts or modifies the
acl_group_memberstable, mapping the resolveduser_idstrictly to thetier:proglobal ACL group. - Cache Invalidation: The server evicts the user's cached identity and permissions footprint from high-speed memory, forcing a fresh lookup.
- Instant Authorization: Upon the user's next API call, the request hits the
productAclMiddleware. TheIAclBackendrecalculates the merged groups, detects the activetier:proinheritance, and structurally allows access to Pro-restricted product features and modified rate limit overrides.
This brief documentation reflects the current state of CRUD routing and API interactions across the architecture.