@openlup/platform 0.0.0 → 0.16.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +59 -0
- package/LICENSE +204 -0
- package/README.md +471 -1
- package/dist/bff/dispatch.d.ts +27 -0
- package/dist/bff/dispatch.js +47 -0
- package/dist/bff/envelope.d.ts +46 -0
- package/dist/bff/envelope.js +80 -0
- package/dist/bff/health.d.ts +24 -0
- package/dist/bff/health.js +19 -0
- package/dist/bff/index.d.ts +6 -0
- package/dist/bff/index.js +6 -0
- package/dist/bff/lazyRoute.d.ts +4 -0
- package/dist/bff/lazyRoute.js +13 -0
- package/dist/bff/requestContext.d.ts +17 -0
- package/dist/bff/requestContext.js +26 -0
- package/dist/bff/routerRewrite.d.ts +2 -0
- package/dist/bff/routerRewrite.js +31 -0
- package/dist/blob/binding.d.ts +16 -0
- package/dist/blob/binding.js +37 -0
- package/dist/blob/filesystem.d.ts +8 -0
- package/dist/blob/filesystem.js +71 -0
- package/dist/blob/index.d.ts +6 -0
- package/dist/blob/index.js +6 -0
- package/dist/blob/s3.d.ts +32 -0
- package/dist/blob/s3.js +56 -0
- package/dist/blob/s3Client.d.ts +25 -0
- package/dist/blob/s3Client.js +76 -0
- package/dist/blob/supabase.d.ts +40 -0
- package/dist/blob/supabase.js +59 -0
- package/dist/blob/vercel.d.ts +63 -0
- package/dist/blob/vercel.js +69 -0
- package/dist/composition/composeBundle.d.ts +47 -0
- package/dist/composition/composeBundle.js +45 -0
- package/dist/composition/httpBinding.d.ts +8 -0
- package/dist/composition/httpBinding.js +18 -0
- package/dist/composition/index.d.ts +3 -0
- package/dist/composition/index.js +3 -0
- package/dist/composition/nodeHost.d.ts +103 -0
- package/dist/composition/nodeHost.js +145 -0
- package/dist/data/binding.d.ts +34 -0
- package/dist/data/binding.js +92 -0
- package/dist/data/index.d.ts +5 -0
- package/dist/data/index.js +5 -0
- package/dist/data/postgresGateway.d.ts +42 -0
- package/dist/data/postgresGateway.js +135 -0
- package/dist/data/queryBuilder.d.ts +54 -0
- package/dist/data/queryBuilder.js +240 -0
- package/dist/data/queryBuilderSql.d.ts +76 -0
- package/dist/data/queryBuilderSql.js +145 -0
- package/dist/data/supabaseClientFactory.d.ts +34 -0
- package/dist/data/supabaseClientFactory.js +56 -0
- package/dist/data/supabaseGateway.d.ts +22 -0
- package/dist/data/supabaseGateway.js +49 -0
- package/dist/http/deadline.d.ts +20 -0
- package/dist/http/deadline.js +93 -0
- package/dist/http/index.d.ts +6 -0
- package/dist/http/index.js +5 -0
- package/dist/http/requestAdapter.d.ts +38 -0
- package/dist/http/requestAdapter.js +203 -0
- package/dist/http/runtime.d.ts +83 -0
- package/dist/http/runtime.js +199 -0
- package/dist/http/security.d.ts +44 -0
- package/dist/http/security.js +114 -0
- package/dist/http/staticAssets.d.ts +3 -0
- package/dist/http/staticAssets.js +42 -0
- package/dist/http/types.d.ts +23 -0
- package/dist/http/types.js +6 -0
- package/dist/identity/adminAuthBinding.d.ts +28 -0
- package/dist/identity/adminAuthBinding.js +66 -0
- package/dist/identity/adminAuthorization.d.ts +34 -0
- package/dist/identity/adminAuthorization.js +72 -0
- package/dist/identity/adminContracts.d.ts +70 -0
- package/dist/identity/adminContracts.js +43 -0
- package/dist/identity/adminMagicLinkHandler.d.ts +39 -0
- package/dist/identity/adminMagicLinkHandler.js +94 -0
- package/dist/identity/adminMeHandler.d.ts +15 -0
- package/dist/identity/adminMeHandler.js +49 -0
- package/dist/identity/adminPreflight.d.ts +16 -0
- package/dist/identity/adminPreflight.js +38 -0
- package/dist/identity/adminUserActionPorts.d.ts +31 -0
- package/dist/identity/adminUserActionPorts.js +51 -0
- package/dist/identity/adminUserHandlers.d.ts +38 -0
- package/dist/identity/adminUserHandlers.js +140 -0
- package/dist/identity/authVerifyUrl.d.ts +6 -0
- package/dist/identity/authVerifyUrl.js +54 -0
- package/dist/identity/contracts/contracts.d.ts +8 -0
- package/dist/identity/contracts/contracts.js +2 -0
- package/dist/identity/contracts/emailTrust.d.ts +3 -0
- package/dist/identity/contracts/emailTrust.js +4 -0
- package/dist/identity/contracts/index.d.ts +8 -0
- package/dist/identity/contracts/index.js +8 -0
- package/dist/identity/contracts/oidc.d.ts +3 -0
- package/dist/identity/contracts/oidc.js +9 -0
- package/dist/identity/contracts/operatorAuth.d.ts +35 -0
- package/dist/identity/contracts/operatorAuth.js +53 -0
- package/dist/identity/contracts/operatorInvitations.d.ts +37 -0
- package/dist/identity/contracts/operatorInvitations.js +1 -0
- package/dist/identity/contracts/ports.d.ts +22 -0
- package/dist/identity/contracts/ports.js +1 -0
- package/dist/identity/contracts/privacy.d.ts +62 -0
- package/dist/identity/contracts/privacy.js +99 -0
- package/dist/identity/contracts/providerList.d.ts +3 -0
- package/dist/identity/contracts/providerList.js +11 -0
- package/dist/identity/contracts/types.d.ts +16 -0
- package/dist/identity/contracts/types.js +4 -0
- package/dist/identity/contribution.d.ts +8 -0
- package/dist/identity/contribution.js +22 -0
- package/dist/identity/customerAuth.d.ts +8 -0
- package/dist/identity/customerAuth.js +1 -0
- package/dist/identity/customerAuthorization.d.ts +5 -0
- package/dist/identity/customerAuthorization.js +22 -0
- package/dist/identity/customerContracts.d.ts +42 -0
- package/dist/identity/customerContracts.js +43 -0
- package/dist/identity/customerIdentityBinding.d.ts +44 -0
- package/dist/identity/customerIdentityBinding.js +60 -0
- package/dist/identity/customerIdentityVerifier.d.ts +8 -0
- package/dist/identity/customerIdentityVerifier.js +101 -0
- package/dist/identity/customerMagicLinkHandler.d.ts +38 -0
- package/dist/identity/customerMagicLinkHandler.js +115 -0
- package/dist/identity/customerMeHandler.d.ts +11 -0
- package/dist/identity/customerMeHandler.js +46 -0
- package/dist/identity/customerPorts.d.ts +4 -0
- package/dist/identity/customerPorts.js +1 -0
- package/dist/identity/customerSessionBinding.d.ts +38 -0
- package/dist/identity/customerSessionBinding.js +80 -0
- package/dist/identity/customerSessionIssuer.d.ts +10 -0
- package/dist/identity/customerSessionIssuer.js +57 -0
- package/dist/identity/customerVerifyOtpHandler.d.ts +8 -0
- package/dist/identity/customerVerifyOtpHandler.js +41 -0
- package/dist/identity/directOperatorInvitationStore.d.ts +19 -0
- package/dist/identity/directOperatorInvitationStore.js +193 -0
- package/dist/identity/emailTrustPolicy.d.ts +14 -0
- package/dist/identity/emailTrustPolicy.js +16 -0
- package/dist/identity/identityPersonalDataContributor.d.ts +7 -0
- package/dist/identity/identityPersonalDataContributor.js +46 -0
- package/dist/identity/identityReadiness.d.ts +10 -0
- package/dist/identity/identityReadiness.js +25 -0
- package/dist/identity/index.d.ts +67 -0
- package/dist/identity/index.js +66 -0
- package/dist/identity/inviteAdminUserUseCase.d.ts +89 -0
- package/dist/identity/inviteAdminUserUseCase.js +75 -0
- package/dist/identity/jwtLibrary.d.ts +54 -0
- package/dist/identity/jwtLibrary.js +1 -0
- package/dist/identity/machineActorWriteFence.d.ts +4 -0
- package/dist/identity/machineActorWriteFence.js +13 -0
- package/dist/identity/magicLinkPorts.d.ts +28 -0
- package/dist/identity/magicLinkPorts.js +1 -0
- package/dist/identity/managedAccountLinkStore.d.ts +2 -0
- package/dist/identity/managedAccountLinkStore.js +93 -0
- package/dist/identity/managedAdminAuthVerifier.d.ts +7 -0
- package/dist/identity/managedAdminAuthVerifier.js +27 -0
- package/dist/identity/managedAdminUserGateways.d.ts +123 -0
- package/dist/identity/managedAdminUserGateways.js +127 -0
- package/dist/identity/managedClient.d.ts +90 -0
- package/dist/identity/managedClient.js +10 -0
- package/dist/identity/managedClientAuthLink.d.ts +3 -0
- package/dist/identity/managedClientAuthLink.js +115 -0
- package/dist/identity/managedCustomerMe.d.ts +13 -0
- package/dist/identity/managedCustomerMe.js +30 -0
- package/dist/identity/managedEmailTrustPolicy.d.ts +11 -0
- package/dist/identity/managedEmailTrustPolicy.js +105 -0
- package/dist/identity/managedIdentityVerifier.d.ts +2 -0
- package/dist/identity/managedIdentityVerifier.js +16 -0
- package/dist/identity/managedPrivacy.d.ts +4 -0
- package/dist/identity/managedPrivacy.js +39 -0
- package/dist/identity/messages.d.ts +29 -0
- package/dist/identity/messages.js +39 -0
- package/dist/identity/oidcIdentityVerifier.d.ts +45 -0
- package/dist/identity/oidcIdentityVerifier.js +309 -0
- package/dist/identity/oidcPrincipal.d.ts +2 -0
- package/dist/identity/oidcPrincipal.js +10 -0
- package/dist/identity/operatorAdminAuth.d.ts +6 -0
- package/dist/identity/operatorAdminAuth.js +13 -0
- package/dist/identity/operatorAuthHandlers.d.ts +18 -0
- package/dist/identity/operatorAuthHandlers.js +71 -0
- package/dist/identity/operatorIdentityVerifier.d.ts +8 -0
- package/dist/identity/operatorIdentityVerifier.js +19 -0
- package/dist/identity/operatorInvitationLifecycle.d.ts +7 -0
- package/dist/identity/operatorInvitationLifecycle.js +15 -0
- package/dist/identity/operatorInvitationPorts.d.ts +31 -0
- package/dist/identity/operatorInvitationPorts.js +1 -0
- package/dist/identity/operatorPorts.d.ts +37 -0
- package/dist/identity/operatorPorts.js +1 -0
- package/dist/identity/operatorSession.d.ts +13 -0
- package/dist/identity/operatorSession.js +31 -0
- package/dist/identity/operatorTokenAdminAuth.d.ts +15 -0
- package/dist/identity/operatorTokenAdminAuth.js +50 -0
- package/dist/identity/personalDataRegistry.d.ts +4 -0
- package/dist/identity/personalDataRegistry.js +11 -0
- package/dist/identity/platformAdminAuth.d.ts +15 -0
- package/dist/identity/platformAdminAuth.js +1 -0
- package/dist/identity/ports.d.ts +127 -0
- package/dist/identity/ports.js +38 -0
- package/dist/identity/postgresAccountLinkStore.d.ts +7 -0
- package/dist/identity/postgresAccountLinkStore.js +52 -0
- package/dist/identity/postgresCustomerMe.d.ts +3 -0
- package/dist/identity/postgresCustomerMe.js +21 -0
- package/dist/identity/postgresCustomerRecovery.d.ts +11 -0
- package/dist/identity/postgresCustomerRecovery.js +57 -0
- package/dist/identity/postgresOperatorIdentity.d.ts +5 -0
- package/dist/identity/postgresOperatorIdentity.js +137 -0
- package/dist/identity/postgresPrivacy.d.ts +7 -0
- package/dist/identity/postgresPrivacy.js +126 -0
- package/dist/identity/privacyHandlers.d.ts +10 -0
- package/dist/identity/privacyHandlers.js +35 -0
- package/dist/identity/privacyPorts.d.ts +72 -0
- package/dist/identity/privacyPorts.js +8 -0
- package/dist/identity/privacyUseCases.d.ts +5 -0
- package/dist/identity/privacyUseCases.js +55 -0
- package/dist/identity/reconcileAccountForPrincipal.d.ts +20 -0
- package/dist/identity/reconcileAccountForPrincipal.js +66 -0
- package/dist/identity/reconcileAccountHandler.d.ts +11 -0
- package/dist/identity/reconcileAccountHandler.js +30 -0
- package/dist/identity/removeAdminUserUseCase.d.ts +31 -0
- package/dist/identity/removeAdminUserUseCase.js +60 -0
- package/dist/identity/response.d.ts +3 -0
- package/dist/identity/response.js +2 -0
- package/dist/identity/sql.d.ts +44 -0
- package/dist/identity/sql.js +10 -0
- package/dist/job-ledger/index.d.ts +5 -0
- package/dist/job-ledger/index.js +3 -0
- package/dist/job-ledger/ports.d.ts +10 -0
- package/dist/job-ledger/ports.js +7 -0
- package/dist/job-ledger/postgres.d.ts +10 -0
- package/dist/job-ledger/postgres.js +101 -0
- package/dist/job-ledger/sql.d.ts +7 -0
- package/dist/job-ledger/sql.js +10 -0
- package/dist/job-ledger/supabase.d.ts +77 -0
- package/dist/job-ledger/supabase.js +202 -0
- package/dist/kernel/index.d.ts +1 -0
- package/dist/kernel/index.js +1 -0
- package/dist/kernel/platformKernel.d.ts +34 -0
- package/dist/kernel/platformKernel.js +115 -0
- package/dist/migrations/index.d.ts +1 -0
- package/dist/migrations/index.js +1 -0
- package/dist/migrations/postgresRunner.d.ts +50 -0
- package/dist/migrations/postgresRunner.js +176 -0
- package/dist/scheduler/advisoryLock.d.ts +44 -0
- package/dist/scheduler/advisoryLock.js +114 -0
- package/dist/scheduler/cronGuard.d.ts +10 -0
- package/dist/scheduler/cronGuard.js +19 -0
- package/dist/scheduler/cronSecret.d.ts +5 -0
- package/dist/scheduler/cronSecret.js +23 -0
- package/dist/scheduler/handlers.d.ts +9 -0
- package/dist/scheduler/handlers.js +10 -0
- package/dist/scheduler/httpEntry.d.ts +16 -0
- package/dist/scheduler/httpEntry.js +31 -0
- package/dist/scheduler/index.d.ts +9 -0
- package/dist/scheduler/index.js +9 -0
- package/dist/scheduler/jobRegistry.d.ts +21 -0
- package/dist/scheduler/jobRegistry.js +39 -0
- package/dist/scheduler/jobs.d.ts +48 -0
- package/dist/scheduler/jobs.js +92 -0
- package/dist/scheduler/nodeScheduler.d.ts +42 -0
- package/dist/scheduler/nodeScheduler.js +73 -0
- package/dist/scheduler/vercelScheduler.d.ts +29 -0
- package/dist/scheduler/vercelScheduler.js +51 -0
- package/package.json +116 -3
- package/release-gates.json +143 -0
- package/sql/20260809150000_job_run_ledger.sql +301 -0
- package/sql/20260809150001_job_run_ledger_v3.sql +70 -0
- package/sql/20260810180001_self_host_actor_auth.sql +40 -0
- package/sql/20260810204057_customer_identity_read.sql +31 -0
- package/sql/20260814090000_customer_selfservice_recovery.sql +477 -0
- package/sql/20260901143000_admin_membership_authority_foundation.sql +234 -0
- package/sql/20261018120000_identity_operator_invitations.sql +42 -0
- package/sql/20261018180000_identity_operator_challenges.sql +56 -0
- package/sql/20261018190000_identity_privacy_erasures.sql +15 -0
- package/src/bff/dispatch.ts +81 -0
- package/src/bff/envelope.ts +142 -0
- package/src/bff/health.ts +37 -0
- package/src/bff/index.ts +30 -0
- package/src/bff/lazyRoute.ts +28 -0
- package/src/bff/requestContext.ts +48 -0
- package/src/bff/routerRewrite.ts +38 -0
- package/src/blob/binding.ts +55 -0
- package/src/blob/filesystem.ts +86 -0
- package/src/blob/index.ts +17 -0
- package/src/blob/s3.ts +87 -0
- package/src/blob/s3Client.ts +91 -0
- package/src/blob/supabase.ts +88 -0
- package/src/blob/vercel.ts +127 -0
- package/src/composition/composeBundle.ts +109 -0
- package/src/composition/httpBinding.ts +30 -0
- package/src/composition/index.ts +17 -0
- package/src/composition/nodeHost.ts +289 -0
- package/src/data/binding.ts +157 -0
- package/src/data/index.ts +33 -0
- package/src/data/postgresGateway.ts +186 -0
- package/src/data/queryBuilder.ts +300 -0
- package/src/data/queryBuilderSql.ts +183 -0
- package/src/data/supabaseClientFactory.ts +92 -0
- package/src/data/supabaseGateway.ts +76 -0
- package/src/http/deadline.ts +117 -0
- package/src/http/index.ts +36 -0
- package/src/http/requestAdapter.ts +215 -0
- package/src/http/runtime.ts +319 -0
- package/src/http/security.ts +155 -0
- package/src/http/staticAssets.ts +42 -0
- package/src/http/types.ts +31 -0
- package/src/identity/adminAuthBinding.ts +76 -0
- package/src/identity/adminAuthorization.ts +106 -0
- package/src/identity/adminContracts.ts +52 -0
- package/src/identity/adminMagicLinkHandler.ts +132 -0
- package/src/identity/adminMeHandler.ts +64 -0
- package/src/identity/adminPreflight.ts +46 -0
- package/src/identity/adminUserActionPorts.ts +78 -0
- package/src/identity/adminUserHandlers.ts +174 -0
- package/src/identity/authVerifyUrl.ts +56 -0
- package/src/identity/contracts/contracts.ts +15 -0
- package/src/identity/contracts/emailTrust.ts +5 -0
- package/src/identity/contracts/index.ts +8 -0
- package/src/identity/contracts/oidc.ts +10 -0
- package/src/identity/contracts/operatorAuth.ts +61 -0
- package/src/identity/contracts/operatorInvitations.ts +32 -0
- package/src/identity/contracts/ports.ts +25 -0
- package/src/identity/contracts/privacy.ts +86 -0
- package/src/identity/contracts/providerList.ts +13 -0
- package/src/identity/contracts/types.ts +25 -0
- package/src/identity/contribution.ts +29 -0
- package/src/identity/customerAuth.ts +3 -0
- package/src/identity/customerAuthorization.ts +38 -0
- package/src/identity/customerContracts.ts +52 -0
- package/src/identity/customerIdentityBinding.ts +125 -0
- package/src/identity/customerIdentityVerifier.ts +141 -0
- package/src/identity/customerMagicLinkHandler.ts +171 -0
- package/src/identity/customerMeHandler.ts +64 -0
- package/src/identity/customerPorts.ts +2 -0
- package/src/identity/customerSessionBinding.ts +114 -0
- package/src/identity/customerSessionIssuer.ts +71 -0
- package/src/identity/customerVerifyOtpHandler.ts +44 -0
- package/src/identity/directOperatorInvitationStore.ts +178 -0
- package/src/identity/emailTrustPolicy.ts +16 -0
- package/src/identity/identityPersonalDataContributor.ts +48 -0
- package/src/identity/identityReadiness.ts +26 -0
- package/src/identity/index.ts +69 -0
- package/src/identity/inviteAdminUserUseCase.ts +134 -0
- package/src/identity/jwtLibrary.ts +24 -0
- package/src/identity/machineActorWriteFence.ts +19 -0
- package/src/identity/magicLinkPorts.ts +7 -0
- package/src/identity/managedAccountLinkStore.ts +105 -0
- package/src/identity/managedAdminAuthVerifier.ts +40 -0
- package/src/identity/managedAdminUserGateways.ts +164 -0
- package/src/identity/managedClient.ts +58 -0
- package/src/identity/managedClientAuthLink.ts +120 -0
- package/src/identity/managedCustomerMe.ts +52 -0
- package/src/identity/managedEmailTrustPolicy.ts +90 -0
- package/src/identity/managedIdentityVerifier.ts +20 -0
- package/src/identity/managedPrivacy.ts +37 -0
- package/src/identity/messages.ts +41 -0
- package/src/identity/oidcIdentityVerifier.ts +229 -0
- package/src/identity/oidcPrincipal.ts +10 -0
- package/src/identity/operatorAdminAuth.ts +14 -0
- package/src/identity/operatorAuthHandlers.ts +52 -0
- package/src/identity/operatorIdentityVerifier.ts +19 -0
- package/src/identity/operatorInvitationLifecycle.ts +14 -0
- package/src/identity/operatorInvitationPorts.ts +11 -0
- package/src/identity/operatorPorts.ts +11 -0
- package/src/identity/operatorSession.ts +30 -0
- package/src/identity/operatorTokenAdminAuth.ts +79 -0
- package/src/identity/personalDataRegistry.ts +8 -0
- package/src/identity/platformAdminAuth.ts +7 -0
- package/src/identity/ports.ts +158 -0
- package/src/identity/postgresAccountLinkStore.ts +49 -0
- package/src/identity/postgresCustomerMe.ts +33 -0
- package/src/identity/postgresCustomerRecovery.ts +72 -0
- package/src/identity/postgresOperatorIdentity.ts +123 -0
- package/src/identity/postgresPrivacy.ts +117 -0
- package/src/identity/privacyHandlers.ts +33 -0
- package/src/identity/privacyPorts.ts +52 -0
- package/src/identity/privacyUseCases.ts +48 -0
- package/src/identity/reconcileAccountForPrincipal.ts +99 -0
- package/src/identity/reconcileAccountHandler.ts +36 -0
- package/src/identity/removeAdminUserUseCase.ts +85 -0
- package/src/identity/response.ts +3 -0
- package/src/identity/sql.ts +10 -0
- package/src/job-ledger/index.ts +25 -0
- package/src/job-ledger/ports.ts +27 -0
- package/src/job-ledger/postgres.ts +121 -0
- package/src/job-ledger/sql.ts +12 -0
- package/src/job-ledger/supabase.ts +294 -0
- package/src/kernel/index.ts +17 -0
- package/src/kernel/platformKernel.ts +153 -0
- package/src/migrations/index.ts +10 -0
- package/src/migrations/postgresRunner.ts +255 -0
- package/src/scheduler/advisoryLock.ts +145 -0
- package/src/scheduler/cronGuard.ts +30 -0
- package/src/scheduler/cronSecret.ts +26 -0
- package/src/scheduler/handlers.ts +24 -0
- package/src/scheduler/httpEntry.ts +49 -0
- package/src/scheduler/index.ts +47 -0
- package/src/scheduler/jobRegistry.ts +57 -0
- package/src/scheduler/jobs.ts +119 -0
- package/src/scheduler/nodeScheduler.ts +123 -0
- package/src/scheduler/vercelScheduler.ts +71 -0
|
@@ -0,0 +1,186 @@
|
|
|
1
|
+
// Vanilla-Postgres DataGatewayPort plus capability-local role-free transaction
|
|
2
|
+
// lanes. Actor/service role changes use SET LOCAL; every call owns one pooled
|
|
3
|
+
// BEGIN/COMMIT|ROLLBACK/release lifecycle, so claims never leak between calls.
|
|
4
|
+
import type { Pool, PoolClient } from "pg";
|
|
5
|
+
import type { DataGatewayPort } from "@openlup/core/platform-runtime";
|
|
6
|
+
import { PgGatewayClient } from "./queryBuilder.js";
|
|
7
|
+
|
|
8
|
+
type ActorClaims = { sub?: string; role?: string } | null;
|
|
9
|
+
|
|
10
|
+
export interface PostgresDataGatewayEnv {
|
|
11
|
+
/** Postgres connection string (DATABASE_URL). Empty until a node-postgres deploy supplies it. */
|
|
12
|
+
connectionString: string;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export interface PostgresDataGatewayOptions {
|
|
16
|
+
/** Injection seam: tests pass a stub pool; production lazily builds a real pg.Pool from env. */
|
|
17
|
+
poolFactory?: (env: PostgresDataGatewayEnv) => Pool | Promise<Pool>;
|
|
18
|
+
}
|
|
19
|
+
/** Convert node-postgres timestamptz text to lossless RFC 3339. */
|
|
20
|
+
export function postgresTimestampTzToRfc3339(value: string): string {
|
|
21
|
+
const parts = /^(\d{4,}-\d{2}-\d{2}) (\d{2}:\d{2}:\d{2}(?:\.\d+)?)([+-])(\d{2})(?::?(\d{2}))?$/.exec(value);
|
|
22
|
+
if (!parts) return value;
|
|
23
|
+
const [, date, time, sign, offsetHours, offsetMinutes = "00"] = parts;
|
|
24
|
+
return `${date}T${time}${sign}${offsetHours}:${offsetMinutes}`;
|
|
25
|
+
}
|
|
26
|
+
/** Keep PostgREST-compatible, lossless timestamp strings at the gateway edge. */
|
|
27
|
+
export function createPostgresGatewayTypeOverrides(
|
|
28
|
+
TypeOverridesCtor: typeof import("pg").TypeOverrides,
|
|
29
|
+
): import("pg").TypeOverrides {
|
|
30
|
+
const overrides = new TypeOverridesCtor();
|
|
31
|
+
// node-postgres otherwise turns timestamptz into a millisecond Date and drops
|
|
32
|
+
// PostgreSQL microseconds, making an immediate schedule round-trip look stale.
|
|
33
|
+
overrides.setTypeParser(1184, "text", postgresTimestampTzToRfc3339);
|
|
34
|
+
return overrides;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* Capability-local, role-free transaction lane.
|
|
39
|
+
*
|
|
40
|
+
* The platform manifest intentionally creates no service role. This is not an
|
|
41
|
+
* alternate DataGatewayPort access mode: a deployment hands one lane to exactly
|
|
42
|
+
* one adapter that calls its own rail RPCs, and names that lane after the
|
|
43
|
+
* capability, because the name is the access rule. Its lifecycle reuses the same
|
|
44
|
+
* pooled BEGIN/callback/COMMIT|ROLLBACK/release implementation as the public
|
|
45
|
+
* gateway below, but it never changes the connection role.
|
|
46
|
+
*/
|
|
47
|
+
export interface PostgresRoleFreeTransactionLane {
|
|
48
|
+
run<T>(work: (gateway: unknown) => Promise<T>): Promise<T>;
|
|
49
|
+
close(): Promise<void>;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* Build a node-postgres-backed DataGatewayPort. Pure: NO pool/connection is created until a port
|
|
54
|
+
* method runs work (lazy, like the supabase adapter), so the slot binds even before DATABASE_URL is
|
|
55
|
+
* present (keeps composeBundle({}) non-null). The pool is created once and reused across calls.
|
|
56
|
+
*/
|
|
57
|
+
export function createPostgresDataGateway(
|
|
58
|
+
env: PostgresDataGatewayEnv,
|
|
59
|
+
options: PostgresDataGatewayOptions = {},
|
|
60
|
+
): DataGatewayPort {
|
|
61
|
+
const transactions = createPooledPostgresTransactions(env, options);
|
|
62
|
+
|
|
63
|
+
return {
|
|
64
|
+
async asService<T>(work: (gateway: unknown) => Promise<T>): Promise<T> {
|
|
65
|
+
return transactions.run(async (client) => {
|
|
66
|
+
await client.query("SET LOCAL ROLE service_role");
|
|
67
|
+
}, work);
|
|
68
|
+
},
|
|
69
|
+
|
|
70
|
+
async asActor<T>(claims: ActorClaims, work: (gateway: unknown) => Promise<T>): Promise<T> {
|
|
71
|
+
return transactions.run(async (client) => {
|
|
72
|
+
const jwtClaims = buildJwtClaims(claims);
|
|
73
|
+
if (jwtClaims) {
|
|
74
|
+
// Parameterized: the claims JSON is bound as $1, never interpolated into the SET statement.
|
|
75
|
+
await client.query("SELECT set_config('request.jwt.claims', $1, true)", [jwtClaims]);
|
|
76
|
+
await client.query("SET LOCAL ROLE authenticated");
|
|
77
|
+
} else {
|
|
78
|
+
// No usable principal → drop to the `anon` role so RLS evaluates the request as
|
|
79
|
+
// unauthenticated. CRITICAL: the connection's own login role may be a superuser/owner
|
|
80
|
+
// (which BYPASSes RLS), so we MUST switch roles rather than leave the default — otherwise an
|
|
81
|
+
// unauthenticated actor would silently see everything. Fail-safe: anon is RLS-bound, never
|
|
82
|
+
// elevated. (No request.jwt.claims is set, so auth.uid() returns NULL.)
|
|
83
|
+
await client.query("SET LOCAL ROLE anon");
|
|
84
|
+
}
|
|
85
|
+
}, work);
|
|
86
|
+
},
|
|
87
|
+
};
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/**
|
|
91
|
+
* Build one role-free, per-operation lane. Do not use this for generic service
|
|
92
|
+
* work: DataGatewayPort.asService remains the mandatory service_role boundary.
|
|
93
|
+
* Only a named owner-authority capability of the deployment may hold a lane.
|
|
94
|
+
*/
|
|
95
|
+
export function createPostgresRoleFreeTransactionLane(
|
|
96
|
+
env: PostgresDataGatewayEnv,
|
|
97
|
+
options: PostgresDataGatewayOptions = {},
|
|
98
|
+
): PostgresRoleFreeTransactionLane {
|
|
99
|
+
const transactions = createPooledPostgresTransactions(env, options);
|
|
100
|
+
return { run: (work) => transactions.run(async () => {}, work), close: transactions.close };
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
function createPooledPostgresTransactions(
|
|
104
|
+
env: PostgresDataGatewayEnv,
|
|
105
|
+
options: PostgresDataGatewayOptions,
|
|
106
|
+
): {
|
|
107
|
+
run<T>(setup: (client: PoolClient) => Promise<void>, work: (gateway: unknown) => Promise<T>): Promise<T>;
|
|
108
|
+
close(): Promise<void>;
|
|
109
|
+
} {
|
|
110
|
+
let poolPromise: Promise<Pool> | null = null;
|
|
111
|
+
|
|
112
|
+
async function getPool(): Promise<Pool> {
|
|
113
|
+
// Cache the in-flight promise (not the resolved Pool) so concurrent first calls share ONE pool
|
|
114
|
+
// rather than racing to build two. Promise.resolve normalizes the factory's Pool | Promise<Pool>.
|
|
115
|
+
if (!poolPromise) {
|
|
116
|
+
const factory = options.poolFactory ?? defaultPoolFactory;
|
|
117
|
+
poolPromise = Promise.resolve(factory(env));
|
|
118
|
+
}
|
|
119
|
+
return poolPromise;
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
async function withClient<T>(setup: (client: PoolClient) => Promise<void>, work: (gw: unknown) => Promise<T>): Promise<T> {
|
|
123
|
+
const activePool = await getPool();
|
|
124
|
+
const client = await activePool.connect();
|
|
125
|
+
try {
|
|
126
|
+
await client.query("BEGIN");
|
|
127
|
+
await setup(client);
|
|
128
|
+
const result = await work(new PgGatewayClient(client));
|
|
129
|
+
await client.query("COMMIT");
|
|
130
|
+
return result;
|
|
131
|
+
} catch (error) {
|
|
132
|
+
try {
|
|
133
|
+
await client.query("ROLLBACK");
|
|
134
|
+
} catch {
|
|
135
|
+
// ignore rollback failure; surface the original error
|
|
136
|
+
}
|
|
137
|
+
throw error;
|
|
138
|
+
} finally {
|
|
139
|
+
client.release();
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
return {
|
|
144
|
+
run: withClient,
|
|
145
|
+
async close(): Promise<void> {
|
|
146
|
+
if (poolPromise) await (await poolPromise).end();
|
|
147
|
+
},
|
|
148
|
+
};
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
/**
|
|
152
|
+
* Build the request.jwt.claims JSON PostgREST would set. Returns null when there is no usable
|
|
153
|
+
* principal (no sub) so the caller stays anon rather than asserting an authenticated-but-empty role.
|
|
154
|
+
*/
|
|
155
|
+
function buildJwtClaims(claims: ActorClaims): string | null {
|
|
156
|
+
if (!claims || !claims.sub) return null;
|
|
157
|
+
const role = claims.role && claims.role.trim() !== "" ? claims.role : "authenticated";
|
|
158
|
+
return JSON.stringify({ sub: claims.sub, role });
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
// Lazy default: only import `pg` and build the Pool when actually invoked, so typecheck/test paths
|
|
162
|
+
// that never run work do not load the driver. SET LOCAL keeps pooled-connection reuse safe.
|
|
163
|
+
async function defaultPoolFactory(env: PostgresDataGatewayEnv): Promise<Pool> {
|
|
164
|
+
const pg = await import("pg").catch(peerMissing);
|
|
165
|
+
const PoolCtor = (pg.default?.Pool ?? pg.Pool) as typeof import("pg").Pool;
|
|
166
|
+
const TypeOverridesCtor = (pg.default?.TypeOverrides ?? pg.TypeOverrides) as typeof import("pg").TypeOverrides;
|
|
167
|
+
return new PoolCtor({
|
|
168
|
+
connectionString: env.connectionString,
|
|
169
|
+
types: createPostgresGatewayTypeOverrides(TypeOverridesCtor),
|
|
170
|
+
});
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
/** Resolve the gateway env from process env (DATABASE_URL), mirroring the supabase binding shape. */
|
|
174
|
+
export function resolvePostgresDataGatewayEnv(env: Record<string, string | undefined>): PostgresDataGatewayEnv {
|
|
175
|
+
return { connectionString: env.DATABASE_URL ?? "" };
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
/** Translate only absence of this optional peer; preserve broken SDKs and other failures. */
|
|
179
|
+
function peerMissing(cause: unknown): never {
|
|
180
|
+
if (cause instanceof Error && "code" in cause
|
|
181
|
+
&& (cause.code === "ERR_MODULE_NOT_FOUND" || cause.code === "MODULE_NOT_FOUND")
|
|
182
|
+
&& /^Cannot find (?:package|module) ['"]pg['"]/.test(cause.message)) {
|
|
183
|
+
throw new Error("OPENLUP_E_PEER_MISSING: pg is required by the Postgres data gateway; install it alongside @openlup/platform", { cause });
|
|
184
|
+
}
|
|
185
|
+
throw cause;
|
|
186
|
+
}
|
|
@@ -0,0 +1,300 @@
|
|
|
1
|
+
// Vanilla-Postgres query-builder shim.
|
|
2
|
+
//
|
|
3
|
+
// Option A (approved): a SCOPED, injection-safe builder that emulates ONLY the supabase-js methods
|
|
4
|
+
// the 6 existing gateway consumers actually call — never a full PostgREST reimplementation. It
|
|
5
|
+
// translates a builder chain into a single PARAMETERIZED `pg` query ($1,$2,…). Values are never
|
|
6
|
+
// string-interpolated and identifiers are allowlist-validated; both invariants live in the pure SQL
|
|
7
|
+
// layer (queryBuilderSql.ts), which this file composes.
|
|
8
|
+
//
|
|
9
|
+
// Result semantics mirror PostgREST for the methods used:
|
|
10
|
+
// - default (await builder) -> { data: Row[], error }
|
|
11
|
+
// - .maybeSingle() -> { data: Row | null, error } (0/1 row; >1 is an error)
|
|
12
|
+
// - .single() -> { data: Row, error } (exactly 1 row; else error)
|
|
13
|
+
// - .range(from,to)/.limit(n) -> LIMIT/OFFSET, returns { data: Row[], error }
|
|
14
|
+
// - .select(c, {count:"exact"[,head]}) -> { data, count } from a separate aggregate; head omits rows
|
|
15
|
+
// - .insert(v).select(c).maybeSingle() -> INSERT ... RETURNING c, single row
|
|
16
|
+
// - .update(v)... -> UPDATE ... [RETURNING c]
|
|
17
|
+
// - error.code carries the pg SQLSTATE (e.g. 23505 unique-violation) so consumers' code-based
|
|
18
|
+
// branches (idempotency replay) keep working unchanged.
|
|
19
|
+
//
|
|
20
|
+
// The shim is constructed over a SINGLE acquired pg client (one per asActor/asService tx in the
|
|
21
|
+
// DataGatewayPort), so every query here runs inside that request's transaction with its RLS GUCs set.
|
|
22
|
+
|
|
23
|
+
import type { PoolClient } from "pg";
|
|
24
|
+
|
|
25
|
+
import {
|
|
26
|
+
ParamAccumulator,
|
|
27
|
+
joinParts,
|
|
28
|
+
quoteIdent,
|
|
29
|
+
rangeNotSatisfiable,
|
|
30
|
+
renderColumns,
|
|
31
|
+
renderCountQuery,
|
|
32
|
+
renderFilter,
|
|
33
|
+
renderInsertStatement,
|
|
34
|
+
toShimError,
|
|
35
|
+
unwrapRpcRows,
|
|
36
|
+
type Filter,
|
|
37
|
+
type OrderBy,
|
|
38
|
+
type PgQueryExecutor,
|
|
39
|
+
type PgShimError,
|
|
40
|
+
type PgShimResult,
|
|
41
|
+
} from "./queryBuilderSql.js";
|
|
42
|
+
|
|
43
|
+
// Re-export the result/error/executor shapes so consumers import them from the builder entrypoint.
|
|
44
|
+
export type { PgQueryExecutor, PgShimError, PgShimResult };
|
|
45
|
+
|
|
46
|
+
interface BuilderState {
|
|
47
|
+
table: string;
|
|
48
|
+
mode: "select" | "insert" | "update";
|
|
49
|
+
columns: string; // RETURNING / SELECT projection
|
|
50
|
+
filters: Filter[];
|
|
51
|
+
orders: OrderBy[];
|
|
52
|
+
limit: number | null;
|
|
53
|
+
offset: number | null;
|
|
54
|
+
insertRows: Array<Record<string, unknown>> | null;
|
|
55
|
+
updateValues: Record<string, unknown> | null;
|
|
56
|
+
exactCount: boolean;
|
|
57
|
+
head: boolean;
|
|
58
|
+
rangeRequested: boolean;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* Builder over one pg client. Chainable + awaitable (PromiseLike). Every value flows through a param
|
|
63
|
+
* accumulator, so the rendered SQL contains only $N placeholders for values.
|
|
64
|
+
*/
|
|
65
|
+
export class PgQueryBuilder<T = unknown> implements PromiseLike<PgShimResult<T>> {
|
|
66
|
+
private state: BuilderState;
|
|
67
|
+
|
|
68
|
+
constructor(
|
|
69
|
+
private readonly client: PgQueryExecutor,
|
|
70
|
+
table: string,
|
|
71
|
+
) {
|
|
72
|
+
this.state = {
|
|
73
|
+
table,
|
|
74
|
+
mode: "select",
|
|
75
|
+
columns: "*",
|
|
76
|
+
filters: [],
|
|
77
|
+
orders: [],
|
|
78
|
+
limit: null,
|
|
79
|
+
offset: null,
|
|
80
|
+
insertRows: null,
|
|
81
|
+
updateValues: null,
|
|
82
|
+
exactCount: false,
|
|
83
|
+
head: false,
|
|
84
|
+
rangeRequested: false,
|
|
85
|
+
};
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
select(columns: string, options?: { count?: string; head?: boolean }): this {
|
|
89
|
+
this.state.columns = columns;
|
|
90
|
+
this.state.exactCount = options?.count === "exact";
|
|
91
|
+
this.state.head = options?.head === true;
|
|
92
|
+
return this;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
insert(values: Record<string, unknown> | Array<Record<string, unknown>>): this {
|
|
96
|
+
this.state.mode = "insert";
|
|
97
|
+
this.state.insertRows = Array.isArray(values) ? values : [values];
|
|
98
|
+
return this;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
update(values: Record<string, unknown>): this {
|
|
102
|
+
this.state.mode = "update";
|
|
103
|
+
this.state.updateValues = values;
|
|
104
|
+
return this;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
eq(column: string, value: unknown): this {
|
|
108
|
+
this.state.filters.push({ kind: "eq", column, value });
|
|
109
|
+
return this;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
gt(column: string, value: unknown): this {
|
|
113
|
+
this.state.filters.push({ kind: "gt", column, value });
|
|
114
|
+
return this;
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
gte(column: string, value: unknown): this {
|
|
118
|
+
this.state.filters.push({ kind: "gte", column, value });
|
|
119
|
+
return this;
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
lte(column: string, value: unknown): this {
|
|
123
|
+
this.state.filters.push({ kind: "lte", column, value });
|
|
124
|
+
return this;
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
in(column: string, values: unknown[]): this {
|
|
128
|
+
this.state.filters.push({ kind: "in", column, values });
|
|
129
|
+
return this;
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
is(column: string, value: unknown): this {
|
|
133
|
+
this.state.filters.push({ kind: "is", column, value });
|
|
134
|
+
return this;
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
ilike(column: string, value: string): this {
|
|
138
|
+
this.state.filters.push({ kind: "ilike", column, value });
|
|
139
|
+
return this;
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
order(column: string, options?: { ascending?: boolean }): this {
|
|
143
|
+
this.state.orders.push({ column, ascending: options?.ascending !== false });
|
|
144
|
+
return this;
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
limit(count: number): this {
|
|
148
|
+
this.state.limit = count;
|
|
149
|
+
return this;
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
range(from: number, to: number): Promise<PgShimResult<T>> {
|
|
153
|
+
// PostgREST range is inclusive on both ends → LIMIT (to-from+1) OFFSET from.
|
|
154
|
+
this.state.offset = from;
|
|
155
|
+
this.state.limit = to - from + 1;
|
|
156
|
+
this.state.rangeRequested = true;
|
|
157
|
+
return this.run("many");
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
async maybeSingle(): Promise<PgShimResult<T>> {
|
|
161
|
+
return this.run("maybe");
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
async single(): Promise<PgShimResult<T>> {
|
|
165
|
+
return this.run("single");
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
then<R1 = PgShimResult<T>, R2 = never>(
|
|
169
|
+
onfulfilled?: ((value: PgShimResult<T>) => R1 | PromiseLike<R1>) | null,
|
|
170
|
+
onrejected?: ((reason: unknown) => R2 | PromiseLike<R2>) | null,
|
|
171
|
+
): Promise<R1 | R2> {
|
|
172
|
+
return this.run("many").then(onfulfilled, onrejected);
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
private async run(cardinality: "many" | "maybe" | "single"): Promise<PgShimResult<T>> {
|
|
176
|
+
try {
|
|
177
|
+
const count = this.state.exactCount ? await this.runExactCount() : null;
|
|
178
|
+
// A page past the end is a REFUSAL upstream, not an empty answer — but only once the total is
|
|
179
|
+
// known, which is why this sits behind the count and not behind `.range()` itself.
|
|
180
|
+
const unsatisfiable = this.state.rangeRequested ? rangeNotSatisfiable(this.state.offset, count) : null;
|
|
181
|
+
if (unsatisfiable) return { data: [] as T, error: unsatisfiable, count: null };
|
|
182
|
+
// head:true is a HEAD request: no body, so the client contract reports data:null and no row query.
|
|
183
|
+
if (this.state.head) return { data: null as T, error: null, count };
|
|
184
|
+
const { text, values } = this.compile();
|
|
185
|
+
const { rows } = await this.client.query(text, values);
|
|
186
|
+
// The client contract reports count: null unless a count was requested; `shape` must not invent one.
|
|
187
|
+
return { ...this.shape(rows, cardinality), count };
|
|
188
|
+
} catch (error) {
|
|
189
|
+
return { data: (cardinality === "many" ? [] : null) as T, error: toShimError(error), count: null };
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
private async runExactCount(): Promise<number> {
|
|
194
|
+
const params = new ParamAccumulator();
|
|
195
|
+
const { rows } = await this.client.query(renderCountQuery(this.state.table, this.state.filters, params), params.values);
|
|
196
|
+
return Number(rows[0]?.exact_count ?? 0);
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
private shape(rows: Record<string, unknown>[], cardinality: "many" | "maybe" | "single"): PgShimResult<T> {
|
|
200
|
+
if (cardinality === "many") {
|
|
201
|
+
return { data: rows as T, error: null };
|
|
202
|
+
}
|
|
203
|
+
if (rows.length > 1) {
|
|
204
|
+
// PostgREST returns 406 (PGRST116) when maybeSingle/single match multiple rows.
|
|
205
|
+
return { data: null as T, error: { code: "PGRST116", message: "multiple rows returned" } };
|
|
206
|
+
}
|
|
207
|
+
if (cardinality === "single" && rows.length === 0) {
|
|
208
|
+
return { data: null as T, error: { code: "PGRST116", message: "no rows returned" } };
|
|
209
|
+
}
|
|
210
|
+
return { data: (rows[0] ?? null) as T, error: null };
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
private compile(): { text: string; values: unknown[] } {
|
|
214
|
+
const params = new ParamAccumulator();
|
|
215
|
+
if (this.state.mode === "insert") return this.compileInsert(params);
|
|
216
|
+
if (this.state.mode === "update") return this.compileUpdate(params);
|
|
217
|
+
return this.compileSelect(params);
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
private compileSelect(params: ParamAccumulator): { text: string; values: unknown[] } {
|
|
221
|
+
const parts = [`SELECT ${renderColumns(this.state.columns)} FROM ${quoteIdent(this.state.table)}`];
|
|
222
|
+
parts.push(this.renderWhere(params));
|
|
223
|
+
parts.push(this.renderOrder());
|
|
224
|
+
parts.push(this.renderLimitOffset(params));
|
|
225
|
+
return { text: joinParts(parts), values: params.values };
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
private compileInsert(params: ParamAccumulator): { text: string; values: unknown[] } {
|
|
229
|
+
const text = renderInsertStatement(this.state.table, this.state.insertRows ?? [], this.state.columns, params);
|
|
230
|
+
return { text, values: params.values };
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
private compileUpdate(params: ParamAccumulator): { text: string; values: unknown[] } {
|
|
234
|
+
const values = this.state.updateValues ?? {};
|
|
235
|
+
const assignments = Object.keys(values)
|
|
236
|
+
.map((c) => `${quoteIdent(c)} = ${params.add(values[c])}`)
|
|
237
|
+
.join(", ");
|
|
238
|
+
if (assignments === "") throw new Error("pg-shim: update requires at least one column");
|
|
239
|
+
const parts = [`UPDATE ${quoteIdent(this.state.table)} SET ${assignments}`];
|
|
240
|
+
parts.push(this.renderWhere(params));
|
|
241
|
+
const returning = this.state.columns && this.state.columns !== "*"
|
|
242
|
+
? `RETURNING ${renderColumns(this.state.columns)}`
|
|
243
|
+
: "";
|
|
244
|
+
if (returning) parts.push(returning);
|
|
245
|
+
return { text: joinParts(parts), values: params.values };
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
private renderWhere(params: ParamAccumulator): string {
|
|
249
|
+
if (this.state.filters.length === 0) return "";
|
|
250
|
+
const clauses = this.state.filters.map((f) => renderFilter(f, params));
|
|
251
|
+
return `WHERE ${clauses.join(" AND ")}`;
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
private renderOrder(): string {
|
|
255
|
+
if (this.state.orders.length === 0) return "";
|
|
256
|
+
const cols = this.state.orders
|
|
257
|
+
.map((o) => `${quoteIdent(o.column)} ${o.ascending ? "ASC" : "DESC"}`)
|
|
258
|
+
.join(", ");
|
|
259
|
+
return `ORDER BY ${cols}`;
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
private renderLimitOffset(params: ParamAccumulator): string {
|
|
263
|
+
const parts: string[] = [];
|
|
264
|
+
if (this.state.limit !== null) parts.push(`LIMIT ${params.add(this.state.limit)}`);
|
|
265
|
+
if (this.state.offset !== null) parts.push(`OFFSET ${params.add(this.state.offset)}`);
|
|
266
|
+
return parts.join(" ");
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
/** supabase-js-style client over one acquired pg client: `.from(t)` + `.rpc(fn, args)`. */
|
|
271
|
+
export class PgGatewayClient {
|
|
272
|
+
constructor(private readonly client: PgQueryExecutor) {}
|
|
273
|
+
|
|
274
|
+
query(text: string, values?: unknown[]) { return this.client.query(text, values); }
|
|
275
|
+
|
|
276
|
+
from<T = Record<string, unknown>>(table: string): PgQueryBuilder<T> {
|
|
277
|
+
return new PgQueryBuilder<T>(this.client, table);
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
async rpc(functionName: string, args: Record<string, unknown> = {}): Promise<PgShimResult> {
|
|
281
|
+
try {
|
|
282
|
+
const name = quoteIdent(functionName);
|
|
283
|
+
const params = new ParamAccumulator();
|
|
284
|
+
// Named-arg invocation: every existing RPC uses `p_*` named params. `name => $n` binds by name
|
|
285
|
+
// so arg order is irrelevant and values are fully parameterized.
|
|
286
|
+
const namedArgs = Object.keys(args)
|
|
287
|
+
.map((key) => `${quoteIdent(key)} => ${params.add(args[key])}`)
|
|
288
|
+
.join(", ");
|
|
289
|
+
const text = `SELECT * FROM ${name}(${namedArgs})`;
|
|
290
|
+
const { rows } = await this.client.query(text, params.values);
|
|
291
|
+
// RPCs returning a scalar set-returning function expose the value under the function name;
|
|
292
|
+
// a single-column single-row result unwraps to that value (matches supabase-js rpc shape).
|
|
293
|
+
return { data: unwrapRpcRows(rows, functionName), error: null };
|
|
294
|
+
} catch (error) {
|
|
295
|
+
return { data: null, error: toShimError(error) };
|
|
296
|
+
}
|
|
297
|
+
}
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
export type { PoolClient };
|
|
@@ -0,0 +1,183 @@
|
|
|
1
|
+
// Vanilla-Postgres query-builder SQL primitives.
|
|
2
|
+
//
|
|
3
|
+
// Extracted from queryBuilder.ts (300-LOC cap) — the pure, stateless SQL-fragment layer the builder
|
|
4
|
+
// composes: result/error shapes, the injection-safety chokepoint (ParamAccumulator), identifier
|
|
5
|
+
// quoting (allowlist), column projection, and filter rendering. VALUES ARE NEVER string-interpolated;
|
|
6
|
+
// they flow through ParamAccumulator as $N placeholders. Identifiers (table/column names) are validated
|
|
7
|
+
// against a strict allowlist regex and double-quoted, so they cannot smuggle SQL either.
|
|
8
|
+
|
|
9
|
+
/** PostgREST-shaped error the consumers narrow on (`.code`, `.message`, `.details`, `.hint`). */
|
|
10
|
+
export interface PgShimError {
|
|
11
|
+
code?: string;
|
|
12
|
+
message?: string;
|
|
13
|
+
details?: string;
|
|
14
|
+
hint?: string;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export interface PgShimResult<T = unknown> {
|
|
18
|
+
data: T;
|
|
19
|
+
error: PgShimError | null;
|
|
20
|
+
count?: number | null;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/** Minimal query surface we need from a pg client (Pool acquires a PoolClient per request). */
|
|
24
|
+
export interface PgQueryExecutor {
|
|
25
|
+
query(text: string, values?: unknown[]): Promise<{ rows: Record<string, unknown>[] }>;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export type Filter =
|
|
29
|
+
| { kind: "eq" | "gte" | "lte" | "gt"; column: string; value: unknown }
|
|
30
|
+
| { kind: "in"; column: string; values: unknown[] }
|
|
31
|
+
| { kind: "ilike"; column: string; value: string }
|
|
32
|
+
| { kind: "is"; column: string; value: unknown };
|
|
33
|
+
|
|
34
|
+
export interface OrderBy {
|
|
35
|
+
column: string;
|
|
36
|
+
ascending: boolean;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
// Identifiers (table + column names) are NEVER parameterizable in SQL, so they are validated against
|
|
40
|
+
// a strict allowlist and quoted. Consumers only ever pass static, code-literal identifiers; this
|
|
41
|
+
// guard turns any attempt to pass a crafted identifier into a thrown error rather than injected SQL.
|
|
42
|
+
const IDENTIFIER_RE = /^[a-z_][a-z0-9_]*$/i;
|
|
43
|
+
|
|
44
|
+
export function quoteIdent(raw: string): string {
|
|
45
|
+
if (!IDENTIFIER_RE.test(raw)) {
|
|
46
|
+
throw new Error(`pg-shim: unsafe identifier ${JSON.stringify(raw)}`);
|
|
47
|
+
}
|
|
48
|
+
return `"${raw}"`;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
// `select("a, b")` etc. — a comma list of identifiers or "*". Each segment is validated; "*" passes
|
|
52
|
+
// through. PostgREST embedding syntax (foo(bar)) is NOT used by any consumer, so it is rejected
|
|
53
|
+
// (fail-closed) rather than silently mistranslated.
|
|
54
|
+
export function renderColumns(columns: string): string {
|
|
55
|
+
const trimmed = columns.trim();
|
|
56
|
+
if (trimmed === "" || trimmed === "*") return "*";
|
|
57
|
+
return trimmed
|
|
58
|
+
.split(",")
|
|
59
|
+
.map((c) => c.trim())
|
|
60
|
+
.map((c) => (c === "*" ? "*" : quoteIdent(c)))
|
|
61
|
+
.join(", ");
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
export function renderFilter(filter: Filter, params: ParamAccumulator): string {
|
|
65
|
+
const col = quoteIdent(filter.column);
|
|
66
|
+
switch (filter.kind) {
|
|
67
|
+
case "eq":
|
|
68
|
+
return `${col} = ${params.add(filter.value)}`;
|
|
69
|
+
case "gt":
|
|
70
|
+
return `${col} > ${params.add(filter.value)}`;
|
|
71
|
+
case "gte":
|
|
72
|
+
return `${col} >= ${params.add(filter.value)}`;
|
|
73
|
+
case "lte":
|
|
74
|
+
return `${col} <= ${params.add(filter.value)}`;
|
|
75
|
+
case "ilike":
|
|
76
|
+
return `${col} ILIKE ${params.add(filter.value)}`;
|
|
77
|
+
case "in": {
|
|
78
|
+
// Empty IN () is invalid SQL; PostgREST treats `.in([])` as matching nothing.
|
|
79
|
+
if (filter.values.length === 0) return "false";
|
|
80
|
+
const placeholders = filter.values.map((v) => params.add(v)).join(", ");
|
|
81
|
+
return `${col} IN (${placeholders})`;
|
|
82
|
+
}
|
|
83
|
+
case "is":
|
|
84
|
+
// .is(col, null) → IS NULL; .is(col, true/false) → IS TRUE/FALSE. Value is a literal keyword,
|
|
85
|
+
// not user data (consumers only pass null/true/false), so it is rendered, not parameterized.
|
|
86
|
+
if (filter.value === null) return `${col} IS NULL`;
|
|
87
|
+
if (filter.value === true) return `${col} IS TRUE`;
|
|
88
|
+
if (filter.value === false) return `${col} IS FALSE`;
|
|
89
|
+
throw new Error("pg-shim: .is() only supports null/true/false");
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/**
|
|
94
|
+
* PostgREST `count=exact` rendered as a SEPARATE aggregate over the same FROM/WHERE — deliberately
|
|
95
|
+
* NOT a `COUNT(*) OVER()` folded into the row query. PostgREST's exact count ignores limit/offset,
|
|
96
|
+
* and a window function emits no row at all for an empty page, so an offset past the end would
|
|
97
|
+
* report 0 instead of the true total. Keeping it separate also leaves the row projection
|
|
98
|
+
* byte-identical: there is no synthetic column to strip before cardinality shaping.
|
|
99
|
+
*/
|
|
100
|
+
export function renderCountQuery(table: string, filters: readonly Filter[], params: ParamAccumulator): string {
|
|
101
|
+
const where = filters.length === 0
|
|
102
|
+
? ""
|
|
103
|
+
: `WHERE ${filters.map((filter) => renderFilter(filter, params)).join(" AND ")}`;
|
|
104
|
+
return joinParts([`SELECT count(*) AS exact_count FROM ${quoteIdent(table)}`, where]);
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/**
|
|
108
|
+
* PostgREST refuses an out-of-bounds page instead of answering an empty one -- but ONLY when it
|
|
109
|
+
* knows the total, i.e. when an exact count was requested; without one it answers 200 and `[]`,
|
|
110
|
+
* which is what this shim already did. The boundary is strict: offset === total is a legal empty
|
|
111
|
+
* page, offset === total + 1 is not. Measured against PostgREST 14.10 before this was written,
|
|
112
|
+
* including the `details` sentence, which carries the two numbers a caller pages on.
|
|
113
|
+
*/
|
|
114
|
+
export function rangeNotSatisfiable(offset: number | null, total: number | null): PgShimError | null {
|
|
115
|
+
if (offset === null || total === null || offset <= total) return null;
|
|
116
|
+
return {
|
|
117
|
+
code: "PGRST103",
|
|
118
|
+
message: "Requested range not satisfiable",
|
|
119
|
+
details: `An offset of ${offset} was requested, but there are only ${total} rows.`,
|
|
120
|
+
};
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
/**
|
|
124
|
+
* INSERT ... VALUES ... RETURNING, with the column list taken from the FIRST row and every later
|
|
125
|
+
* row required to carry the same key set. Deriving the columns from row 0 alone and binding the
|
|
126
|
+
* rest positionally is how a batch used to lose a column silently: an extra key vanished, a missing
|
|
127
|
+
* one bound NULL over a DEFAULT. PostgREST answers PGRST102 "All object keys must match" to exactly
|
|
128
|
+
* this payload -- and keeps answering it under `Prefer: missing=default`, measured -- so the shim
|
|
129
|
+
* refuses too. Refusal, not union: parity is the point, and this builder exposes no Prefer header
|
|
130
|
+
* through which a caller could ask for anything else.
|
|
131
|
+
*/
|
|
132
|
+
export function renderInsertStatement(
|
|
133
|
+
table: string,
|
|
134
|
+
rows: readonly Record<string, unknown>[],
|
|
135
|
+
projection: string,
|
|
136
|
+
params: ParamAccumulator,
|
|
137
|
+
): string {
|
|
138
|
+
if (rows.length === 0) throw new Error("pg-shim: insert requires at least one row");
|
|
139
|
+
const columns = Object.keys(rows[0]!);
|
|
140
|
+
const signature = [...columns].sort().join("\u0000");
|
|
141
|
+
for (const row of rows) {
|
|
142
|
+
if ([...Object.keys(row)].sort().join("\u0000") !== signature) {
|
|
143
|
+
throw Object.assign(new Error("All object keys must match"), { code: "PGRST102" });
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
const tuples = rows.map((row) => `(${columns.map((column) => params.add(row[column])).join(", ")})`).join(", ");
|
|
147
|
+
return `INSERT INTO ${quoteIdent(table)} (${columns.map(quoteIdent).join(", ")}) VALUES ${tuples} `
|
|
148
|
+
+ `RETURNING ${renderColumns(projection)}`;
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
// supabase-js rpc() returns the function's return value directly: a scalar/json function yields that
|
|
152
|
+
// value; a TABLE/SETOF function yields the row array. Heuristic mirrors that: 1 row × 1 column whose
|
|
153
|
+
// name equals the function → the scalar; otherwise the rows array (TABLE-returning).
|
|
154
|
+
export function unwrapRpcRows(rows: Record<string, unknown>[], functionName: string): unknown {
|
|
155
|
+
if (rows.length === 1) {
|
|
156
|
+
const keys = Object.keys(rows[0]);
|
|
157
|
+
if (keys.length === 1 && keys[0] === functionName) return rows[0][functionName];
|
|
158
|
+
}
|
|
159
|
+
return rows;
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
/** Accumulates values and hands back $1,$2,… placeholders — the single injection-safety chokepoint. */
|
|
163
|
+
export class ParamAccumulator {
|
|
164
|
+
readonly values: unknown[] = [];
|
|
165
|
+
add(value: unknown): string {
|
|
166
|
+
this.values.push(value);
|
|
167
|
+
return `$${this.values.length}`;
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
export function joinParts(parts: string[]): string {
|
|
172
|
+
return parts.filter((p) => p.trim() !== "").join(" ");
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
export function toShimError(error: unknown): PgShimError {
|
|
176
|
+
const e = error as { code?: string; message?: string; detail?: string; hint?: string };
|
|
177
|
+
return {
|
|
178
|
+
code: e?.code,
|
|
179
|
+
message: e?.message ?? "query failed",
|
|
180
|
+
details: e?.detail,
|
|
181
|
+
hint: e?.hint,
|
|
182
|
+
};
|
|
183
|
+
}
|