/** * Reviewable policy semantics that cannot be inferred safely from field names. * Direct required-tenant models use their manifest `tenantId` contract. Every * nullable model and every FK-derived child is declared explicitly here. */ function ownershipPath(relations, options = {}) { return Object.freeze({ relations: Object.freeze(relations), ...options }); } function ownership(options) { return Object.freeze({ readGlobal: false, anyOf: Object.freeze(options.anyOf ?? []), allOf: Object.freeze(options.allOf ?? []), optionalAllOf: Object.freeze(options.optionalAllOf ?? []), identityAnyOf: Object.freeze(options.identityAnyOf ?? []), ...(options.platformAnalytics ? { platformAnalytics: Object.freeze({ kind: options.platformAnalytics.kind, commands: Object.freeze(options.platformAnalytics.commands), }), } : {}), ...(options.readGlobal === true ? { readGlobal: true } : {}), ...(options.risk ? { risk: options.risk } : {}), }); } const WORKFLOW_GLOBAL_READ_FIELDS = Object.freeze({ status: "live", appliesToAllTenants: true, }); function workflowDefinitionPath(relations, options = {}) { return ownershipPath(relations, { allowGlobalRead: true, globalReadFields: WORKFLOW_GLOBAL_READ_FIELDS, workerReadGlobal: true, ...options, }); } const PUBLIC_ENABLED_KNOWLEDGE_BASE_FIELDS = Object.freeze({ enabled: true }); const PUBLIC_PUBLISHED_ARTICLE_FIELDS = Object.freeze({ publishedAt: Object.freeze({ notNull: true }) }); const PLATFORM_ANALYTICS_VISITOR_ACCESS = Object.freeze({ kind: "anonymous-visitor", commands: Object.freeze(["select", "insert", "update"]), }); const PLATFORM_ANALYTICS_CHILD_ACCESS = Object.freeze({ kind: "anonymous-visitor-child", commands: Object.freeze(["select", "insert"]), }); function publicKnowledgeBasePath(relations, options = {}) { return ownershipPath(relations, { operatorReadGlobal: true, operatorWriteGlobal: true, publicReadGlobal: true, publicTerminalFields: PUBLIC_ENABLED_KNOWLEDGE_BASE_FIELDS, ...options, }); } export const MIXED_POLICY_CONTRACT = Object.freeze({ AuditChainCheckpoint: Object.freeze({ select: "tenant-only", write: "tenant-only", workerReadAllTenants: true, workerWriteAllTenants: true, operatorReadGlobal: true, }), AuditChainHead: Object.freeze({ select: "tenant-only", write: "tenant-only", workerReadAllTenants: true, workerWriteAllTenants: true, operatorReadGlobal: true, operatorWriteGlobal: true, }), AuditChainCheckpointHead: Object.freeze({ select: "tenant-only", write: "tenant-only", workerReadAllTenants: true, workerWriteAllTenants: true, operatorReadGlobal: true, }), IdempotencyKey: Object.freeze({ select: "tenant-only", write: "tenant-only", workerReadGlobal: true, workerWriteGlobal: true, workerGlobalWhere: '"systemOwned" = true', workerGlobalRequiresNoTenantContext: true, risk: "System idempotency is available only to an unbound worker; tenant rows always require the matching tenant context", }), AutomationTemplate: Object.freeze({ select: "tenant-and-global", write: "tenant-only", globalReadWhere: `"isPublished" = true AND "archivedAt" IS NULL`, workerReadGlobal: true, }), Log: Object.freeze({ select: "tenant-or-identity", write: "tenant-or-identity", identityField: "userId", workerReadGlobal: true, workerWriteGlobal: true, operatorReadAllTenants: true, risk: "Pre-tenant authentication logs are identity-scoped for users; authenticated operators have read-only cross-tenant audit visibility", }), AuditEvent: Object.freeze({ select: "tenant-only", write: "tenant-only", workerReadAllTenants: true, workerWriteAllTenants: true, operatorReadAllTenants: true, operatorWriteGlobal: true, risk: "The retention worker owns the chain globally; authenticated operators can read every tenant while their writes remain restricted to platform rows", }), ApiKeyLog: Object.freeze({ select: "tenant-only", write: "tenant-only", workerReadGlobal: true, workerWriteGlobal: true, operatorReadAllTenants: true, risk: "Authenticated operators can inspect the global API-call ledger, but app writes remain tenant-bound and tenantless writes remain worker-only", }), Event: Object.freeze({ select: "tenant-or-identity", write: "tenant-only", identityField: "userId", commandPolicy: "immutable-event", workerReadAllTenants: true, workerWriteAllTenants: true, operatorReadAllTenants: true, risk: "App events are immutable after an owner-bound insert; the reviewed worker remains the only global mutator and operators retain read-only inbox access", }), MetricLog: Object.freeze({ select: "tenant-only", write: "tenant-only", workerReadGlobal: true, workerWriteGlobal: true }), Widget: Object.freeze({ select: "tenant-only", write: "tenant-only", risk: "Nullable legacy widgets stay hidden until their global distribution semantics are reviewed", }), EmailSender: Object.freeze({ select: "tenant-only", write: "tenant-only", workerReadGlobal: true, risk: "NULL rows contain provider secrets and must remain platform-only", }), Campaign: Object.freeze({ select: "tenant-only", write: "tenant-only", workerReadGlobal: true, workerWriteGlobal: true }), OutboundEmail: Object.freeze({ select: "tenant-only", write: "tenant-only", workerReadGlobal: true, workerWriteGlobal: true }), EmailSequence: Object.freeze({ select: "tenant-and-global", write: "tenant-only", workerReadGlobal: true, operatorReadGlobal: true, operatorWriteGlobal: true, risk: "System sequences are readable by tenants, writable by authenticated platform operators, and executable by the worker", }), EmailSequenceRun: Object.freeze({ select: "tenant-only", write: "tenant-only", workerReadGlobal: true, workerWriteGlobal: true, operatorReadAllTenants: true, operatorWriteGlobal: true, risk: "Authenticated operators can aggregate tenant and lead-targeted runs read-only; writes stay tenant-bound except for explicit platform runs", }), FeatureFlag: Object.freeze({ select: "platform-exception", write: "platform-exception", risk: "AD-1 excludes feature flags from tenant RLS; access remains a separate platform contract", }), KnowledgeBase: Object.freeze({ select: "tenant-only", write: "tenant-only", operatorReadGlobal: true, operatorWriteGlobal: true, publicReadFields: PUBLIC_ENABLED_KNOWLEDGE_BASE_FIELDS, risk: "Tenantless knowledge bases are authorable by platform operators and publicly readable only through an enabled-id capability", }), NotificationDelivery: Object.freeze({ select: "tenant-or-identity", write: "tenant-only", identityField: "userId", additionalIdentityFields: Object.freeze(["adminUserId"]), workerReadGlobal: true, workerWriteGlobal: true, operatorWriteGlobal: true, }), DeviceToken: Object.freeze({ select: "tenant-or-identity", write: "tenant-or-identity", identityField: "userId", workerReadGlobal: true }), OnboardingSession: Object.freeze({ select: "tenant-or-identity", write: "tenant-or-identity", identityField: "userId", risk: "Pre-tenant onboarding sessions remain outside tenant runtime and require an identity-scoped path", }), OutboxEvent: Object.freeze({ select: "tenant-only", write: "tenant-only", commandPolicy: "immutable-user-trigger-outbox", workerReadAllTenants: true, workerWriteAllTenants: true, risk: "App outbox rows are immutable and limited to the active tenant or an exact user-owned workflow trigger; the dispatcher worker remains the global mutator", }), Role: Object.freeze({ select: "tenant-and-global", write: "tenant-only", operatorWriteGlobal: true, risk: "Global role templates are mutable only by authenticated platform operators; tenant roles remain bound to the active tenant", }), UserRole: Object.freeze({ select: "tenant-or-identity", write: "tenant-only", identityField: "userId", commandPolicy: "scoped-user-role-assignment", workerReadGlobal: true, operatorReadGlobal: true, operatorWriteGlobal: true, risk: "Global admin-role assignments require an authenticated operator; tenant assignments require the active tenant and an app role", }), Group: Object.freeze({ select: "tenant-only", write: "tenant-only" }), Workflow: Object.freeze({ select: "tenant-and-global", write: "tenant-only", globalReadWhere: `"status" = 'live' AND "appliesToAllTenants" = true`, workerReadGlobal: true, }), WorkflowExecution: Object.freeze({ select: "tenant-only", write: "tenant-only", workerReadGlobal: true, workerWriteGlobal: true, risk: "Global workflow definitions may execute for a tenant, but execution rows are never globally readable", }), WorkflowVariable: Object.freeze({ select: "tenant-only", write: "tenant-only", workerReadGlobal: true, risk: "NULL workflow variables remain platform-only because values may be sensitive", }), WorkflowCredential: Object.freeze({ select: "tenant-only", write: "tenant-only", workerReadGlobal: true, risk: "NULL workflow credentials remain platform-only because values are secrets", }), }); /** * Tenant-owned ledgers that runtime roles may append to but never mutate. * Sequence access is declared alongside the table contract so a new serial * dependency cannot inherit broad schema privileges accidentally. */ export const APPEND_ONLY_TENANT_MODEL_CONTRACT = Object.freeze({ TeamChatEvent: Object.freeze({ commands: Object.freeze({ select: "tenant-only", insert: "tenant-only", update: "none", delete: "none", }), sequence: Object.freeze({ name: "TeamChatEvent_sequence_seq", privilege: "USAGE", roles: Object.freeze(["hivegrid_app", "hivegrid_worker"]), }), risk: "Durable chat events are append-only; runtime roles need only tenant-bound reads, inserts, and nextval access", }), }); export const DERIVED_OWNERSHIP_CONTRACT = Object.freeze({ AnalyticsUniqueVisitor: ownership({ anyOf: [ownershipPath(["portal"]), ownershipPath(["portalUser"])], optionalAllOf: [ownershipPath(["portal"]), ownershipPath(["portalUser"])], platformAnalytics: PLATFORM_ANALYTICS_VISITOR_ACCESS, risk: "The isolated analytics capability may read, insert, and update only fully anonymous rows; tenant and portal ownership remains the alternative scoped path", }), AnalyticsPageView: ownership({ anyOf: [ownershipPath(["uniqueVisitor", "portal"]), ownershipPath(["uniqueVisitor", "portalUser"])], optionalAllOf: [ownershipPath(["portal"]), ownershipPath(["portalUser"])], platformAnalytics: PLATFORM_ANALYTICS_CHILD_ACCESS, risk: "The isolated analytics capability may read and insert only portal-free rows whose referenced visitor is fully anonymous", }), AnalyticsEvent: ownership({ anyOf: [ownershipPath(["uniqueVisitor", "portal"]), ownershipPath(["uniqueVisitor", "portalUser"])], optionalAllOf: [ownershipPath(["portal"]), ownershipPath(["portalUser"])], platformAnalytics: PLATFORM_ANALYTICS_CHILD_ACCESS, risk: "The isolated analytics capability may read and insert only portal-free rows whose referenced visitor is fully anonymous", }), EventWebhookAttempt: ownership({ allOf: [ ownershipPath(["event"], { workerReadGlobal: true, workerWriteGlobal: true, operatorReadAllTenants: true, operatorWriteGlobal: true, }), ], risk: "The platform inbox reads every attempt; writes stay tenant-bound except for tenantless platform events", }), Email: ownership({ allOf: [ownershipPath(["tenantInboundAddress"])], risk: "Legacy emails without tenantInboundAddressId have no tenant ownership and remain hidden", }), EmailRead: ownership({ allOf: [ownershipPath(["email", "tenantInboundAddress"])] }), EmailCc: ownership({ allOf: [ownershipPath(["email", "tenantInboundAddress"])] }), EmailAttachment: ownership({ allOf: [ownershipPath(["email", "tenantInboundAddress"])] }), OutboundEmailOpen: ownership({ allOf: [ownershipPath(["outboundEmail"])] }), OutboundEmailClick: ownership({ allOf: [ownershipPath(["outboundEmail"])] }), EmailSequenceStepDelivery: ownership({ allOf: [ ownershipPath(["run"], { workerReadGlobal: true, workerWriteGlobal: true, operatorReadAllTenants: true, operatorWriteGlobal: true, }), ], risk: "Authenticated operators can aggregate tenant and lead-targeted deliveries read-only; writes inherit the run boundary", }), FeatureFlagFilter: ownership({ allOf: [ownershipPath(["featureFlag"])] }), FeatureFlagAudit: ownership({ allOf: [ownershipPath(["flag"])] }), KnowledgeBaseCategory: ownership({ allOf: [publicKnowledgeBasePath(["knowledgeBase"])] }), KnowledgeBaseCategorySection: ownership({ allOf: [publicKnowledgeBasePath(["category", "knowledgeBase"])] }), KnowledgeBaseArticle: ownership({ allOf: [publicKnowledgeBasePath(["knowledgeBase"], { publicRowFields: PUBLIC_PUBLISHED_ARTICLE_FIELDS })], optionalAllOf: [ publicKnowledgeBasePath(["category", "knowledgeBase"], { publicRowFields: PUBLIC_PUBLISHED_ARTICLE_FIELDS }), publicKnowledgeBasePath(["section", "category", "knowledgeBase"], { publicRowFields: PUBLIC_PUBLISHED_ARTICLE_FIELDS }), ], }), KnowledgeBaseRelatedArticle: ownership({ allOf: [ publicKnowledgeBasePath(["article", "knowledgeBase"], { publicPathFields: Object.freeze({ KnowledgeBaseArticle: PUBLIC_PUBLISHED_ARTICLE_FIELDS }), }), publicKnowledgeBasePath(["relatedArticle", "knowledgeBase"], { publicPathFields: Object.freeze({ KnowledgeBaseArticle: PUBLIC_PUBLISHED_ARTICLE_FIELDS }), }), ], }), KnowledgeBaseViews: ownership({ allOf: [publicKnowledgeBasePath(["knowledgeBase"], { publicWriteGlobal: true })] }), KnowledgeBaseArticleViews: ownership({ allOf: [ publicKnowledgeBasePath(["knowledgeBaseArticle", "knowledgeBase"], { publicWriteGlobal: true, publicPathFields: Object.freeze({ KnowledgeBaseArticle: PUBLIC_PUBLISHED_ARTICLE_FIELDS }), }), ], }), KnowledgeBaseArticleUpvotes: ownership({ allOf: [ publicKnowledgeBasePath(["knowledgeBaseArticle", "knowledgeBase"], { publicWriteGlobal: true, publicPathFields: Object.freeze({ KnowledgeBaseArticle: PUBLIC_PUBLISHED_ARTICLE_FIELDS }), }), ], }), KnowledgeBaseArticleDownvotes: ownership({ allOf: [ publicKnowledgeBasePath(["knowledgeBaseArticle", "knowledgeBase"], { publicWriteGlobal: true, publicPathFields: Object.freeze({ KnowledgeBaseArticle: PUBLIC_PUBLISHED_ARTICLE_FIELDS }), }), ], }), OnboardingSessionAction: ownership({ allOf: [ownershipPath(["onboardingSession"])], identityAnyOf: [ownershipPath(["onboardingSession", "user"])], }), OnboardingSessionFilterMatch: ownership({ allOf: [ownershipPath(["onboardingSession"])], identityAnyOf: [ownershipPath(["onboardingSession", "user"])], }), OnboardingSessionStep: ownership({ allOf: [ownershipPath(["onboardingSession"])], identityAnyOf: [ownershipPath(["onboardingSession", "user"])], }), RolePermission: ownership({ readGlobal: true, allOf: [ownershipPath(["role"], { operatorWriteGlobal: true })], risk: "Only authenticated platform operators may mutate permissions on global roles; tenant-role permissions remain tenant-bound", }), GroupUser: ownership({ allOf: [ownershipPath(["group"])] }), PluginUserConfig: ownership({ allOf: [ownershipPath(["plugin"])] }), PortalPage: ownership({ allOf: [ownershipPath(["portal"])] }), TenantSubscriptionProduct: ownership({ allOf: [ownershipPath(["tenantSubscription"])] }), TenantSubscriptionProductPrice: ownership({ allOf: [ownershipPath(["tenantSubscriptionProduct", "tenantSubscription"])], }), WorkflowBlock: ownership({ allOf: [workflowDefinitionPath(["workflow"])] }), WorkflowBlockConditionGroup: ownership({ allOf: [workflowDefinitionPath(["workflowBlock", "workflow"])], }), WorkflowBlockCondition: ownership({ allOf: [workflowDefinitionPath(["workflowBlockConditionGroup", "workflowBlock", "workflow"])], }), WorkflowBlockToBlock: ownership({ allOf: [workflowDefinitionPath(["fromBlock", "workflow"]), workflowDefinitionPath(["toBlock", "workflow"])], }), WorkflowInputExample: ownership({ allOf: [workflowDefinitionPath(["workflow"])] }), WorkflowBlockExecution: ownership({ allOf: [ ownershipPath(["workflowExecution"], { workerReadGlobal: true, workerWriteGlobal: true }), workflowDefinitionPath(["workflowBlock", "workflow"], { allowGlobalWrite: true, globalWriteFields: WORKFLOW_GLOBAL_READ_FIELDS, workerWriteGlobal: true, }), ], optionalAllOf: [ workflowDefinitionPath(["fromWorkflowBlock", "workflow"], { allowGlobalWrite: true, globalWriteFields: WORKFLOW_GLOBAL_READ_FIELDS, workerWriteGlobal: true, }), ], }), }); export const TENANT_ROOT_POLICY_CONTRACT = Object.freeze({ Tenant: Object.freeze({ tenantContext: "app.tenant_id", userContext: "app.user_id", membershipModel: "TenantUser", tenantField: "tenantId", userField: "userId", }), }); /** * Tenant tables that have one reviewed cross-tenant worker operation. The * runtime worker role remains explicit so ordinary app traffic still requires * app.tenant_id and new exceptions cannot appear through inference. */ export const DIRECT_WORKER_POLICY_CONTRACT = Object.freeze({ KwpApiContractSnapshot: Object.freeze({ operatorReadAllTenants: true, risk: "Authenticated operators can inspect redacted KWP contract evidence across tenants; adapter snapshots remain tenant-bound for writes", }), KwpCapabilityState: Object.freeze({ operatorReadAllTenants: true, risk: "Authenticated operators can inspect paused KWP capabilities across tenants; approval and capability writes remain tenant-bound", }), KwpErrorReport: Object.freeze({ operatorReadAllTenants: true, risk: "Authenticated operators can inspect redacted KWP drift alarms across tenants; resolution writes remain tenant-bound", }), PluginCapabilityUse: Object.freeze({ readAllTenants: true, writeAllTenants: true, risk: "The nightly plugin capability retention worker scans and deletes expired rows across every tenant", }), }); /** * Cross-module references deliberately remain bare scalars under AD-21. These * reviewed predicates give security-critical references the same tenant-safe * write guarantee as an in-schema Prisma relation without duplicating shared * back-relations or provider credentials. */ export const DIRECT_SCALAR_TENANT_REFERENCE_CONTRACT = Object.freeze({ "KwpApiContractSnapshot.dataConnectionId": Object.freeze({ targetModel: "DataConnection", targetField: "id", targetWhere: Object.freeze({ appId: "kwp" }), risk: "A KWP contract snapshot may reference only a KWP DataConnection owned by the same tenant", }), "KwpCapabilityState.dataConnectionId": Object.freeze({ targetModel: "DataConnection", targetField: "id", targetWhere: Object.freeze({ appId: "kwp" }), risk: "A KWP capability state may reference only a KWP DataConnection owned by the same tenant", }), "KwpErrorReport.dataConnectionId": Object.freeze({ targetModel: "DataConnection", targetField: "id", targetWhere: Object.freeze({ appId: "kwp" }), risk: "A KWP error report may reference only a KWP DataConnection owned by the same tenant", }), "KwpProjectRouting.dataConnectionId": Object.freeze({ targetModel: "DataConnection", targetField: "id", targetWhere: Object.freeze({ appId: "kwp" }), risk: "A KWP project route may reference only a KWP DataConnection owned by the same tenant", }), "KwpProjectRouting.pipelineId": Object.freeze({ targetModel: "Pipeline", targetField: "id", risk: "A KWP project route may reference only a Pipeline owned by the same tenant", }), "KwpProjectRouting.stageId": Object.freeze({ targetModel: "PipelineStage", targetField: "id", risk: "A KWP project route may reference only a PipelineStage owned by the same tenant", }), "KwpProjectCatalogState.dataConnectionId": Object.freeze({ targetModel: "DataConnection", targetField: "id", targetWhere: Object.freeze({ appId: "kwp" }), risk: "A KWP project catalog state may reference only a KWP DataConnection owned by the same tenant", }), "KwpProjectCatalogItem.dataConnectionId": Object.freeze({ targetModel: "DataConnection", targetField: "id", targetWhere: Object.freeze({ appId: "kwp" }), risk: "A cached KWP project may reference only a KWP DataConnection owned by the same tenant", }), "KwpMaterialPosition.dataConnectionId": Object.freeze({ targetModel: "DataConnection", targetField: "id", targetWhere: Object.freeze({ appId: "kwp" }), risk: "A KWP material position may reference only a KWP DataConnection owned by the same tenant", }), "KwpMaterialPosition.projektId": Object.freeze({ targetModel: "Projekt", targetField: "id", risk: "A KWP material position may reference only a project owned by the same tenant", }), "TelephonyConnection.dataConnectionId": Object.freeze({ targetModel: "DataConnection", targetField: "id", targetWhere: Object.freeze({ appId: Object.freeze({ oneOf: Object.freeze(["aircall", "hallopetra"]) }) }), risk: "A telephony extension may reference only a supported telephony DataConnection owned by the same tenant", }), "TelephonyUserBinding.tenantUserId": Object.freeze({ targetModel: "TenantUser", targetField: "id", risk: "An Aircall user binding may reference only a TenantUser membership owned by the same tenant", }), "TelephonyCallSession.tenantUserId": Object.freeze({ targetModel: "TenantUser", targetField: "id", optional: true, risk: "An Aircall call may reference only a TenantUser membership owned by the same tenant", }), "TelephonyCallSession.manualOverrideUserId": Object.freeze({ targetModel: "TenantUser", targetField: "userId", optional: true, risk: "A manual Aircall match override may be attributed only to a user who belongs to the same tenant", }), "TelephonyCallSession.matchedKontaktId": Object.freeze({ targetModel: "Kontakt", targetField: "id", optional: true, risk: "An Aircall call may match only a Kontakt owned by the same tenant", }), "TelephonyCallSession.matchedLeadId": Object.freeze({ targetModel: "InboxLead", targetField: "id", optional: true, risk: "An Aircall call may match only an InboxLead owned by the same tenant", }), "TelephonyCallSession.matchedProjektId": Object.freeze({ targetModel: "Projekt", targetField: "id", optional: true, risk: "An Aircall call may match only a Projekt owned by the same tenant", }), "TeamChat.projektId": Object.freeze({ targetModel: "Projekt", targetField: "id", optional: true, risk: "A project channel may reference only a Projekt owned by the same tenant", }), "TeamChat.createdByUserId": Object.freeze({ targetModel: "TenantUser", targetField: "userId", optional: true, risk: "A chat channel creator must belong to the same tenant", }), "TeamChatGroupSource.groupId": Object.freeze({ targetModel: "Group", targetField: "id", requireTenantOwnedTarget: true, risk: "A synced chat group source may reference only a permission group owned by the same tenant", }), "TeamChatMember.userId": Object.freeze({ targetModel: "TenantUser", targetField: "userId", risk: "A chat membership may include only a user who belongs to the same tenant", }), "TeamChatMember.joinedViaUserId": Object.freeze({ targetModel: "TenantUser", targetField: "userId", optional: true, risk: "A chat invitation may be attributed only to a user who belongs to the same tenant", }), "TeamChatMessage.authorUserId": Object.freeze({ targetModel: "TenantUser", targetField: "userId", optional: true, risk: "A chat message author must belong to the same tenant", }), "TeamChatMessage.deletedByUserId": Object.freeze({ targetModel: "TenantUser", targetField: "userId", optional: true, risk: "A chat message deletion may be attributed only to a user who belongs to the same tenant", }), "TeamChatThread.createdByUserId": Object.freeze({ targetModel: "TenantUser", targetField: "userId", risk: "A chat thread creator must belong to the same tenant", }), "TeamChatPinnedMessage.pinnedByUserId": Object.freeze({ targetModel: "TenantUser", targetField: "userId", risk: "A chat pin may be attributed only to a user who belongs to the same tenant", }), "TeamChatReaction.userId": Object.freeze({ targetModel: "TenantUser", targetField: "userId", risk: "A chat reaction may be attributed only to a user who belongs to the same tenant", }), "TeamChatRead.userId": Object.freeze({ targetModel: "TenantUser", targetField: "userId", risk: "A chat read receipt may be attributed only to a user who belongs to the same tenant", }), "TeamChatEvent.actorUserId": Object.freeze({ targetModel: "TenantUser", targetField: "userId", optional: true, risk: "A durable chat event may be attributed only to a user who belongs to the same tenant", }), }); /** * Deliberately global tables stay readable by tenant runtimes, while catalog * mutations require an authenticated platform operator. This is RLS for * operator privilege separation, not tenant ownership. */ export const GLOBAL_GUARDED_MODEL_CONTRACT = Object.freeze({ App: Object.freeze({ workerRead: true }), Subprocessor: Object.freeze({ workerRead: true }), Onboarding: Object.freeze({ workerRead: true }), OnboardingFilter: Object.freeze({ workerRead: true }), OnboardingStep: Object.freeze({ workerRead: true }), Permission: Object.freeze({ workerRead: true }), SubscriptionProduct: Object.freeze({ workerRead: true }), SubscriptionPrice: Object.freeze({ workerRead: true }), SubscriptionUsageBasedPrice: Object.freeze({ workerRead: true }), SubscriptionUsageBasedTier: Object.freeze({ workerRead: true }), SubscriptionFeature: Object.freeze({ workerRead: true }), FeatureFlag: Object.freeze({ workerRead: true }), FeatureFlagFilter: Object.freeze({ workerRead: true }), FeatureFlagAudit: Object.freeze({ workerRead: true }), }); /** * Reviewed non-catalog exceptions that need the same operator-only mutation * boundary. Keeping this list separate makes omissions and accidental additions * to the guarded contract fail generation. */ export const GLOBAL_GUARDED_EXTRA_MODELS = Object.freeze(["FeatureFlag", "FeatureFlagFilter", "FeatureFlagAudit"]); function globalSharedPolicy(commands, options = {}) { return Object.freeze({ commands: Object.freeze(commands), status: options.status ?? "reviewed", ...(options.risk ? { risk: options.risk } : {}), }); } const DENY_ALL_COMMANDS = Object.freeze({ select: "none", insert: "none", update: "none", delete: "none", }); /** * Every global-shared table needs a command-by-command runtime contract. There * is deliberately no default: a newly classified table or a removed entry * makes policy generation fail. Pending contracts deny every runtime command * until their bootstrap or identity-scoped access path has been reviewed. */ export const GLOBAL_SHARED_POLICY_CONTRACT = Object.freeze({ User: globalSharedPolicy( { select: "user-visible", insert: "current-user", update: "current-user", delete: "current-user", }, { risk: "Users are visible only to themselves, platform operators, and members of the active tenant; mutations remain self- or operator-only", } ), MagicLinkToken: globalSharedPolicy( { select: "user-owned", insert: "user-owned", update: "user-owned", delete: "user-owned", }, { risk: "Signed magic-link payloads bind app.user_id before the persisted token is read or consumed", } ), Registration: globalSharedPolicy( { select: "operator", insert: "operator", update: "operator", delete: "operator" }, { risk: "Public registration uses capability-scoped create and claim functions; direct table access is operator-only" } ), Blacklist: globalSharedPolicy( { select: "operator", insert: "operator", update: "operator", delete: "operator" }, { risk: "Runtime abuse protection uses exact-match capability functions; direct table access is operator-only" } ), AnalyticsSettings: globalSharedPolicy({ select: "runtime-read", insert: "operator", update: "operator", delete: "operator", }), UserSession: globalSharedPolicy( { select: "user-owned", insert: "user-owned", update: "user-owned", delete: "user-owned", }, { risk: "Opaque session hashes resolve only user and session ids before the complete row is read under app.user_id", } ), TrustedDevice: globalSharedPolicy( { select: "user-owned", insert: "user-owned", update: "user-owned", delete: "user-owned", }, { risk: "Trusted-device rows are constrained to app.user_id; opaque-cookie logout uses an id-only bootstrap resolver", } ), AppConfiguration: globalSharedPolicy({ select: "runtime-read", insert: "operator", update: "operator", delete: "operator", }), FileUploadProgress: globalSharedPolicy(DENY_ALL_COMMANDS, { risk: "Legacy global upload progress has no reviewed runtime consumer", }), FileChunk: globalSharedPolicy(DENY_ALL_COMMANDS, { risk: "Legacy global binary chunks have no reviewed runtime consumer", }), FileObject: globalSharedPolicy(DENY_ALL_COMMANDS, { risk: "Global storage metadata has no reviewed runtime consumer", }), IpAddress: globalSharedPolicy( { select: "operator", insert: "operator", update: "operator", delete: "operator" }, { risk: "Runtime IP reputation uses exact-match and upsert capability functions; direct table access is operator-only" } ), IpAddressLog: globalSharedPolicy( { select: "operator", insert: "operator", update: "operator", delete: "operator" }, { risk: "Runtime IP logs are append-only through a capability function; direct table access is operator-only" } ), Credential: globalSharedPolicy(DENY_ALL_COMMANDS, { risk: "Legacy plaintext global credentials have no reviewed runtime consumer", }), McpOAuthClient: globalSharedPolicy({ select: "active-or-operator", insert: "operator", update: "operator", delete: "operator", }), BillingWebhookLog: globalSharedPolicy({ select: "operator", insert: "none", update: "none", delete: "none", }), }); function platformPolicy(select, insert, update, deleteAccess, options = {}) { return Object.freeze({ commands: Object.freeze({ select, insert, update, delete: deleteAccess }), ...(options.updateCheck ? { updateCheck: options.updateCheck } : {}), ...(options.risk ? { risk: options.risk } : {}), }); } /** * Platform tables are not tenant catalogs. Each command explicitly declares * the only reviewed access shape, so they can never fall back to broad runtime * CRUD grants. */ export const PLATFORM_ADMIN_POLICY_CONTRACT = Object.freeze({ AdminSession: platformPolicy("operator", "operator", "operator", "operator", { risk: "Admin sessions are tenant-less, capped at eight hours and only reachable by an active operator", }), AdminRole: platformPolicy("operator", "operator", "operator", "operator"), AdminPermission: platformPolicy("operator", "operator", "operator", "operator"), AdminRolePermission: platformPolicy("operator", "operator", "operator", "operator"), AdminUserRole: platformPolicy("operator", "operator", "operator", "operator"), AdminDataConnection: platformPolicy( "operator-admin-user-or-worker", "operator-admin-user", "operator-admin-user-or-worker", "none", { risk: "Admin connections are tenant-less personal integrations; app access is bound to the active AdminUser and workers only process reviewed provider jobs", } ), AdminConnectionCredential: platformPolicy( "operator-admin-user-or-worker", "operator-admin-user", "operator-admin-user-or-worker", "none", { risk: "Credential envelopes are owner-bound and revoked in place; plaintext only exists inside the dedicated platform-envelope service boundary", } ), AdminCalendarConnection: platformPolicy( "operator-admin-user-or-worker", "operator-admin-user", "operator-admin-user-or-worker", "none", { risk: "Personal admin calendars remain owner-bound; workers may only advance sync health and provider cursors", } ), AdminCalendarSyncCursor: platformPolicy( "operator-admin-user-or-worker", "operator-admin-user-or-worker", "operator-admin-user-or-worker", "none", { risk: "Calendar cursors retain only provider tokens and anonymous busy intervals, never unrelated event contents", } ), AdminMeetingType: platformPolicy("operator", "operator-created-by", "operator", "none", { risk: "Meeting types are shared operator configuration and are archived rather than deleted so historical bookings remain reproducible", }), AdminAvailabilityRule: platformPolicy( "admin-communication-read", "admin-communication-write", "admin-communication-write", "none" ), AdminAvailabilityOverride: platformPolicy( "admin-communication-read", "admin-communication-write", "admin-communication-write", "none" ), AdminBookingPage: platformPolicy("operator", "operator-created-by", "operator", "none", { risk: "Published admin booking pages are resolved through a narrow public capability and remain operator-owned configuration", }), AdminBooking: platformPolicy( "admin-communication-read-or-worker", "operator-or-worker", "admin-communication-write-or-worker", "none", { risk: "Admin bookings are tenant-less sales records; public creation binds the published page owner and provider jobs use the bounded worker role", } ), AdminBookingParticipant: platformPolicy( "admin-communication-read-or-worker", "operator-or-worker", "admin-communication-write-or-worker", "none", { risk: "Public round-robin booking binds the page owner before host selection; inserts are therefore permitted to an active operator while reads and updates remain host-bound", } ), AdminBookingAssignment: platformPolicy( "admin-communication-read-or-worker", "operator-or-worker", "none", "none", { risk: "Round-robin assignment evidence is append-only; public inserts bind the active page owner and record only eligible host ids plus minimized exclusion reasons", } ), AdminBookingReminder: platformPolicy( "admin-communication-read-or-worker", "operator-or-worker", "admin-communication-write-or-worker", "none", { risk: "Public round-robin booking creates minimized reminder metadata after host selection while later reads and updates remain host- or worker-bound", } ), AdminMailbox: platformPolicy("admin-communication-read-or-worker", "admin-communication-write", "admin-communication-write-or-worker", "none"), AdminMailboxSyncCursor: platformPolicy("admin-communication-read-or-worker", "admin-communication-write", "admin-communication-write-or-worker", "none"), AdminMailboxWebhookEvent: platformPolicy("admin-communication-read-or-worker", "admin-communication-write-or-worker", "admin-communication-write-or-worker", "none"), AdminEmailThread: platformPolicy("admin-communication-read-or-worker", "admin-communication-write-or-worker", "admin-communication-write-or-worker", "none"), AdminEmailMessage: platformPolicy("admin-communication-read-or-worker", "admin-communication-write-or-worker", "admin-communication-write-or-worker", "none"), AdminEmailParticipant: platformPolicy("admin-communication-read-or-worker", "admin-communication-write-or-worker", "admin-communication-write-or-worker", "none"), AdminEmailAttachment: platformPolicy("admin-communication-read-or-worker", "admin-communication-write-or-worker", "admin-communication-write-or-worker", "none"), AdminEmailEvent: platformPolicy("admin-communication-read-or-worker", "admin-communication-write-or-worker", "admin-communication-write-or-worker", "none"), AdminEmailLink: platformPolicy("admin-communication-read-or-worker", "admin-communication-write-or-worker", "admin-communication-write-or-worker", "none"), AdminEmailTemplate: platformPolicy("admin-communication-read-or-worker", "admin-communication-write", "admin-communication-write-or-worker", "none"), AdminEmailSnippet: platformPolicy("admin-communication-read-or-worker", "admin-communication-write", "admin-communication-write-or-worker", "none"), AdminEmailSignature: platformPolicy("admin-communication-read-or-worker", "admin-communication-write", "admin-communication-write-or-worker", "none"), AdminEmailOutboundPolicy: platformPolicy("admin-communication-read-or-worker", "admin-communication-write", "admin-communication-write-or-worker", "none"), AdminScheduledEmail: platformPolicy("admin-communication-read-or-worker", "admin-communication-write", "admin-communication-write-or-worker", "none"), AdminNoReplyReminder: platformPolicy("admin-communication-read-or-worker", "admin-communication-write-or-worker", "admin-communication-write-or-worker", "none"), AdminBulkEmailRun: platformPolicy("admin-communication-read-or-worker", "admin-communication-write", "admin-communication-write-or-worker", "none"), AdminSendingDomain: platformPolicy("admin-communication-read-or-worker", "admin-communication-write", "admin-communication-write-or-worker", "none"), AdminBccAddress: platformPolicy("admin-communication-read-or-worker", "admin-communication-write", "admin-communication-write-or-worker", "none"), AdminPhoneConnection: platformPolicy( "admin-communication-read-or-worker", "admin-communication-write", "admin-communication-write-or-worker", "none", { risk: "Aircall company bindings are personal, tenant-less connections; webhook workers may only advance the reviewed provider state", } ), AdminPhoneNumber: platformPolicy( "admin-communication-read-or-worker", "admin-communication-write-or-worker", "admin-communication-write-or-worker", "none" ), AdminTelephonyPolicy: platformPolicy( "admin-communication-read", "admin-communication-write", "admin-communication-write", "none", { risk: "Outbound and recording remain fail-closed until the owning operator explicitly configures consent, time and budget gates", } ), AdminCallDisposition: platformPolicy("operator", "operator", "operator", "none", { risk: "Disposition codes remain stable and rows are archived rather than deleted so historical call outcomes stay interpretable", }), AdminCallSession: platformPolicy( "admin-communication-read-or-worker", "admin-communication-write-or-worker", "admin-communication-write-or-worker", "none" ), AdminCallParticipant: platformPolicy( "admin-communication-read-or-worker", "admin-communication-write-or-worker", "none", "none" ), AdminCallEvent: platformPolicy( "admin-communication-read-or-worker", "admin-communication-write-or-worker", "none", "none", { risk: "Normalized provider events are append-only, deduplicated and contain no raw webhook token", } ), AdminCallMatchCandidate: platformPolicy( "admin-communication-read-or-worker", "admin-communication-write-or-worker", "none", "none" ), AdminCallRecording: platformPolicy( "admin-communication-read-or-worker", "admin-communication-write-or-worker", "admin-communication-write-or-worker", "none", { risk: "Recording metadata is owner-bound, encrypted, AV-gated and expired in place by a bounded worker", } ), AdminDialerList: platformPolicy( "admin-communication-read-or-worker", "admin-communication-write", "admin-communication-write-or-worker", "none" ), AdminDialerEntry: platformPolicy( "admin-communication-read-or-worker", "admin-communication-write", "admin-communication-write-or-worker", "none", { risk: "Dialer entries advance sequentially and remain blocked unless the owner policy permits outbound activity", } ), AdminOutboundCallRequest: platformPolicy( "admin-communication-read-or-worker", "admin-communication-write", "admin-communication-write-or-worker", "none", { risk: "Every click-to-call request is owner-bound and idempotent; only the bounded worker may claim and deliver pending provider actions", } ), AdminFeatureFlagOverride: platformPolicy("operator", "operator", "operator", "none", { risk: "Operator-managed rollout overrides may target any tenant but remain guarded by authenticated AdminRBAC and are retired by expiry rather than runtime deletion", }), AdminLead: platformPolicy("admin-sales-owned-read", "admin-sales-owned-write", "admin-sales-owned-write", "none", { risk: "Platform leads are archived, never hard-deleted through the runtime role", }), AdminLeadActivity: platformPolicy("admin-sales-lead-child-read", "admin-sales-lead-activity-write", "none", "none", { risk: "The platform lead timeline is append-only; current actions require the bound actor, while deterministic historical rows may remain system-attributed only on legacy imports", }), AdminLeadSource: platformPolicy("admin-sales-shared-read", "admin-sales-shared-write", "admin-sales-shared-write", "none", { risk: "Sources are disabled for rollback and attribution retention rather than deleted", }), AdminLeadSourceCredential: platformPolicy("admin-sales-shared-read", "admin-sales-shared-write", "admin-sales-shared-write", "none", { risk: "Only one-way source credential digests are persisted and credentials are revoked rather than deleted; S2S authentication uses a narrow capability rather than direct table reads", }), AdminCompany: platformPolicy("admin-sales-shared-read-or-worker", "admin-sales-shared-write-or-worker", "admin-sales-shared-write", "none", { risk: "Platform sales companies are archived rather than hard-deleted; the worker may read or create them only while materializing a validated contact import", }), AdminContact: platformPolicy("admin-sales-shared-read-or-worker", "admin-sales-shared-write-or-worker", "admin-sales-shared-write", "none", { risk: "Platform sales contacts are archived rather than hard-deleted; the worker may read or create them only while materializing validated imports and exports", }), AdminContactChannel: platformPolicy("admin-sales-shared-read", "admin-sales-shared-write", "admin-sales-shared-write", "none", { risk: "Contact channels remain operator-only PII and are archived rather than hard-deleted", }), AdminPipeline: platformPolicy("admin-sales-shared-read", "admin-sales-shared-write", "admin-sales-shared-write", "none", { risk: "Platform pipelines are retired rather than hard-deleted so historical deals remain reproducible", }), AdminPipelineStage: platformPolicy("admin-sales-shared-read", "admin-sales-shared-write", "admin-sales-shared-write", "none", { risk: "Pipeline stages are retired rather than hard-deleted so stage history remains reproducible", }), AdminStageRequiredField: platformPolicy("admin-sales-shared-read", "admin-sales-shared-write", "none", "admin-sales-shared-write", { risk: "Stage requirements are explicit configuration rows and may only be changed by authenticated operators", }), AdminDealLossReason: platformPolicy("admin-sales-shared-read", "admin-sales-shared-write", "admin-sales-shared-write", "none", { risk: "Loss reasons are retired rather than deleted so historical reporting remains stable", }), AdminDeal: platformPolicy("admin-sales-owned-read", "admin-sales-owned-write", "admin-sales-owned-write", "none", { risk: "Platform deals remain operator data even after an explicit tenant promotion", }), AdminDealContact: platformPolicy("admin-sales-deal-child-read", "admin-sales-deal-child-write", "admin-sales-deal-child-write", "admin-sales-deal-child-write", { risk: "Buying-center membership remains operator-only and is removed through the owning deal or contact lifecycle", }), AdminDealStageHistory: platformPolicy("admin-sales-deal-child-read", "admin-sales-deal-history-write", "none", "none", { risk: "Deal stage history is append-only and every transition is attributed to the bound active operator", }), AdminTaskRecurrence: platformPolicy("admin-sales-owned-read-or-worker", "admin-sales-owned-write-or-worker", "admin-sales-owned-write-or-worker", "none", { risk: "Task recurrence rules remain tenant-less operator data; the worker may only materialize their deterministic next occurrence", }), AdminTask: platformPolicy("admin-sales-owned-read-or-worker", "admin-sales-owned-write-or-worker", "admin-sales-owned-write-or-worker", "none", { risk: "Admin sales tasks remain tenant-less operator data and the worker needs bounded access for reminders and recurring occurrences", }), AdminTag: platformPolicy("admin-sales-shared-read-or-worker", "admin-sales-shared-write", "admin-sales-shared-write", "none", { risk: "Admin sales tags are retired rather than deleted; the worker receives read-only access to resolve reviewed CSV classifications", }), AdminContactTag: platformPolicy("admin-sales-shared-read-or-worker", "operator-created-by-or-worker", "admin-sales-shared-write", "admin-sales-shared-write", { risk: "Contact-tag membership is mutable operator-owned classification; the worker may create actor-attributed rows for validated imports", }), AdminCustomFieldDefinition: platformPolicy("admin-sales-shared-read", "admin-sales-shared-write", "admin-sales-shared-write", "none", { risk: "Typed custom field definitions are retired rather than deleted so historical values remain interpretable", }), AdminCustomFieldValue: platformPolicy("admin-sales-custom-value-read", "admin-sales-custom-value-write", "admin-sales-custom-value-write", "admin-sales-custom-value-write", { risk: "Typed custom values are entity-bound operator data; deletion represents an explicit cleared value", }), AdminContactNote: platformPolicy("admin-sales-shared-read", "operator-created-by", "none", "none", { risk: "Contact notes are immutable PII-bearing timeline records attributed to the bound active operator", }), AdminImportJob: platformPolicy("operator-or-worker", "operator-requested-by-or-worker", "operator-or-worker", "none", { risk: "Contact imports are operator-requested jobs; the worker may only advance their validated processing state", }), AdminImportRowError: platformPolicy("operator-or-worker", "worker", "none", "none", { risk: "Import row errors are immutable worker-produced validation evidence visible only to active operators", }), AdminExportJob: platformPolicy("operator-or-worker", "operator-requested-by-or-worker", "operator-or-worker", "none", { risk: "Contact exports are operator-requested jobs; the worker may only materialize their expiring artifact", }), AdminActivity: platformPolicy("admin-sales-activity-read", "admin-sales-activity-write-or-worker", "none", "none", { risk: "The shared platform sales timeline is append-only; operator writes are actor-bound and worker writes are limited to deterministic background contracts", }), AdminLeadAssignmentRule: platformPolicy("admin-sales-shared-read", "admin-sales-shared-write", "admin-sales-shared-write", "none", { risk: "Assignment rules and round-robin cursors are operator-managed platform configuration and are archived rather than deleted", }), AdminLeadScoreRule: platformPolicy("admin-sales-shared-read", "admin-sales-shared-write", "admin-sales-shared-write", "none", { risk: "Lead score rules are versioned operator configuration and are archived rather than deleted", }), AdminLeadQualification: platformPolicy("admin-sales-lead-child-read", "admin-sales-lead-child-write", "admin-sales-lead-child-write", "none", { risk: "Lead qualification and provider-neutral enrichment snapshots are operator-only sales data", }), AdminDuplicateCandidate: platformPolicy("admin-sales-paired-lead-read", "admin-sales-paired-lead-write", "admin-sales-paired-lead-write", "none", { risk: "Duplicate candidates retain their resolution history and are never hard-deleted through the runtime role", }), AdminMergeRecord: platformPolicy("admin-sales-merged-lead-read", "admin-sales-merge-record-write", "none", "none", { risk: "Lead merge records are append-only and every merge is attributed to the bound active operator", }), AdminTenantNote: platformPolicy("operator-tenant", "operator-tenant", "operator-tenant", "operator-tenant"), Feedback: platformPolicy( "tenant-or-identity-or-operator", "scoped-or-anonymous-or-operator", "tenant-or-identity-or-operator", "tenant-or-identity-or-operator", { updateCheck: "tenant-member-or-pretenant-identity-or-operator", risk: "Updates keep tenantless rows identity-owned and require tenant-bound target users to belong to the active tenant", } ), ImpersonationAudit: platformPolicy("operator", "operator", "operator", "operator"), Lead: platformPolicy("operator", "none", "none", "none", { risk: "R-LEADS keeps the legacy platform lead table read-only only for rollback and historical reporting", }), LeadEvent: platformPolicy("operator", "none", "none", "none", { risk: "R-LEADS keeps the legacy lead event timeline read-only only for rollback and historical reporting", }), MarketingIntegration: platformPolicy("operator-or-worker", "operator", "operator-or-worker", "operator"), QueueFailedJob: platformPolicy("operator-or-worker", "worker", "worker", "operator-or-worker"), SupportTicket: platformPolicy( "tenant-or-identity-or-operator", "scoped-or-anonymous-or-operator", "tenant-or-identity-or-operator", "tenant-or-identity-or-operator", { updateCheck: "tenant-member-or-pretenant-identity-or-operator", risk: "Updates keep tenantless rows identity-owned and require tenant-bound target users to belong to the active tenant", } ), SupportTicketMessage: platformPolicy( "public-ticket-tenant-or-operator", "public-ticket-tenant-or-operator", "public-ticket-tenant-or-operator", "public-ticket-tenant-or-operator" ), TenantAcquisition: platformPolicy("operator-or-worker", "operator-or-worker", "operator-or-worker", "operator-or-worker"), }); function tenantResolver(parameters, query, options = {}) { return Object.freeze({ parameters: Object.freeze(parameters.map((parameter) => Object.freeze(parameter))), query, ...(options.readModels ? { readModels: Object.freeze(options.readModels) } : {}), }); } /** * Narrow bootstrap resolvers return only the tenant boundary and opaque ids. * Full eligibility and authorization always run again under app.tenant_id. */ export const TENANT_RESOLVER_CONTRACT = Object.freeze({ hivegrid_resolve_admin_sso_identity_v2: tenantResolver( [{ name: "p_subject", type: "text" }], ` SELECT NULL::text AS tenant_id, admin_row."id"::text AS resource_id, admin_row."id"::text AS user_id FROM public."AdminUser" AS admin_row WHERE NULLIF(trim(p_subject), '') IS NOT NULL AND admin_row."authentikSubject" = trim(p_subject) AND admin_row."status" = 'active' LIMIT 1` ), hivegrid_resolve_admin_session_identity: tenantResolver( [{ name: "p_token_hash", type: "text" }], ` SELECT NULL::text AS tenant_id, session_row."id"::text AS resource_id, session_row."adminUserId"::text AS user_id FROM public."AdminSession" AS session_row JOIN public."AdminUser" AS admin_row ON admin_row."id" = session_row."adminUserId" WHERE session_row."tokenHash" = p_token_hash AND session_row."revokedAt" IS NULL AND session_row."expiresAt" > clock_timestamp() AND admin_row."status" = 'active' LIMIT 1` ), hivegrid_resolve_user_email: tenantResolver( [{ name: "p_email", type: "text" }], ` WITH matches AS MATERIALIZED ( SELECT user_row."id"::text AS id FROM public."User" AS user_row WHERE NULLIF(trim(p_email), '') IS NOT NULL AND lower(trim(user_row."email")) = lower(trim(p_email)) ORDER BY user_row."id" LIMIT 2 ) SELECT NULL::text AS tenant_id, min(matches.id)::text AS resource_id, min(matches.id)::text AS user_id FROM matches HAVING count(*) = 1` ), hivegrid_resolve_user_session: tenantResolver( [{ name: "p_token_hash", type: "text" }], ` SELECT NULL::text AS tenant_id, session_row."id"::text AS resource_id, session_row."userId"::text AS user_id FROM public."UserSession" AS session_row WHERE session_row."tokenHash" = p_token_hash AND session_row."revokedAt" IS NULL AND session_row."expiresAt" > CURRENT_TIMESTAMP LIMIT 1` ), hivegrid_resolve_trusted_device: tenantResolver( [{ name: "p_token_hash", type: "text" }], ` SELECT NULL::text AS tenant_id, device_row."id"::text AS resource_id, device_row."userId"::text AS user_id FROM public."TrustedDevice" AS device_row WHERE device_row."tokenHash" = p_token_hash AND device_row."revokedAt" IS NULL AND device_row."expiresAt" > CURRENT_TIMESTAMP LIMIT 1` ), hivegrid_resolve_public_form_key: tenantResolver( [{ name: "p_key", type: "text" }], ` SELECT form_row."tenantId"::text AS tenant_id, form_row."id"::text AS resource_id, NULL::text AS user_id FROM public."Form" AS form_row WHERE form_row."key" = p_key AND form_row."isEnabled" = true LIMIT 1` ), hivegrid_resolve_public_form_slug: tenantResolver( [ { name: "p_tenant_slug", type: "text" }, { name: "p_form_slug", type: "text" }, ], ` SELECT tenant_row."id"::text AS tenant_id, form_row."id"::text AS resource_id, NULL::text AS user_id FROM public."Tenant" AS tenant_row JOIN public."Form" AS form_row ON form_row."tenantId" = tenant_row."id" WHERE tenant_row."slug" = p_tenant_slug AND tenant_row."active" = true AND form_row."slug" = p_form_slug AND form_row."isEnabled" = true AND form_row."isPublic" = true AND form_row."status" = 'published' LIMIT 1` ), hivegrid_resolve_public_booking_page: tenantResolver( [ { name: "p_tenant_slug", type: "text" }, { name: "p_page_slug", type: "text" }, ], ` SELECT tenant_row."id"::text AS tenant_id, page_row."id"::text AS resource_id, NULL::text AS user_id FROM public."Tenant" AS tenant_row JOIN public."BookingPage" AS page_row ON page_row."tenantId" = tenant_row."id" WHERE tenant_row."slug" = p_tenant_slug AND tenant_row."active" = true AND page_row."slug" = p_page_slug AND page_row."isPublished" = true AND page_row."archivedAt" IS NULL LIMIT 1` ), hivegrid_resolve_admin_booking_page: tenantResolver( [{ name: "p_page_slug", type: "text" }], ` SELECT NULL::text AS tenant_id, page_row."id"::text AS resource_id, page_row."createdByAdminUserId"::text AS user_id FROM public."AdminBookingPage" AS page_row JOIN public."AdminUser" AS admin_row ON admin_row."id" = page_row."createdByAdminUserId" JOIN public."AdminMeetingType" AS meeting_type ON meeting_type."id" = page_row."meetingTypeId" WHERE NULLIF(trim(p_page_slug), '') IS NOT NULL AND page_row."slug" = lower(trim(p_page_slug)) AND page_row."published" = true AND page_row."archivedAt" IS NULL AND meeting_type."active" = true AND meeting_type."archivedAt" IS NULL AND admin_row."status" = 'active' LIMIT 1`, { readModels: ["AdminBookingPage", "AdminMeetingType", "AdminUser"], } ), hivegrid_resolve_calendar_webhook: tenantResolver( [ { name: "p_channel_id", type: "text" }, { name: "p_channel_token", type: "text" }, ], ` SELECT connection_row."tenantId"::text AS tenant_id, connection_row."id"::text AS resource_id, connection_row."userId"::text AS user_id FROM public."CalendarConnection" AS connection_row WHERE connection_row."provider" = 'google' AND connection_row."status" = 'active' AND connection_row."archivedAt" IS NULL AND connection_row."webhookSubscriptionId" = p_channel_id AND connection_row."id" = p_channel_token` ), hivegrid_resolve_aircall_webhook: tenantResolver( [{ name: "p_token_hash", type: "text" }], ` SELECT connection_row."tenantId"::text AS tenant_id, connection_row."id"::text AS resource_id, NULL::text AS user_id FROM public."TelephonyConnection" AS connection_row JOIN public."DataConnection" AS data_connection ON data_connection."id" = connection_row."dataConnectionId" AND data_connection."tenantId" = connection_row."tenantId" WHERE p_token_hash IS NOT NULL AND connection_row."provider" = 'aircall' AND connection_row."webhookTokenHash" = p_token_hash AND data_connection."appId" = 'aircall' AND data_connection."connectionStatus" IN ('active', 'degraded') AND data_connection."archivedAt" IS NULL LIMIT 1`, { readModels: ["TelephonyConnection", "DataConnection"] } ), hivegrid_resolve_hallopetra_webhook: tenantResolver( [{ name: "p_token_hash", type: "text" }], ` SELECT connection_row."tenantId"::text AS tenant_id, connection_row."id"::text AS resource_id, NULL::text AS user_id FROM public."TelephonyConnection" AS connection_row JOIN public."DataConnection" AS data_connection ON data_connection."id" = connection_row."dataConnectionId" AND data_connection."tenantId" = connection_row."tenantId" WHERE p_token_hash IS NOT NULL AND connection_row."provider" = 'hallopetra' AND connection_row."webhookTokenHash" = p_token_hash AND data_connection."appId" = 'hallopetra' AND data_connection."connectionStatus" IN ('active', 'degraded') AND data_connection."archivedAt" IS NULL LIMIT 1`, { readModels: ["TelephonyConnection", "DataConnection"] } ), hivegrid_resolve_admin_aircall_webhook: tenantResolver( [{ name: "p_token_hash", type: "text" }], ` SELECT NULL::text AS tenant_id, phone_connection."id"::text AS resource_id, phone_connection."adminUserId"::text AS user_id FROM public."AdminPhoneConnection" AS phone_connection JOIN public."AdminDataConnection" AS data_connection ON data_connection."id" = phone_connection."connectionId" AND data_connection."adminUserId" = phone_connection."adminUserId" JOIN public."AdminUser" AS admin_row ON admin_row."id" = phone_connection."adminUserId" WHERE p_token_hash IS NOT NULL AND phone_connection."webhookTokenHash" = p_token_hash AND phone_connection."archivedAt" IS NULL AND data_connection."provider" = 'aircall' AND data_connection."capability" = 'telephony' AND data_connection."status" IN ('active', 'degraded') AND data_connection."archivedAt" IS NULL AND admin_row."status" = 'active' LIMIT 1`, { readModels: ["AdminPhoneConnection", "AdminDataConnection", "AdminUser"] } ), hivegrid_resolve_gmail_mailboxes: tenantResolver( [ { name: "p_provider", type: "text" }, { name: "p_email", type: "text" }, ], ` WITH eligible_matches AS MATERIALIZED ( SELECT mailbox_row."tenantId", mailbox_row."id", mailbox_row."ownerUserId" FROM public."EmailIntegrationMailbox" AS mailbox_row WHERE p_provider = 'gmail' AND mailbox_row."provider"::text = p_provider AND mailbox_row."status" = 'active' AND mailbox_row."archivedAt" IS NULL AND lower(btrim(mailbox_row."emailAddress")) = p_email ), bounded_matches AS ( SELECT count(*) AS match_count FROM eligible_matches HAVING count(*) BETWEEN 1 AND 25 ) SELECT matches."tenantId"::text AS tenant_id, matches."id"::text AS resource_id, matches."ownerUserId"::text AS user_id FROM eligible_matches AS matches CROSS JOIN bounded_matches ORDER BY matches."tenantId", matches."id"` ), hivegrid_resolve_microsoft_mailbox: tenantResolver( [ { name: "p_subscription_id", type: "text" }, { name: "p_client_state", type: "text" }, ], ` SELECT mailbox_row."tenantId"::text AS tenant_id, mailbox_row."id"::text AS resource_id, mailbox_row."ownerUserId"::text AS user_id FROM public."EmailIntegrationMailbox" AS mailbox_row WHERE mailbox_row."provider" = 'microsoft' AND mailbox_row."status" = 'active' AND mailbox_row."archivedAt" IS NULL AND mailbox_row."webhookSubscriptionId" = p_subscription_id AND mailbox_row."webhookClientState" = p_client_state` ), hivegrid_resolve_signature_signer: tenantResolver( [{ name: "p_access_token_hash", type: "text" }], ` SELECT signer_row."tenantId"::text AS tenant_id, signer_row."id"::text AS resource_id, NULL::text AS user_id FROM public."ProjektSignatureSigner" AS signer_row WHERE p_access_token_hash IS NOT NULL AND signer_row."accessTokenHash" = p_access_token_hash` ), hivegrid_resolve_outbound_email_click: tenantResolver( [{ name: "p_outbound_email_id", type: "text" }], ` SELECT email_row."tenantId"::text AS tenant_id, email_row."id"::text AS resource_id, NULL::text AS user_id FROM public."OutboundEmail" AS email_row WHERE email_row."id" = p_outbound_email_id AND email_row."tenantId" IS NOT NULL` ), hivegrid_resolve_outbound_email_open: tenantResolver( [ { name: "p_outbound_email_id", type: "text" }, { name: "p_tracking_token", type: "text" }, ], ` SELECT email_row."tenantId"::text AS tenant_id, email_row."id"::text AS resource_id, NULL::text AS user_id FROM public."OutboundEmail" AS email_row WHERE email_row."id" = p_outbound_email_id AND email_row."tenantId" IS NOT NULL AND email_row."trackingToken" = p_tracking_token` ), hivegrid_resolve_public_knowledge_base: tenantResolver( [{ name: "p_slug", type: "text", defaultSql: "NULL" }], ` SELECT NULL::text AS tenant_id, knowledge_base."id"::text AS resource_id, NULL::text AS user_id FROM public."KnowledgeBase" AS knowledge_base WHERE knowledge_base."tenantId" IS NULL AND knowledge_base."enabled" = true AND (p_slug IS NULL OR knowledge_base."slug" = p_slug) ORDER BY knowledge_base."id"` ), hivegrid_resolve_workspace_invite: tenantResolver( [{ name: "p_token_hash", type: "text" }], ` SELECT invitation_row."tenantId"::text AS tenant_id, invitation_row."id"::text AS resource_id, NULL::text AS user_id FROM public."TenantUserInvitation" AS invitation_row WHERE p_token_hash IS NOT NULL AND invitation_row."tokenHash" = p_token_hash AND invitation_row."expiresAt" IS NOT NULL AND invitation_row."expiresAt" > CURRENT_TIMESTAMP AND invitation_row."revokedAt" IS NULL AND ( ( invitation_row."status" = 'pending' AND invitation_row."pending" = true AND invitation_row."acceptedAt" IS NULL AND invitation_row."acceptedByUserId" IS NULL ) OR ( invitation_row."status" = 'accepted' AND invitation_row."pending" = false AND invitation_row."type" = 0 AND invitation_row."acceptedAt" IS NOT NULL AND invitation_row."acceptedByUserId" IS NOT NULL ) ) LIMIT 1` ), hivegrid_resolve_api_key: tenantResolver( [ { name: "p_key_hash", type: "text" }, { name: "p_plaintext", type: "text", defaultSql: "NULL" }, ], ` SELECT key_row."tenantId"::text AS tenant_id, key_row."id"::text AS resource_id, key_row."createdByUserId"::text AS user_id FROM public."ApiKey" AS key_row WHERE key_row."keyHash" = p_key_hash OR (p_plaintext IS NOT NULL AND key_row."key" = p_plaintext) ORDER BY CASE WHEN key_row."keyHash" = p_key_hash THEN 0 ELSE 1 END, key_row."id" LIMIT 1` ), hivegrid_resolve_public_webhook: tenantResolver( [ { name: "p_tenant", type: "text" }, { name: "p_slug", type: "text" }, ], ` WITH selected_tenant AS ( SELECT tenant_row."id" FROM public."Tenant" AS tenant_row WHERE (tenant_row."id" = p_tenant OR tenant_row."slug" = p_tenant) AND tenant_row."active" = true ORDER BY CASE WHEN tenant_row."id" = p_tenant THEN 0 ELSE 1 END, tenant_row."id" LIMIT 1 ) SELECT tenant_row."id"::text AS tenant_id, endpoint_row."id"::text AS resource_id, NULL::text AS user_id FROM selected_tenant AS tenant_row JOIN public."PublicIncomingWebhookEndpoint" AS endpoint_row ON endpoint_row."tenantId" = tenant_row."id" WHERE endpoint_row."slug" = p_slug AND endpoint_row."archivedAt" IS NULL AND endpoint_row."status" = 'active' LIMIT 1` ), hivegrid_resolve_mcp_oauth_access_token: tenantResolver( [{ name: "p_token_hash", type: "text" }], ` SELECT token_row."tenantId"::text AS tenant_id, token_row."id"::text AS resource_id, token_row."userId"::text AS user_id FROM public."McpOAuthAccessToken" AS token_row WHERE token_row."tokenHash" = p_token_hash LIMIT 1` ), hivegrid_resolve_mcp_oauth_refresh_token: tenantResolver( [{ name: "p_token_hash", type: "text" }], ` SELECT token_row."tenantId"::text AS tenant_id, token_row."id"::text AS resource_id, token_row."userId"::text AS user_id FROM public."McpOAuthRefreshToken" AS token_row WHERE token_row."tokenHash" = p_token_hash LIMIT 1` ), hivegrid_resolve_mcp_oauth_authorization_code: tenantResolver( [{ name: "p_token_hash", type: "text" }], ` SELECT code_row."tenantId"::text AS tenant_id, code_row."id"::text AS resource_id, code_row."userId"::text AS user_id FROM public."McpOAuthAuthorizationCode" AS code_row WHERE code_row."codeHash" = p_token_hash LIMIT 1` ), hivegrid_resolve_tenant_inbound_address: tenantResolver( [{ name: "p_addresses", type: "text[]" }], ` WITH eligible_matches AS MATERIALIZED ( SELECT address_row."tenantId", address_row."id" FROM public."TenantInboundAddress" AS address_row WHERE address_row."archivedAt" IS NULL AND ( address_row."address" = ANY (p_addresses) OR address_row."fullAddress" = ANY (p_addresses) ) ), single_tenant AS ( SELECT min(matches."tenantId") AS tenant_id FROM eligible_matches AS matches HAVING count(DISTINCT matches."tenantId") = 1 ) SELECT matches."tenantId"::text AS tenant_id, matches."id"::text AS resource_id, NULL::text AS user_id FROM eligible_matches AS matches JOIN single_tenant ON single_tenant.tenant_id = matches."tenantId" ORDER BY matches."id" LIMIT 1` ), hivegrid_resolve_email_sequence_provider_message: tenantResolver( [{ name: "p_provider_message_id", type: "text" }], ` WITH eligible_matches AS MATERIALIZED ( SELECT run_row."tenantId", delivery_row."id" FROM public."EmailSequenceStepDelivery" AS delivery_row JOIN public."EmailSequenceRun" AS run_row ON run_row."id" = delivery_row."runId" WHERE delivery_row."providerMessageId" = p_provider_message_id AND run_row."tenantId" IS NOT NULL ), single_tenant AS ( SELECT min(matches."tenantId") AS tenant_id FROM eligible_matches AS matches HAVING count(DISTINCT matches."tenantId") = 1 ) SELECT matches."tenantId"::text AS tenant_id, matches."id"::text AS resource_id, NULL::text AS user_id FROM eligible_matches AS matches JOIN single_tenant ON single_tenant.tenant_id = matches."tenantId" ORDER BY matches."id" LIMIT 1` ), hivegrid_resolve_event_webhook_attempt: tenantResolver( [{ name: "p_attempt_id", type: "text" }], ` SELECT event_row."tenantId"::text AS tenant_id, attempt_row."id"::text AS resource_id, NULL::text AS user_id FROM public."EventWebhookAttempt" AS attempt_row JOIN public."Event" AS event_row ON event_row."id" = attempt_row."eventId" WHERE attempt_row."id" = p_attempt_id AND event_row."tenantId" IS NOT NULL LIMIT 1` ), hivegrid_resolve_email_sequence_delivery: tenantResolver( [{ name: "p_delivery_id", type: "text" }], ` SELECT run_row."tenantId"::text AS tenant_id, delivery_row."id"::text AS resource_id, NULL::text AS user_id FROM public."EmailSequenceStepDelivery" AS delivery_row JOIN public."EmailSequenceRun" AS run_row ON run_row."id" = delivery_row."runId" WHERE delivery_row."id" = p_delivery_id AND run_row."tenantId" IS NOT NULL LIMIT 1` ), }); /** * Direct tenant rows may only reference a global parent for these reviewed * product semantics. Every other tenant-bound FK must resolve inside the * active tenant, even when the parent model has a nullable tenantId. */ export const DIRECT_RELATION_GLOBAL_PARENT_CONTRACT = Object.freeze({ "EmailSequenceRun.sequence": Object.freeze({ read: true, write: true }), "UserRole.role": Object.freeze({ read: true, write: true }), "WorkflowExecution.workflow": Object.freeze({ read: true, write: true }), "WorkflowExecution.waitingBlock": Object.freeze({ read: true, write: true }), });