import { CompleteSelfServiceOrganizationSetupResponse, type CompleteSelfServiceOrganizationSetupResponse as CompleteSelfServiceOrganizationSetupResponseType, CompleteOrganizationUserSetupResponse, type CompleteOrganizationUserSetupResponse as CompleteOrganizationUserSetupResponseType, OrganizationUserSetupDelivery, type OrganizationUserSetupDelivery as OrganizationUserSetupDeliveryType, OrganizationUserSetupPreview, type OrganizationUserSetupPreview as OrganizationUserSetupPreviewType, OrganizationUserSetupPreviewWorkspace, } from "@opengeni/contracts"; import { sql } from "drizzle-orm"; import type { Database } from "./database"; import { rawRows, setSubjectRlsContext, withRlsContext } from "./database"; export async function getSelfServiceOrganizationOnboardingState( db: Database, input: { authUserId: string; email: string; emailVerified: boolean }, ): Promise<"required" | "invitation_pending" | "unavailable" | "complete"> { const actorSubjectId = `user:${input.authUserId}`; return await db.transaction(async (tx) => { const txDb = tx as unknown as Database; await setSubjectRlsContext(txDb, actorSubjectId); if (input.emailVerified) { await rawRows( txDb, sql`select bind_pending_organization_invitations_for_verified_email( ${actorSubjectId}::text, ${input.email}::text )`, ); } const [membershipRow] = await rawRows<{ active: boolean }>( txDb, sql`select exists( select 1 from pg_catalog.jsonb_array_elements( list_self_organization_memberships(${actorSubjectId}::text) ) membership(value) where membership.value ->> 'status' = 'active' ) as active`, ); if (membershipRow?.active === true) return "complete"; const [invitationRow] = await rawRows<{ pending: boolean }>( txDb, sql`select has_pending_organization_invitation_for_subject( ${actorSubjectId}::text ) as pending`, ); if (invitationRow?.pending === true) return "invitation_pending"; const [membershipPresenceRow] = await rawRows<{ exists: boolean }>( txDb, sql`select exists( select 1 from pg_catalog.jsonb_array_elements( list_self_organization_memberships(${actorSubjectId}::text) ) membership(value) ) as exists`, ); return membershipPresenceRow?.exists === true ? "unavailable" : "required"; }); } export async function preflightOrganizationUserSetup( db: Database, tokenDigest: string, ): Promise<"pending" | "completed" | "unavailable"> { const [row] = await rawRows<{ result: unknown }>( db, sql`select preflight_organization_user_setup(${tokenDigest}::text) as result`, ); if (row?.result !== "pending" && row?.result !== "completed" && row?.result !== "unavailable") { throw new Error("Organization user setup preflight returned an invalid result"); } return row.result; } export async function completeSelfServiceOrganizationSetup( db: Database, input: { authUserId: string; actorSubjectId: string; organizationName: string; operationId: string; requestFingerprint: string; /** Legacy compatibility flag; eligibility issuance is unconditional after migration 0845. */ trialCreditsEnabled?: boolean; trialCreditModelIds?: string[] | undefined; }, ): Promise { return (await completeSelfServiceOrganizationSetupWithSignupNetwork(db, input)).setup; } /** Keyed hashes of the trusted client network; never the address itself. */ export type SignupNetworkSource = { addressHash: string; prefixHash: string }; /** * Whether the owner's mail address is a disposable inbox (its domain or MX * host is a temporary-inbox service, migration 1493), as the API found at * setup. Only this flag is recorded, never the domain or the MX host. */ export type SignupMailSignal = "disposable" | "clear"; /** * Hands the setup trigger the owner's mail signal for this transaction * (migration 1493). Transaction-local and set by the trusted API; null * records nothing (unknown). */ export async function setSignupMailSignalForSetup( txDb: Database, signal: SignupMailSignal | null | undefined, ): Promise { await rawRows( txDb, sql`select pg_catalog.set_config('opengeni.signup_owner_mail_signal', ${signal ?? ""}, true)`, ); } /** * Hands the setup receipt trigger the signup network (migration 1354) for * this transaction. Every route that can create a self-serve organization * must call it before the receipt is written, so the network rate limit and * velocity rule see the organization. Transaction-local and set by the * trusted API, never from the request body. Null records nothing. */ export async function setSignupNetworkSourceForSetup( txDb: Database, signupNetwork: SignupNetworkSource | null | undefined, ): Promise { await rawRows( txDb, sql`select pg_catalog.set_config( 'opengeni.signup_network_source', ${ signupNetwork ? JSON.stringify({ addressHash: signupNetwork.addressHash, prefixHash: signupNetwork.prefixHash, }) : "" }, true )`, ); } /** * Accounts the setup receipt trigger of this transaction asked to evaluate * after commit (this one first, then recent same-network organizations). * Empty for a replay of a committed setup or when detection is off. */ export async function readSignupNetworkEvaluateAccounts(txDb: Database): Promise { // The network rules' list (1354, 1471, 1484), then the email cluster // rule's (1489), each this organization first; duplicates once. const [evaluate] = await rawRows<{ ids: string | null; email_ids: string | null }>( txDb, sql`select pg_catalog.current_setting('opengeni.signup_network_evaluate_accounts', true) as ids, pg_catalog.current_setting('opengeni.signup_email_cluster_evaluate_accounts', true) as email_ids`, ); const ids = [ ...(evaluate?.ids ?? "").split(","), ...(evaluate?.email_ids ?? "").split(","), ].filter((id) => /^[0-9a-f-]{36}$/u.test(id)); return [...new Set(ids)]; } /** * {@link completeSelfServiceOrganizationSetup} that also hands the setup * receipt trigger the signup network (migration 1354). A new self-serve * organization records it and may be refused with SQLSTATE OG429 by the * network rate limit; an idempotent replay records and refuses nothing. * `evaluateAccountIds` lists the accounts to evaluate after commit (this one * first, then recent same-network organizations), empty when detection is off. */ export async function completeSelfServiceOrganizationSetupWithSignupNetwork( db: Database, input: { authUserId: string; actorSubjectId: string; organizationName: string; operationId: string; requestFingerprint: string; /** Legacy compatibility flag; eligibility issuance is unconditional after migration 0845. */ trialCreditsEnabled?: boolean; trialCreditModelIds?: string[] | undefined; signupNetwork?: SignupNetworkSource | null; signupMailSignal?: SignupMailSignal | null; }, ): Promise<{ setup: CompleteSelfServiceOrganizationSetupResponseType; evaluateAccountIds: string[]; }> { return await db.transaction(async (tx) => { const txDb = tx as unknown as Database; await setSubjectRlsContext(txDb, input.actorSubjectId); // Transaction-local and set by the trusted API, never the request body. // The AFTER INSERT trigger records non-monetary Free eligibility atomically // with setup. Keep the legacy GUC for pre-0845 compatibility; it cannot // enable a monetary signup bonus on the current schema. await rawRows( txDb, sql`select pg_catalog.set_config( 'opengeni.verified_signup_trial_enabled', ${input.trialCreditsEnabled === true ? "on" : "off"}, true )`, ); await rawRows( txDb, sql`select pg_catalog.set_config( 'opengeni.signup_credit_model_ids', ${input.trialCreditModelIds ? JSON.stringify(input.trialCreditModelIds) : ""}, true )`, ); await setSignupNetworkSourceForSetup(txDb, input.signupNetwork); await setSignupMailSignalForSetup(txDb, input.signupMailSignal); const [row] = await rawRows<{ result: unknown }>( txDb, sql`select complete_self_service_organization_setup( ${JSON.stringify({ authUserId: input.authUserId, actorSubjectId: input.actorSubjectId, organizationName: input.organizationName, operationId: input.operationId, requestFingerprint: input.requestFingerprint, })}::jsonb ) as result`, ); const setup = CompleteSelfServiceOrganizationSetupResponse.parse(row?.result); // Set only by the receipt trigger of this transaction, for a new receipt. return { setup, evaluateAccountIds: await readSignupNetworkEvaluateAccounts(txDb) }; }); } export async function ensureOrganizationUserSetupIntent( db: Database, input: { organizationId: string; actorSubjectId: string; invitationId: string; tokenDigest: string; expiresAt: string; }, ): Promise<{ status: "pending" | "completed" }> { return await withRlsContext( db, { accountId: input.organizationId, workspaceId: null }, async (scopedDb) => { await setSubjectRlsContext(scopedDb, input.actorSubjectId); const [row] = await rawRows<{ result: unknown }>( scopedDb, sql`select ensure_organization_user_setup_intent( ${JSON.stringify(input)}::jsonb ) as result`, ); const result = row?.result as { status?: unknown } | undefined; if (result?.status !== "pending" && result?.status !== "completed") { throw new Error("Organization user setup intent returned an invalid result"); } return { status: result.status }; }, ); } export type OrganizationUserSetupDeliveryClaim = | { claimed: false; delivery: OrganizationUserSetupDeliveryType; } | { claimed: true; delivery: OrganizationUserSetupDeliveryType; attemptId: string; claimHolderId: string; invitationId: string; providerKey: string; recipientEmail: string; recipientName: string | null; organizationName: string; organizationRole: "owner" | "admin" | "member"; sharedWorkspaceAccess: Array<{ workspaceId: string; workspaceName: string; role: "viewer" | "member" | "admin"; }>; expiresAt: string; setupTokenTransport: "fragment" | "query" | null; payloadDigest: string | null; }; export async function claimOrganizationUserSetupDelivery( db: Database, input: { organizationId: string; actorSubjectId: string; invitationId: string; invitationOperationId?: string; operationId: string; }, ): Promise { return await withRlsContext( db, { accountId: input.organizationId, workspaceId: null }, async (scopedDb) => { await setSubjectRlsContext(scopedDb, input.actorSubjectId); const [row] = await rawRows<{ result: unknown }>( scopedDb, sql`select claim_organization_user_setup_delivery_v2( ${JSON.stringify(input)}::jsonb ) as result`, ); return parseOrganizationUserSetupDeliveryClaim(row?.result); }, ); } export async function prepareOrganizationUserSetupDelivery( db: Database, input: { organizationId: string; actorSubjectId: string; deliveryId: string; attemptId: string; claimHolderId: string; tokenDigest: string; payloadDigest: string; setupTokenTransport: "fragment" | "query"; providerIdempotencyScope: string; providerIdempotencyRetentionSeconds: number; }, ): Promise { await withRlsContext( db, { accountId: input.organizationId, workspaceId: null }, async (scopedDb) => { await setSubjectRlsContext(scopedDb, input.actorSubjectId); await rawRows( scopedDb, sql`select prepare_organization_user_setup_delivery_v2( ${JSON.stringify(input)}::jsonb )`, ); }, ); } export async function settleOrganizationUserSetupDelivery( db: Database, input: { organizationId: string; actorSubjectId: string; deliveryId: string; attemptId: string; claimHolderId: string; outcome: "sent" | "failed" | "outcome_unknown"; errorClass?: string; providerMessageId?: string | null; }, ): Promise { return await withRlsContext( db, { accountId: input.organizationId, workspaceId: null }, async (scopedDb) => { await setSubjectRlsContext(scopedDb, input.actorSubjectId); const [row] = await rawRows<{ result: unknown }>( scopedDb, sql`select settle_organization_user_setup_delivery( ${JSON.stringify(input)}::jsonb ) as result`, ); return OrganizationUserSetupDelivery.parse(row?.result); }, ); } export async function previewOrganizationUserSetup( db: Database, tokenDigest: string, ): Promise { const [row] = await rawRows<{ result: unknown }>( db, sql`select preview_organization_user_setup(${tokenDigest}::text) as result`, ); return OrganizationUserSetupPreview.parse(row?.result); } function parseOrganizationUserSetupDeliveryClaim( value: unknown, ): OrganizationUserSetupDeliveryClaim { if (!value || typeof value !== "object" || Array.isArray(value)) { throw new Error("Organization user setup delivery claim returned an invalid result"); } const candidate = value as Record; const delivery = OrganizationUserSetupDelivery.parse(candidate.delivery); if (candidate.claimed !== true) return { claimed: false, delivery }; const workspaceAccess = OrganizationUserSetupPreviewWorkspace.array() .max(100) .safeParse(candidate.sharedWorkspaceAccess); const uuid = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i; if ( typeof candidate.attemptId !== "string" || !uuid.test(candidate.attemptId) || typeof candidate.claimHolderId !== "string" || !uuid.test(candidate.claimHolderId) || typeof candidate.invitationId !== "string" || !uuid.test(candidate.invitationId) || typeof candidate.providerKey !== "string" || typeof candidate.recipientEmail !== "string" || (typeof candidate.recipientName !== "string" && candidate.recipientName !== null) || typeof candidate.organizationName !== "string" || !["owner", "admin", "member"].includes(String(candidate.organizationRole)) || !workspaceAccess.success || typeof candidate.expiresAt !== "string" || (candidate.setupTokenTransport !== null && candidate.setupTokenTransport !== "fragment" && candidate.setupTokenTransport !== "query") || (candidate.payloadDigest !== null && (typeof candidate.payloadDigest !== "string" || !/^[0-9a-f]{64}$/u.test(candidate.payloadDigest))) ) { throw new Error("Organization user setup delivery claim returned an invalid result"); } return { claimed: true, delivery, attemptId: candidate.attemptId, claimHolderId: candidate.claimHolderId, invitationId: candidate.invitationId, providerKey: candidate.providerKey, recipientEmail: candidate.recipientEmail, recipientName: candidate.recipientName, organizationName: candidate.organizationName, organizationRole: candidate.organizationRole as "owner" | "admin" | "member", sharedWorkspaceAccess: workspaceAccess.data, expiresAt: candidate.expiresAt, setupTokenTransport: candidate.setupTokenTransport, payloadDigest: candidate.payloadDigest, }; } export async function completeOrganizationUserSetup( db: Database, input: { tokenDigest: string; operationId: string; requestFingerprint: string; authUserId: string; name: string; passwordHash: string; }, ): Promise { return await db.transaction(async (tx) => { const [row] = await rawRows<{ result: unknown }>( tx, sql`select complete_organization_user_setup( ${JSON.stringify(input)}::jsonb ) as result`, ); return CompleteOrganizationUserSetupResponse.parse(row?.result); }); }