TUASESOR Web Architecture
This document is the architectural source of truth for the TUASESOR web repository. It defines product ownership, system and data boundaries, integration contracts, security invariants, and design intent. It describes current implementation unless a capability is explicitly marked foundational, inactive, or planned.
When evidence conflicts, use this order: current application behavior; current database migrations and active security controls; approved architectural decisions committed to the repository; this document; ECOSYSTEM.md; DATABASE.md; REPOSITORY.md; the generated project tree; and finally the README. Generated structure and older descriptions never override running behavior, ownership, or security controls.
One current implementation limitation materially affects interpretation:
- The committed migration sequence contains an empty profile-foundation migration even though the exported schema and subsequent migrations contain and depend on
tuasesor.profiles. The exported shape and later security migrations evidence the repository's current model, but clean migration replay must not be assumed until that history is reconciled.
Repository Purpose
TUASESOR is a SaaS product boundary for small and medium-sized organizations and the professionals who support them. Such organizations may work with financial, accounting, labor, contractual, client, beneficiary, document, and other confidential business information. The repository exists to provide the browser product, directly owned server behavior, operational data model, and product-specific authorization decisions for those workflows.
The intended outcome is a controlled workspace-oriented environment in which authenticated people can use TUASESOR business workflows, connect their own external accounts, and work with operational information without collapsing identity, profile, tenant, and provider boundaries into one concept.
The repository is more than a UI package. It owns a vertical product boundary:
- the TUASESOR user experience and application navigation;
- the product's server-side API and orchestration surface;
- TUASESOR profiles and lifecycle gating;
- the workspace-oriented operational model and expense-report domain;
- product adapters that persist application state or call shared platform capabilities;
- database migrations and security controls for the
tuasesorschema.
It does not own Supabase Auth credentials, Google accounts or Drive content, Cortexa package implementations, cloud-provider operation, or unimplemented document-intelligence capabilities.
Ecosystem Role
TUASESOR sits at the vertical-product layer. It consumes reusable platform and infrastructure capabilities while retaining responsibility for product purpose, user experience, application authorization, data minimization, and the safe use of delegated processing.
Current ecosystem relationships are:
| System or module | Current relationship | Authority and ownership |
|---|---|---|
| Browser clients | Primary product consumer | TUASESOR owns the rendered experience and response contracts. |
| Supabase Auth | Authentication provider | Supabase establishes the authenticated identity; TUASESOR decides whether the corresponding profile may enter the product. |
| Supabase PostgreSQL/PostgREST | Persistence and data-access infrastructure | TUASESOR owns the application schema, migrations, data purpose, grants, and RLS policy design; Supabase operates the managed runtime. |
@cortexa/auth | Direct package dependency | Cortexa owns reusable provider OAuth and session orchestration; TUASESOR owns the provider configuration, persistence adapter, product routes, and connection ownership. |
@cortexa/connectors-google-drive | Direct package dependency | Cortexa owns Google Drive API abstraction and metadata mapping; TUASESOR owns when and why it is called and what is disclosed to the client. |
@cortexa/contracts | Declared local dependency | It is an ecosystem contract foundation, but current TUASESOR application code does not directly import it. Product-local contracts remain TUASESOR-owned unless deliberately promoted. |
| Google OAuth and Drive | External authorization and resource provider | Google remains authoritative for account authorization, files, folders, permissions, and provider metadata. |
The referenced Cortexa platform model also describes SDK, knowledge, capability, agent, and cloud modules. The current TUASESOR application does not import or call those modules. They are platform context or future candidates, not implemented TUASESOR architecture.
No Planetta-named runtime dependency, repository contract, configuration, or data flow exists in the inspected repository. Any relationship between TUASESOR and a broader Planetta organization or portfolio is therefore governance context outside this codebase, not an implemented integration or technical ownership claim.
See ECOSYSTEM.md for the wider product/platform relationship. Where that document describes earlier document synchronization behavior, current implementation takes precedence.
Architectural Responsibilities
TUASESOR owns the following implemented or directly represented responsibilities:
| Responsibility | TUASESOR ownership | Delegated capability |
|---|---|---|
| Product experience | Owns pages, layouts, navigation, loading/error states, and product-specific presentation. | UI libraries provide primitives only. |
| Application entry | Owns login UX, callback validation, profile lookup, and profile-status admission rules. | Supabase performs Google-backed application authentication and session handling. |
| Profile lifecycle | Owns the application profile, its business metadata, and pending, active, or disabled admission state. | Supabase Auth remains identity authority; a database trigger mirrors selected identity metadata. |
| Workspace business context | Owns workspace, membership, role, permission, and workspace-scoped domain concepts in the application schema. | PostgreSQL/RLS enforces membership on the implemented expense-report and catalog paths. |
| Expense reports | Owns the workspace-scoped domain model, validation, repository/service boundaries, authorized workspace discovery, listing, detail, initial draft creation, catalog reads, secure item create/update/delete operations, status-dependent editability, and accounting classification. | Supabase provides authenticated query and transaction execution; PostgreSQL grants, RLS, constraints, triggers, and invoker-rights RPCs enforce database authorization and integrity. |
| External account connection | Owns the decision to connect, the product routes, profile ownership, credential storage adapter, scopes requested, and reconnect/error behavior. | Cortexa auth orchestrates OAuth/session behavior; Google issues credentials. |
| My Space | Owns the product purpose, live-browse orchestration, metadata projection, and client disclosure. | The Cortexa connector calls Google Drive; Google remains resource authority. |
| Document persistence | Owns the schema surface and the decision to keep it closed until ownership is definitive. | No active application document repository, upload, or synchronization flow exists. |
| Documentation | Owns canonical repository documentation and its generation workflows. | Docusaurus copies and the generated tree are presentation/navigation artifacts. |
Responsibilities outside this repository include:
- credential verification and user-session infrastructure in Supabase Auth;
- Google authorization, token issuance, file storage, provider permissions, and availability;
- reusable OAuth internals in Cortexa auth;
- provider SDK isolation in the Cortexa Google Drive connector;
- hosting operations, backups, recovery, and monitoring not defined by committed infrastructure;
- OCR, parsing, extraction, classification, embeddings, semantic retrieval, agent execution, and knowledge services not called by the current application.
Delegation does not transfer TUASESOR's responsibility to define purpose, scope access, protect credentials, minimize returned data, respond to incidents, and maintain appropriate provider and contractual governance.
System Boundaries
Inside the repository boundary are:
- the Next.js application and its browser/server rendering behavior;
- application API route handlers;
- product services, repositories, provider factories, and persistence adapters;
- Supabase browser, server, and middleware client construction;
- the
tuasesordatabase model, migrations, grants, RLS policies, and RPCs; - canonical architecture, repository, database, and ecosystem documentation.
Outside the repository boundary are:
- Supabase-managed authentication identities and infrastructure;
- the hosted PostgreSQL, PostgREST, and network runtime;
- Google accounts, OAuth consent, Drive contents, Drive permissions, and sharing state;
- the source and release lifecycle of Cortexa packages referenced by local package dependencies;
- the deployment platform, production observability, backup execution, and incident operations;
- other business systems for which only mock or future UI references exist.
The important authority boundaries are:
- Identity:
auth.usersis authoritative for authenticated identity;tuasesor.profilesis authoritative for TUASESOR-specific profile state. - Profile: a profile owns its external integrations. A profile is not a workspace.
- Workspace: workspace records own workspace-scoped business aggregates. Access must derive from membership and authorization, not from a client-selected identifier alone.
- Provider: Google owns Drive resources and provider permissions. TUASESOR owns the meaning and disclosure of those resources within its product.
- Persistence: the repository owns schema intent and access rules; Supabase owns managed execution.
- Shared platform: Cortexa owns reusable module behavior; TUASESOR owns vertical workflows and product authorization.
- Deployment: the Next.js runtime and Supabase runtime are separate operational boundaries even when deployed as one product.
Locally authoritative information includes TUASESOR profile status, application roles and memberships, expense reports, and application configuration records. Externally authoritative information includes Supabase identity/session state and Google Drive resources. A provider identifier is a correlation value, not a substitute for local ownership.
High-Level Architecture
The implementation follows a layered, server-orchestrated web architecture:
Browser UI
|
v
Next.js routing, middleware, and application APIs
|
+--> TUASESOR services and repositories --> Supabase Auth/PostgreSQL
|
`--> TUASESOR adapters --> Cortexa auth/connectors --> Google
The layers have distinct responsibilities:
- Presentation layer: React client and server components render the product. Several surfaces still use static or local demonstration data; presentation does not make those domains authoritative.
- Request and session layer: Next.js middleware refreshes Supabase sessions and protects non-public pages. API routes are excluded from blanket middleware protection and must validate authentication and authorization themselves.
- Application layer: route handlers validate request context, select product services, translate failures into product responses, and decide which provider data reaches the browser.
- Domain/service layer: expense-report services validate inputs and require an authenticated user; the Google controller and auth service factory coordinate account authorization.
- Repository/adapter layer: the expense-report repository owns Supabase query/RPC mapping; the auth storage adapter implements the Cortexa storage contract against profile-owned integrations; the connector factory isolates connector construction.
- Persistence layer: Supabase PostgreSQL stores application state in the non-public
tuasesorschema. RLS and grants form part of application authorization rather than being mere infrastructure configuration. - External-provider layer: Cortexa abstractions isolate reusable OAuth and Drive behavior, while Google remains the source of provider resources.
The current source uses the public Supabase URL and anonymous client key with authenticated user cookies. It does not use a service-role credential in ordinary application flows. Database policy is therefore expected to constrain requests made on behalf of users.
Domain Overview
Only the following current concepts should be treated as architectural domain concepts:
| Concept | Architectural role and current status |
|---|---|
| Authenticated identity | Supabase Auth identity used to establish the server-validated user and auth.uid(). Implemented. |
| Profile | One-to-one TUASESOR application identity carrying contact/display metadata, global role, profile type, lifecycle status, and provider ownership. Implemented. |
| Workspace | Tenant-like operational context for collaborative business records. The application discovers the authenticated profile's available workspaces through membership-scoped server and database reads. The browser-selected workspace remains request and presentation context rather than authorization proof. |
| Workspace membership | Profile-to-workspace relationship carrying the coarse business role used by workspace discovery, expense-report authorization, and catalog RLS. |
| Workspace permission | Granular grant/deny record attached to a membership. Persisted as a foundation; current application routes, services, RPCs, and RLS do not evaluate permission keys. |
| Expense report | Workspace-owned aggregate with status, responsible profile, reporting period, notes, and expense lines. Listing, detail, initial draft creation, item totals, catalog reads, and secure item creation, update, and deletion are wired through the application. Item mutations are allowed only while the parent report remains draft. Formal submission, review, approval, rejection, reimbursement, cancellation, and document workflows remain unimplemented. |
| Expense-report item | Child financial record belonging to one expense report. Its mutation path preserves parent ownership, validates positive amounts and supported inputs, enforces same-workspace catalog references, and derives authorization through the parent report's workspace and status. |
| Business line, cost center, accounting account | Workspace-scoped classification catalogs read through membership-scoped access and validated against the expense report's workspace during item mutations. Catalog administration is not implemented. |
| Document type | Global reference catalog used by expense-item classification. Its use does not establish a document-processing workflow. |
| Integration | Profile-owned external account connection containing provider identity, scopes, token lifecycle data, and credentials. Google is the implemented provider. |
| Google Drive resource | Provider-owned live file or folder metadata projected into My Space. It is not currently a locally persisted TUASESOR document. |
| Document and normalized document | Persistence surfaces for operational metadata and derived content. No active application workflow uses them, and ordinary authenticated document access is closed. |
| Workspace source | Persisted model for a workspace/provider root. It is not used by the current My Space live-browse route. |
| Specialty/profile specialty | Profile-classification foundation without a current product workflow. |
| Transaction | Earlier or foundational financial persistence without a current application service or route. It is not the expense-report aggregate. |
Clients, tasks, calendar information, history, and control-tower events appear in mock, local-only, or preview UI. They are not active persisted domains. Google Calendar, SII, and automation integrations are not implemented.
Identity, Profiles, And Workspaces
Authentication identity, application profile, and workspace participation are separate:
- Supabase Auth establishes the identity and session.
- A TUASESOR profile uses the same UUID and stores application-specific data. A database trigger synchronizes selected email, name, avatar, and authentication metadata without granting product status, role, or profile type.
- Middleware and the application-auth callback require a profile with an email and an
activestatus. Missing, pending, disabled, or unknown statuses are rejected. - A workspace is an operational tenant-like context. Its creator reference does not make every creator-owned resource profile-owned.
- A workspace membership connects a profile to a workspace and carries a role.
- Workspace member permissions can represent granular grants or denials, but no current route, service, RPC, or policy implements their semantics.
- Integrations are profile-owned. Expense reports and their classification catalogs are workspace-owned.
WorkspaceProvider loads the authenticated profile's available workspaces through GET /api/workspaces. That endpoint derives its result from self-readable memberships and membership-scoped workspace reads. The browser may persist the selected workspace identifier in localStorage, but that identifier remains presentation and request context only. It cannot grant access to a workspace that the authenticated caller cannot read through the server and database authorization layers.
The expense-report application contract includes:
GET /api/expense-reportsfor workspace-scoped listing;POST /api/expense-reportsfor initial emptydraftcreation;- authenticated detail loading for a selected report, its items, and the active catalogs available within the supplied workspace;
- authenticated create, update, and delete operations for individual expense-report items.
The browser communicates only with TUASESOR application APIs. Route handlers validate authentication and request shape, services apply product validation, repositories map requests to authenticated Supabase queries or RPC calls, and PostgreSQL grants, RLS, constraints, triggers, and RPC authorization enforce the final data boundary.
Expense-item mutations require:
- an authenticated caller;
- membership in the parent report's workspace;
- an
owner,admin, ormemberrole; - a parent report whose status remains
draft; - a workspace identifier consistent with the parent report;
- valid item input and same-workspace catalog references.
viewer and client roles retain membership-scoped read access but cannot create, update, or delete expense items. Ordinary authenticated callers cannot delete expense-report headers. Granular permission keys and formal lifecycle-transition authorization remain unimplemented.
Authorization must be based on explicit authenticated identity and, as applicable, profile ownership, workspace membership, coarse role, resource ownership, and workflow state. The selected workspace identifier is never authorization proof, and application-level checks do not replace database enforcement.
Authentication And External Authorization
TUASESOR application authentication and Google Drive authorization are separate security concerns even though both currently use Google-facing consent flows.
Application authentication:
- the login page asks Supabase Auth to authenticate with Google;
- Supabase exchanges the callback code and establishes the TUASESOR session;
- the server validates the resulting user;
- TUASESOR independently validates that the application profile exists and is active.
External-provider authorization:
- a separate TUASESOR route starts Cortexa-managed Google authorization;
- the requested scopes include identity scopes and read-only Google Drive access;
- the callback requires an already authenticated TUASESOR user;
- the exchanged provider account is stored under that user's profile;
- subsequent Drive access obtains a valid provider session for the profile-owned integration.
Logging into TUASESOR therefore does not authorize My Space to read Google Drive. Connecting Google Drive is an explicit, separate grant. Conversely, a Google account identifier or token does not establish TUASESOR identity.
Authorization codes, client secrets, access tokens, refresh tokens, and credential-bearing session payloads are server-side confidential data. They must not be returned to browser clients, placed in documentation, or written to logs.
Contracts And Integration Points
The important contracts are responsibility boundaries, not endpoint inventories:
- Application authentication contract: a server-side Supabase client validates the current user. Page middleware also validates profile existence, email, and active status.
- Workspace-discovery contract:
WorkspaceProviderrequests the authenticated profile's available workspaces through a TUASESOR API. The server resolves self-readable memberships and membership-scoped workspace records. The selected identifier remains browser-held presentation and request context, not authorization proof. - Expense-report read contract: authenticated routes delegate workspace-scoped listing, report detail, item loading, and catalog reads to product services and repositories. Repository filters narrow the query, while grants and RLS enforce the final row boundary.
- Expense-report creation contract: initial creation produces an empty workspace-owned
draftthrough the service, repository, and invoker-rights report RPC. The authenticated actor is derived server-side, and ordinary callers cannot create reports outside an authorized writable workspace. - Expense-item mutation contract: create, update, and delete operations flow from TUASESOR APIs through services and repositories to invoker-rights RPCs. They require an authenticated workspace writer and a parent report that remains
draft. Constraints and triggers additionally preserve parent ownership, validate supported inputs, and prevent cross-workspace catalog references. - Cortexa auth storage contract: the Supabase adapter finds, saves, refreshes, and deletes provider accounts only with its constructor-supplied profile ID and provider/account lookup.
- Provider-session contract: Cortexa auth exchanges or refreshes credentials and supplies a usable access token to the connector without exposing it to the client.
- Google Drive connector contract: a provider token and listing options produce normalized file/folder metadata. Provider failures are translated into reconnect, retry, or support-oriented product errors.
- Persistence contract: repositories use the
tuasesorschema through an authenticated Supabase client. Grants permit an operation; RLS determines which rows the caller may access. RPC authorization, constraints, and triggers add workflow and integrity enforcement without replacing RLS. - Document-processing contract: none is active. Schema columns and Cortexa platform references do not constitute an implemented ingestion or extraction contract.
Inputs crossing these boundaries can include workspace and resource identifiers, search and filter values, dates, monetary amounts, supplier and document metadata, accounting classifications, provider metadata, and credentials. Each boundary must validate ownership, authorization, purpose, and sensitivity before returning or modifying data. External or database failures must not disclose credentials, raw provider payloads, unrelated tenant data, or unnecessary internal details.
External Integrations
Supabase
Supabase provides application authentication, PostgreSQL, PostgREST access, session cookies, and database roles. TUASESOR stores profiles, workspaces, memberships, integrations, expense reports, catalogs, and inactive/foundational domain surfaces in the tuasesor schema.
Supabase is authoritative for identity and managed runtime behavior. TUASESOR remains authoritative for schema purpose, product authorization policy, retention requirements, and which data is sent to or read from Supabase. The repository does not define hosting region, backups, disaster recovery, or provider contractual terms; those require operational verification outside the codebase.
Cortexa
Cortexa auth and the Google Drive connector are consumed as local package dependencies whose source lives outside this repository. They provide reusable horizontal capability, not TUASESOR business authorization.
The repository configures those modules, persists auth accounts, and decides when provider access is allowed. TUASESOR must not delegate profile or workspace authorization to a connector merely because the connector can call an external API.
Google
Google serves two purposes: an upstream identity provider used through Supabase Auth, and a separately authorized external resource provider used through Cortexa auth and the Drive connector.
The active Drive integration accesses file/folder metadata visible to the connected Google account under a read-only scope. It returns a minimized product projection, but that projection can still contain confidential names, identifiers, folder relationships, timestamps, sizes, MIME types, and links. Google remains authoritative for the resources, sharing state, and provider permissions.
The repository does not establish Google processing location, subprocessors, retention, or international-transfer terms. These are provider, organizational, and contractual matters that must be assessed for the applicable deployment and customer relationship.
No other provider integration is active. UI references to SII, Google Calendar, or future providers are mocks or previews.
Google Integration Architecture
The implemented Google connection model is profile-owned:
- A user explicitly starts provider authorization. The initiation route can produce the Google redirect without first validating a TUASESOR session; no connection is committed at that step.
- The callback validates the TUASESOR user, and Cortexa auth exchanges the authorization code with Google.
- TUASESOR's storage adapter saves the account in
tuasesor.integrationswith the authenticated profile ID. - A later Drive request validates the TUASESOR user, finds that profile's Google integration, obtains a valid provider session, and gives only the access token to the server-side connector.
- The connector lists resources and the API returns a product-specific metadata projection without returning credentials.
Current ownership controls include:
integrations.profile_idis required;- each profile has at most one integration per provider;
- a provider account is unique per provider across stored integrations;
- every adapter read, update, and delete is constrained by profile, provider, and provider-account identity;
- integration RLS permits an authenticated user to select, insert, update, or delete only rows whose profile ID equals
auth.uid(); - the Drive route repeats the profile constraint when locating the provider account.
Different profiles may connect different Google accounts. One profile must not read, refresh, update, or delete another profile's connection. The Google account identifier identifies the external account but never replaces TUASESOR profile ownership.
Credentials are stored in controlled database columns through the server-side adapter. The repository evidences RLS and restricted application access but does not evidence application-layer token encryption, a rotation policy, or a credential audit trail. Those protections must not be claimed as implemented.
Google client credentials come from server runtime configuration. Provider tokens and authorization codes are not included in current client responses. Google-specific handlers log sanitized error classifications and aggregate file counts rather than credential payloads; this convention is a security invariant for future changes.
My Space And External Resources
My Space is a live view over the connected profile's Google Drive resources:
- resources are listed from Google on each request;
- listing is non-recursive and can be narrowed by a parent folder;
- the configured root folder, when present, limits the root listing; otherwise the connector's accessible root/shared behavior applies;
- returned resources are mapped to identifiers, names, types, MIME types, parent relationships, timestamps, sizes, links, provider/source labels, and a presentation status;
- the current route does not insert or update
tuasesor.documents,workspace_sources, or another local metadata index.
Google is therefore authoritative for My Space resources. The TUASESOR database stores the profile-owned connection, not the returned resource catalog. Provider metadata remains transient in the application response and browser state.
My Space requires both an authenticated TUASESOR profile context and a valid profile-owned Google connection. When the connection is absent, the API instructs the product to connect. Revoked or invalid authorization results in a reconnect outcome; retryable provider failure results in a temporary-unavailability outcome. These failures must not fall back to another profile's connection.
The access token, refresh token, provider session, client secret, and raw credential-bearing payload remain server-side. External identifiers and links are not credentials, but they are sensitive metadata and must be disclosed only for the My Space purpose.
My Space is currently profile-scoped, not workspace-scoped. The client workspace selector does not change which Google integration is used. Introducing workspace-owned provider sources would require an explicit ownership, membership, permission, and retention design rather than reusing the profile connection implicitly.
Document And File-Processing Boundary
The active repository does not implement document upload, download, synchronization, parsing, OCR, extraction, classification, embedding, semantic retrieval, or derived-document workflows.
Current boundaries are:
- Google Drive metadata is read live for My Space and is not persisted as a TUASESOR document.
tuasesor.documentsremains an operational persistence surface with provider-specific and workspace/profile association fields, but the current application has no document API or repository using it.- ordinary anonymous and authenticated privileges on
documentsare revoked, RLS is enabled, and no authenticated policies are defined. The table is intentionally closed until a definitive ownership model exists. tuasesor.normalized_documentsexists as a possible derived-content surface, but no current source calls it. RLS is enabled without user policies, so its broad historical grants do not make rows available to ordinary RLS-bound users.- document types remain a global classification catalog used by the expense-report creation contract; they do not establish a file-processing pipeline.
- the Google connector listing contract is an external metadata contract, not ingestion or document intelligence.
The Cortexa reference describes SDK and future knowledge capabilities, but TUASESOR does not currently depend on the SDK or a knowledge service. OCR, normalization, extraction, knowledge indexing, and similar capabilities are non-implemented. Any future implementation must establish purpose, source ownership, workspace/profile authorization, derived-data ownership, retention, source-removal behavior, and deletion before opening persistence.
Persistence And Data Ownership
TUASESOR uses Supabase PostgreSQL and a dedicated non-public tuasesor schema. Migrations control schema evolution; generated schema exports support inspection but do not replace migrations or active runtime controls. DATABASE.md contains schema-level detail.
The ownership model is mixed by design:
- profiles own external integrations and profile-classification relationships;
- workspaces own memberships, workspace sources, expense reports, and workspace-specific catalogs;
- expense reports own their line items;
- Google owns live My Space files and folders;
- TUASESOR owns persisted application records and the purpose for which they exist;
- Supabase manages identity and infrastructure, not TUASESOR business ownership.
Foreign keys, cascades, checks, uniqueness constraints, grants, policies, functions, and triggers encode parts of this model. Implemented examples include:
- unique membership per profile and workspace;
- one integration per profile and provider;
- unique provider-account use where identifiers are present;
- workspace/year report numbering;
- allowed expense-report statuses;
- positive expense amounts and bounded item text;
- immutable expense-item parent relationships;
- same-workspace validation for business lines, cost centers, and accounting accounts.
Current database authorization is deliberately uneven and must be described precisely:
- integrations have profile-owner RLS and authenticated CRUD grants;
- authenticated members may read only their own memberships;
- authenticated callers may discover only workspaces in which they have a membership;
- expense reports and items have membership-scoped read policies;
owner,admin, andmembermay write reports through the coarse workspace-role helper;owner,admin, andmembermay create, update, or delete items only while the parent report remainsdraft;viewerandclientremain read-only for the implemented expense-report workflow;- business lines, cost centers, and accounting accounts have membership-scoped read policies;
- documents remain closed to ordinary users;
- normalized documents remain closed through RLS without ordinary-user policies;
- profiles remain selectable by authenticated users without profile-specific RLS;
- granular workspace permission rows are persisted but are not evaluated by current application routes, services, RPCs, or policies;
- workspace and membership administration require a separately controlled privileged process because no ordinary product administration workflow is implemented.
The expense-report path therefore demonstrates authorized workspace discovery, membership-scoped reads, coarse role-aware writes, state-dependent item mutation, and database-enforced integrity. It does not establish complete tenant administration or uniform isolation across every historical or foundational table.
Persisted data must have a defined product purpose, owner, access model, retention expectation, and correction, blocking, export, deletion, or preservation path where applicable. The current schema includes foreign-key deletion behavior, but the repository does not implement a complete data-rights or retention workflow. Technical cascades are not a retention policy.
OAuth credentials require stronger handling than ordinary metadata. RLS and server-side adapters are implemented; application-layer token encryption, credential rotation procedures, and credential-access auditing are not evidenced.
Security And Authorization Responsibilities
Security is divided across distinct enforcement layers:
| Layer | Implemented responsibility |
|---|---|
| Application identity | Supabase getUser() validates the user server-side. |
| Profile admission | Middleware and the authentication callback require an existing active profile with an email. |
| Workspace discovery | The server resolves the caller's self-readable memberships and membership-scoped workspaces before presenting workspace choices. |
| Application authorization | Routes validate authentication and request shape; services apply product validation and determine the intended operation. |
| Repository scoping | Repositories pass explicit workspace and resource identifiers through authenticated Supabase clients and map product operations to queries or RPCs. |
| Database authorization | PostgreSQL grants and RLS use auth.uid() for profile ownership or workspace membership. The coarse workspace-role helper authorizes implemented writer roles. |
| Workflow enforcement | Expense-item RPCs require a writable workspace role and a parent report whose status remains draft. |
| Database integrity | Constraints and triggers enforce positive and bounded inputs, immutable item parentage, and same-workspace catalog references. |
| Provider authorization | Google scopes and Cortexa session handling determine which external resources the profile-owned connection can access. |
| Infrastructure privilege | Supabase roles and provider secrets support runtime access; no service-role key is used by current ordinary product source. |
The implemented integration path prevents cross-profile access by combining authenticated user lookup, profile-filtered queries, adapter scoping, and RLS.
The implemented expense-report path combines:
- server-derived workspace choices;
- membership-scoped workspace, report, item, and catalog reads;
- role-aware report and item writes;
draft-state enforcement for item mutations;- repository workspace scoping;
- grants, RLS, invoker-rights RPCs, constraints, and triggers.
This does not make workspace isolation universally complete. Workspace and membership administration remain outside ordinary product workflows, granular permission keys are not evaluated, no server-owned active-workspace session exists, and older or foundational persistence surfaces are not uniformly protected.
Least privilege is visible in the Google Drive read-only scope, authenticated invoker-rights RPCs, read-only catalog access, owner-only integration policies, protected membership reads, and the closed document surface. It is not uniform across all older or foundational tables, so no repository-wide least-privilege claim is justified.
Errors returned by Google and expense-report flows must be translated into bounded product responses. Credentials, full financial payloads, personal data, provider payloads, and unrelated database details must not be written to untrusted logs or exposed to clients. Current server logging must continue to be reviewed as these workflows mature.
The audit schema is declared but no active audit/event model is implemented. Sensitive-operation traceability, security-event evidence, and tamper-resistant history remain operational and architectural gaps rather than existing controls.
Workspace And Tenant Isolation
TUASESOR has several different isolation domains:
- Profile-owned: external integrations and associated credential lifecycle.
- Workspace-owned: expense reports, expense items through their parent, and workspace-specific business/accounting catalogs.
- Provider-owned: Google files, folders, permissions, and sharing state.
- Application-owned: profile status, product responses, and persisted business records.
- Platform-managed: authentication/session infrastructure and reusable Cortexa behavior.
Implemented workspace isolation for the expense-report workflow includes membership-scoped reads for workspaces, reports, items, and catalogs; explicit workspace filters in the repository; coarse writer-role enforcement for owner, admin, and member; read-only behavior for viewer and client; and draft-state enforcement for item mutations. Supplying a workspace identifier alone does not satisfy these controls.
The current application is still not a complete tenant-administration boundary:
- workspace choices are loaded from the authenticated caller's authorized memberships, but the selected workspace remains browser-held request context rather than a server-owned active-workspace session;
- ordinary authenticated callers can read only their own membership rows and cannot mutate them, but no product workflow creates workspaces or administers memberships;
- coarse workspace roles are enforced for the implemented expense-report workflow, while granular permission records remain unused;
- formal lifecycle operations do not yet have action-specific authorization;
- not every persistence surface is workspace-owned or uniformly protected.
Profile isolation for Google integrations remains a separate implemented boundary. Provider-owned My Space resources follow the authenticated profile's connection, not workspace membership. A future workspace-owned Google model must not silently merge those boundaries.
Privacy And Data Protection
The architecture can process materially sensitive information:
- profile email, name, avatar, status, role/type, and authentication metadata;
- Google account identifiers, scopes, access tokens, refresh tokens, expiration, and provider metadata;
- Drive file names, identifiers, folder structure, MIME types, timestamps, sizes, and links;
- expense dates, suppliers, document identifiers, descriptions, notes, amounts, classifications, and responsible profiles;
- potentially financial, labor, contractual, client, beneficiary, and confidential business information if future document or workflow surfaces are opened.
Architecture changes must identify the data subject, business purpose, source, local owner, permitted users, provider recipients, storage location, retention, correction, export, blocking, and deletion path. Metadata deserves the same analysis as file contents because names, folder relationships, and identifiers can disclose sensitive activity.
Implemented privacy-relevant controls include:
- separate application authentication and provider consent;
- a read-only Drive scope;
- profile-owner RLS for external credentials;
- live provider reads without duplicating Drive metadata locally;
- server-only credential handling;
- closed document and normalized-document user surfaces;
- workspace membership policies on the implemented expense-report path;
- rejection of inactive application profiles.
Not implemented or not evidenced are:
- a documented retention schedule;
- user-facing export, correction, blocking, or deletion workflows;
- source-document removal propagation;
- token encryption at the application layer;
- a comprehensive audit trail;
- provider-region and international-transfer configuration;
- incident-response, breach-notification, or evidence-retention procedures;
- uniform tenant isolation across all persistence surfaces.
The party acting as responsible entity, controller, processor, or subprocessor depends on the customer relationship and provider contracts; the repository cannot determine those legal roles. Supabase, Google, Cortexa, hosting providers, and possible international transfers require organizational and contractual review. Material conclusions under Chilean privacy, labor, financial, or other law require validation by a Chilean lawyer or the designated legal/privacy responsible role. Technical controls alone do not establish compliance.
Infrastructure Responsibilities
Verified infrastructure dependencies and responsibilities are:
- Next.js runtime: executes pages, middleware, callbacks, and application APIs. The repository does not identify a production hosting provider.
- Supabase: runs authentication, PostgreSQL, PostgREST, sessions, and database roles. TUASESOR owns migration content, grants, RLS intent, application queries, and safe configuration.
- Google: operates OAuth and Drive. TUASESOR owns requested scopes, connection purpose, failure behavior, and disclosure to the product.
- Cortexa packages: provide external local package implementations for auth and Drive connector behavior. TUASESOR owns compatible configuration and adapters.
- Configuration and secrets: public Supabase connection values are supplied through runtime configuration; Google client credentials and redirect configuration are server runtime secrets; provider tokens are persisted in the database.
The repository does not verify production deployment automation, centralized observability, backup schedules, recovery objectives, secret rotation, or provider failover. These remain operational responsibilities outside the committed implementation and must not be inferred.
Documentation generation is development infrastructure, not runtime infrastructure. scripts/generate-project-tree.ps1 generates docs/repository/project-tree.md; run npm run docs:tree after meaningful structural changes. The generated file must not be edited manually.
Architectural Constraints And Invariants
The following rules must remain true as implementation changes:
- Authenticated identity must be validated server-side for protected operations.
- A TUASESOR profile must not be treated as interchangeable with a Supabase identity, Google account, or workspace.
- Profile-owned integrations must remain scoped to the authenticated profile in application queries, adapters, grants, and RLS.
- Provider account identifiers must never replace TUASESOR ownership keys.
- Workspace-owned data must require authenticated workspace membership; roles and permissions must also be enforced when a workflow depends on them.
- Client-selected workspace identifiers must never be treated as authorization proof.
- One profile or tenant must not access another profile's credentials or another workspace's protected business data.
- Application authentication and external-provider authorization must remain separate explicit flows.
- Tokens, authorization codes, client secrets, and credential-bearing payloads must remain server-side and absent from client responses, logs, examples, and documentation.
- External resources must not be persisted without a defined purpose, ownership model, authorization model, and retention/deletion design.
- Provider-authoritative resources should be read live when local duplication has no justified product purpose.
documentsand derived-content surfaces must remain closed until their profile/workspace ownership and access policies are explicit.- Database grants and RLS must be reviewed together; either control alone is not a complete authorization model.
- Ordinary user flows must use least privilege. Elevated or service-level credentials must not silently replace user-context authorization.
- TUASESOR product workflows and authorization remain separate from reusable Cortexa platform behavior.
- Source code should depend on the existing service, repository, storage-adapter, and connector abstractions when those boundaries apply.
- Removed, mock, empty, or schema-only capabilities must not be documented as active.
- Current implementation and active security controls remain the primary technical source of truth.
- The generated project tree is navigation only, must be regenerated rather than edited, and cannot define ownership.
- Architecture documentation must describe durable boundaries rather than duplicate repository navigation, endpoints, schemas, or transient implementation details.
Extensibility And Design Principles
Observable design principles include:
- Server-side orchestration: provider credentials and privileged provider calls remain behind application APIs.
- Separate identity domains: Supabase authentication, TUASESOR profile admission, workspace authorization, and Google consent are distinct.
- Repository and service boundaries: expense-report validation, data mapping, and persistence are separated.
- Adapter-owned persistence: the Cortexa auth storage interface is implemented by a TUASESOR Supabase adapter, preserving platform/product independence.
- Provider abstraction: the application constructs a Cortexa Drive connector rather than embedding Google SDK calls throughout product code.
- Explicit ownership keys: profile IDs and workspace IDs express different ownership models.
- Defense in depth where implemented: route checks, scoped queries, grants, RLS, and provider scopes reinforce the integration and expense-report paths.
- Incremental migrations: database changes, integrity rules, grants, RLS, and RPCs evolve through ordered migrations.
- Minimal provider duplication: My Space reads live external metadata instead of maintaining a local copy without a current need.
- Vertical/horizontal separation: TUASESOR owns product workflows; Cortexa owns reusable cross-product auth and connector behavior.
These patterns are not universal maturity claims. Workspace discovery and selection are now server-backed, but the selected workspace remains browser-held request context; workspace administration, granular permission semantics, lifecycle-specific authorization, comprehensive auditing, and uniform least privilege across older persistence surfaces remain incomplete. No document-processing pipeline exists.
Extensions should preserve dependency direction: presentation depends on product APIs; APIs depend on services and repositories/adapters; TUASESOR adapters depend on stable Cortexa or Supabase interfaces; external providers must not depend on TUASESOR internals.
Inactive Or Superseded Architecture
The following surfaces must not be interpreted as active architecture:
- earlier documentation claims that Drive metadata is synchronized into
tuasesor.documents; - document listing/creation APIs that are no longer present;
- document upload, OCR, extraction, normalization, knowledge, embeddings, and semantic retrieval inferred from tables or Cortexa strategy;
- workspace source usage inferred from its schema alone;
- client management backed only by local mock records;
- task, history, calendar, control-tower, and dashboard data rendered from local or static examples;
- SII, Google Calendar, automation, non-Google connectors, or Planetta integration inferred from labels or ecosystem aspiration;
- audit/event behavior inferred from the existence of an empty audit schema;
- transaction or professional-specialty workflows inferred from persistence foundations without active services.
The current active server-backed boundary includes authenticated profile admission, profile-owned Google connection, live My Space browsing, authorized workspace discovery, workspace-scoped expense-report listing and detail, initial draft creation, catalog reads, and secure expense-item management while reports remain draft. Formal expense-report lifecycle transitions, document workflows, workspace administration, and granular permission evaluation remain outside the implemented boundary.
Documentation Corpus Map
Only existing canonical documents are linked here:
- README.md: repository entry point, introductory context, setup, and common commands.
- ARCHITECTURE.md: ownership, boundaries, contracts, invariants, security principles, and design intent.
- REPOSITORY.md: repository organization, package responsibilities, code-placement guidance, and contributor navigation.
- repository/project-tree.md: generated structural snapshot for locating current files and validating broad organization. It does not define architecture or ownership, must not be edited manually, and must be regenerated with
npm run docs:treeafter meaningful structural changes. - DATABASE.md: persistence architecture, schema organization, data ownership, RLS, grants, migration responsibilities, and retention/deletion implications.
- ECOSYSTEM.md: ecosystem relationships, capability ownership, and TUASESOR/Cortexa/external-system boundaries.
- references/CORTEXA_PLATFORM.md: Cortexa platform context, horizontal capability ownership, module relationships, and explicitly future platform direction.
Generated database schema material and the Docusaurus site are supporting references or publication copies. They do not override current application behavior, migrations, active security controls, or canonical documents.
Guidance For Developers And AI Agents
Contributors and AI agents should:
- inspect current implementation before proposing an architectural change;
- read this document for product responsibilities, ownership, boundaries, contracts, and invariants;
- read DATABASE.md and active migrations before changing persistence, grants, RLS, retention, or deletion behavior;
- read ECOSYSTEM.md and the relevant Cortexa reference before moving responsibility between TUASESOR and a shared platform;
- read REPOSITORY.md for code-placement and repository conventions;
- use the generated project tree for navigation only;
- regenerate the project tree with
npm run docs:treeafter meaningful structural changes; - preserve the distinction among Supabase identity, TUASESOR profile, workspace membership, and provider account;
- preserve profile isolation and strengthen workspace isolation rather than relying on client context;
- identify sensitive content and metadata before changing a workflow;
- avoid collecting or persisting data without an explicit purpose and owner;
- prefer narrower grants, scopes, responses, and provider access;
- consider access, retention, correction, export, blocking, source removal, and deletion before introducing persistence;
- keep credential handling server-side and sanitize logs and errors;
- distinguish implemented behavior from schema foundations, mocks, planned platform capability, and historical remnants;
- treat roles and permission records as non-enforced until application and database policy actually evaluate them;
- do not reopen
documentsor derived-content storage without an approved ownership and authorization model; - update this document only when purpose, responsibility, ownership, boundaries, contracts, dependency direction, data ownership, security invariants, privacy-relevant design, infrastructure responsibility, or ecosystem relationships materially change.
Routine component, route, schema-field, or feature additions that preserve these boundaries should be documented in their more specific source of truth rather than expanding this document into an inventory.