@x12i/keyrox-store-pg 0.1.0 → 0.1.2

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.
Files changed (76) hide show
  1. package/dist/database.d.ts.map +1 -1
  2. package/dist/database.js +2 -0
  3. package/dist/database.js.map +1 -1
  4. package/dist/directory-access-sql.d.ts +12 -0
  5. package/dist/directory-access-sql.d.ts.map +1 -0
  6. package/dist/directory-access-sql.js +253 -0
  7. package/dist/directory-access-sql.js.map +1 -0
  8. package/dist/directory-sql.d.ts +4 -2
  9. package/dist/directory-sql.d.ts.map +1 -1
  10. package/dist/directory-sql.js +832 -30
  11. package/dist/directory-sql.js.map +1 -1
  12. package/dist/hosted-human-sessions.d.ts +5 -0
  13. package/dist/hosted-human-sessions.d.ts.map +1 -0
  14. package/dist/hosted-human-sessions.js +116 -0
  15. package/dist/hosted-human-sessions.js.map +1 -0
  16. package/dist/migrate.d.ts.map +1 -1
  17. package/dist/migrate.js +24 -1
  18. package/dist/migrate.js.map +1 -1
  19. package/dist/notification-deliveries.d.ts +5 -0
  20. package/dist/notification-deliveries.d.ts.map +1 -0
  21. package/dist/notification-deliveries.js +81 -0
  22. package/dist/notification-deliveries.js.map +1 -0
  23. package/dist/notification-webhook-sql.d.ts +4 -0
  24. package/dist/notification-webhook-sql.d.ts.map +1 -0
  25. package/dist/notification-webhook-sql.js +109 -0
  26. package/dist/notification-webhook-sql.js.map +1 -0
  27. package/dist/rows.d.ts +19 -1
  28. package/dist/rows.d.ts.map +1 -1
  29. package/dist/rows.js +168 -4
  30. package/dist/rows.js.map +1 -1
  31. package/dist/sql-store.d.ts.map +1 -1
  32. package/dist/sql-store.js +855 -81
  33. package/dist/sql-store.js.map +1 -1
  34. package/migrations/007_account_sso.sql +40 -0
  35. package/migrations/008_app_sign_in.sql +26 -0
  36. package/migrations/009_account_sso_next.sql +4 -0
  37. package/migrations/010_account_sso_profile.sql +14 -0
  38. package/migrations/011_hosted_sso_profiles.sql +26 -0
  39. package/migrations/012_app_signup_roles.sql +2 -0
  40. package/migrations/013_product_role_catalog.sql +14 -0
  41. package/migrations/014_application_staff_access.sql +21 -0
  42. package/migrations/015_audit_service_actor.sql +7 -0
  43. package/migrations/016_app_waitlist_questions.sql +2 -0
  44. package/migrations/017_app_signup_policy.sql +9 -0
  45. package/migrations/018_managed_app_sign_in.sql +8 -0
  46. package/migrations/019_hosted_sso_email_proofs.sql +12 -0
  47. package/migrations/020_cli_login_codes.sql +15 -0
  48. package/migrations/021_hosted_email_codes.sql +18 -0
  49. package/migrations/022_sso_waitlist_callback.sql +3 -0
  50. package/migrations/023_app_email_code_sign_in.sql +1 -0
  51. package/migrations/024_hosted_auth_copy.sql +2 -0
  52. package/migrations/025_app_directory_workspaces.sql +55 -0
  53. package/migrations/027_role_features_and_configuration.sql +17 -0
  54. package/migrations/028_sso_only_signup_audience.sql +4 -0
  55. package/migrations/029_people_only_directory_model.sql +3 -0
  56. package/migrations/030_typed_questionnaires.sql +3 -0
  57. package/migrations/031_app_notifications.sql +22 -0
  58. package/migrations/032_agent_grant_duration.sql +10 -0
  59. package/migrations/033_application_lifecycle.sql +67 -0
  60. package/migrations/034_notification_deliveries.sql +25 -0
  61. package/migrations/035_app_notification_webhook_jobs.sql +28 -0
  62. package/migrations/036_account_notification_recovery.sql +11 -0
  63. package/migrations/037_waitlist_confirmation.sql +7 -0
  64. package/migrations/039_hosted_human_sessions.sql +45 -0
  65. package/migrations/040_hosted_human_clients.sql +35 -0
  66. package/migrations/041_app_workspace_invitations.sql +9 -0
  67. package/migrations/042_directory_email_proof.sql +16 -0
  68. package/migrations/043_sso_exchange_redirect_uri.sql +1 -0
  69. package/migrations/044_repair_app_sign_in_connections.sql +30 -0
  70. package/migrations/045_directory_integrity.sql +140 -0
  71. package/migrations/046_person_email_across_organizations.sql +7 -0
  72. package/migrations/047_owner_access.sql +35 -0
  73. package/migrations/048_invitation_links.sql +28 -0
  74. package/migrations/049_password_change_required.sql +6 -0
  75. package/migrations/050_jwt_profiles.sql +9 -0
  76. package/package.json +3 -3
package/dist/sql-store.js CHANGED
@@ -1,6 +1,9 @@
1
- import { asTime, asTimeOrNull, decideLongLived, effectiveActions, isExpired, StoreError, } from "@x12i/keyrox-store";
2
- import { createSqlDirectory } from "./directory-sql.js";
3
- import { agentOf, applicationOf, appTokenOf, environmentOf, auditOf, authorizationOf, challengeOf, clientOf, deniedOf, grantOf, gatewayRouteOf, idempotencyOf, inviteOf, longTokenOf, membershipOf, orgOf, principalOf, providerOf, refreshOf, roleOf, serviceCredentialOf, sessionOf, signInOf, ssoExchangeOf, ssoLoginOf, trustOf, userOf, workloadCredentialOf, audienceOf, assignmentOf, } from "./rows.js";
1
+ import { appIdFromTenantResource, applicationLifecycleTime, applicationMoveKeys, asTime, asTimeOrNull, decideLongLived, effectiveActions, hostedEmailCodePolicy, isExpired, StoreError, verifyApplicationTrashSnapshot, } from "@x12i/keyrox-store";
2
+ import { createSqlDirectory, repairDirectoryStructure } from "./directory-sql.js";
3
+ import { createSqlHostedHumanSessions, pruneSqlHostedHumanCredentials } from "./hosted-human-sessions.js";
4
+ import { createSqlNotificationWebhookJobs } from "./notification-webhook-sql.js";
5
+ import { createSqlNotificationDeliveries, insertSqlNotificationDelivery } from "./notification-deliveries.js";
6
+ import { agentOf, applicationOf, trashedApplicationOf, applicationStaffAccessOf, appTokenOf, environmentOf, notificationSettingsOf, notificationWebhookOf, auditOf, authorizationOf, challengeOf, clientOf, deniedOf, grantOf, gatewayRouteOf, idempotencyOf, inviteOf, longTokenOf, membershipOf, orgOf, principalOf, providerOf, refreshOf, roleOf, serviceCredentialOf, sessionOf, accountHandoffOf, accountIdentityOf, accountSsoLoginOf, accountSsoProfileOf, cliLoginCodeOf, platformSignInOf, signInOf, hostedEmailCodeOf, hostedHumanClientOf, hostedHumanCodeOf, hostedSsoProfileOf, ssoExchangeOf, ssoLoginOf, trustOf, userOf, workloadCredentialOf, audienceOf, assignmentOf, } from "./rows.js";
4
7
  async function rows(sql, text, values = []) {
5
8
  const result = await sql.query(text, values);
6
9
  return result.rows;
@@ -9,6 +12,32 @@ async function first(sql, text, values, map) {
9
12
  const found = await rows(sql, text, values);
10
13
  return found[0] ? map(found[0]) : null;
11
14
  }
15
+ async function writeEmailChallenge(sql, row) {
16
+ await sql.query(`INSERT INTO email_challenges (id, user_id, purpose, token_hash, expires_at, used_at, created_at)
17
+ VALUES ($1, $2, $3, $4, $5::timestamptz, $6::timestamptz, $7::timestamptz)`, [row.id, row.userId, row.purpose, row.tokenHash, asTime(row.expiresAt), asTimeOrNull(row.usedAt), asTime(row.createdAt)]);
18
+ }
19
+ async function checkPendingInvite(sql, row, at) {
20
+ const conflicts = await rows(sql, `SELECT id FROM invites WHERE org_id = $1 AND lower(email) = lower($2) AND id <> $3
21
+ AND accepted_at IS NULL AND revoked_at IS NULL AND expires_at > $4::timestamptz LIMIT 1`, [row.orgId, row.email, row.id, asTime(at)]);
22
+ if (conflicts.length)
23
+ throw new StoreError("invite_pending", "An open invitation already exists.");
24
+ }
25
+ async function lockHostedSsoEmailProfile(sql, challengeHash, browserHash, at) {
26
+ if (!await lockHostedSsoApplication(sql, challengeHash, browserHash))
27
+ return null;
28
+ return first(sql, `SELECT * FROM hosted_sso_profiles
29
+ WHERE challenge_hash = $1 AND browser_hash = $2 AND expires_at > $3::timestamptz AND email IS NULL FOR UPDATE`, [challengeHash, browserHash, at], hostedSsoProfileOf);
30
+ }
31
+ async function lockHostedSsoApplication(sql, challengeHash, browserHash) {
32
+ const scope = await rows(sql, `SELECT app.id FROM hosted_sso_profiles profile JOIN applications app ON app.id = profile.app_id
33
+ WHERE profile.challenge_hash = $1 AND profile.browser_hash = $2 AND profile.org_id = app.org_id
34
+ AND app.trashed_at IS NULL FOR SHARE OF app`, [challengeHash, browserHash]);
35
+ return scope.length > 0;
36
+ }
37
+ async function writeAudit(sql, row) {
38
+ await sql.query(`INSERT INTO audit_events (id, at, org_id, actor_user_id, agent_id, audience, action, decision, target, detail, actor_service_id)
39
+ VALUES ($1, $2::timestamptz, $3, $4, $5, $6, $7, $8, $9, $10, $11)`, [row.id, asTime(row.at), row.orgId, row.actorUserId, row.agentId, row.audience, row.action, row.decision, row.target, row.detail, row.actorServiceId ?? null]);
40
+ }
12
41
  async function revokeGrant(sql, id, at) {
13
42
  const grant = await first(sql, "SELECT * FROM delegation_grants WHERE id = $1 FOR UPDATE", [id], grantOf);
14
43
  if (!grant)
@@ -22,9 +51,101 @@ async function revokeGrant(sql, id, at) {
22
51
  await sql.query("UPDATE refresh_tokens SET revoked_at = $2::timestamptz WHERE grant_id = $1 AND revoked_at IS NULL", [id, grant.revokedAt]);
23
52
  return { grant, changed };
24
53
  }
54
+ async function insertAccountIdentity(sql, row) {
55
+ await sql.query("INSERT INTO account_identities (id, user_id, provider, subject, email, created_at) VALUES ($1, $2, $3, $4, $5, $6::timestamptz)", [row.id, row.userId, row.provider, row.subject, row.email, asTime(row.createdAt)]);
56
+ }
57
+ async function retireLegacyAppSignIn(sql, appId, provider) {
58
+ await sql.query("UPDATE app_sign_in SET providers = array_remove(providers, $2) WHERE app_id = $1 AND $2 = ANY(providers)", [appId, provider]);
59
+ }
60
+ async function lockApplicationTenant(sql, orgId) {
61
+ const tenant = await rows(sql, "SELECT id FROM orgs WHERE id = $1 FOR NO KEY UPDATE", [orgId]);
62
+ if (!tenant.length)
63
+ throw new StoreError("not_found", "Tenant not found.");
64
+ }
65
+ async function assertApplicationScope(sql, appId, orgId, code = "not_found") {
66
+ const app = await rows(sql, `SELECT id FROM applications WHERE id = $1 AND org_id = $2 AND trashed_at IS NULL FOR SHARE`, [appId, orgId]);
67
+ if (!app.length)
68
+ throw new StoreError(code, "Application not found in this tenant.");
69
+ }
70
+ async function ensureAnotherNotificationWebhook(sql, environmentId, webhookId) {
71
+ const last = await rows(sql, `SELECT hook.id FROM app_notification_webhooks hook
72
+ JOIN app_notification_settings settings ON settings.environment_id = hook.environment_id
73
+ WHERE hook.environment_id = $1 AND hook.id = $2 AND hook.enabled AND settings.delivery = 'webhook'
74
+ AND NOT EXISTS (SELECT 1 FROM app_notification_webhooks other
75
+ WHERE other.environment_id = $1 AND other.id <> $2 AND other.enabled)`, [environmentId, webhookId]);
76
+ if (last.length)
77
+ throw new StoreError("conflict", "webhook_required");
78
+ }
79
+ async function removeApplicationTenantAccess(sql, orgId, appId, at) {
80
+ const path = `/tenants/${orgId}/apps/${appId}`;
81
+ await sql.query("DELETE FROM app_staff_access WHERE app_id = $1", [appId]);
82
+ await sql.query(`DELETE FROM role_assignments WHERE org_id = $1 AND (scope = $2 OR starts_with(scope, $2 || '/'))`, [orgId, path]);
83
+ await sql.query(`UPDATE service_credentials SET
84
+ revoked_at = CASE WHEN cardinality(array_remove(app_ids, $2)) = 0 THEN COALESCE(revoked_at, $3::timestamptz) ELSE revoked_at END,
85
+ app_ids = CASE WHEN cardinality(array_remove(app_ids, $2)) > 0 THEN array_remove(app_ids, $2) ELSE app_ids END
86
+ WHERE org_id = $1 AND $2 = ANY(app_ids)`, [orgId, appId, at]);
87
+ }
88
+ async function purgeApplication(sql, app) {
89
+ await removeApplicationTenantAccess(sql, app.orgId, app.id, app.trashedAt);
90
+ await sql.query("INSERT INTO application_logo_purge (app_id) VALUES ($1) ON CONFLICT DO NOTHING", [app.id]);
91
+ await sql.query("DELETE FROM gateway_routes WHERE org_id = $1 AND rtrim(resource, '/') = $2", [app.orgId, `/tenants/${app.orgId}/apps/${app.id}`]);
92
+ await sql.query("DELETE FROM sso_exchanges WHERE app_id = $1", [app.id]);
93
+ await sql.query("DELETE FROM app_waitlist WHERE app_id = $1", [app.id]);
94
+ await sql.query("DELETE FROM directory_challenges WHERE environment_id IN (SELECT id FROM app_environments WHERE app_id = $1)", [app.id]);
95
+ await sql.query("DELETE FROM applications WHERE id = $1 AND org_id = $2 AND trashed_at IS NOT NULL", [app.id, app.orgId]);
96
+ }
97
+ async function insertApp(sql, row) {
98
+ await sql.query(`INSERT INTO applications (
99
+ id, org_id, title, description, status, allowed_scopes, allowed_features, created_at, updated_at, signup_mode, waitlist_questions,
100
+ signup_audience, signup_sso_providers, signup_organization, managed_sign_in, email_code_sign_in, auth_copy,
101
+ directory_model, directory_labels, onboarding, waitlist_question_definitions, waitlist_question_layout
102
+ ) VALUES (
103
+ $1, $2, $3, $4, $5, $6::text[], $7::text[], $8::timestamptz, $9::timestamptz, $10, $11::text[], $12, $13::text[], $14, $15, $16, $17::jsonb,
104
+ $18, $19::jsonb, $20::jsonb, $21::jsonb, $22
105
+ )`, [
106
+ row.id, row.orgId, row.title, row.description, row.status, row.allowedScopes, row.allowedFeatures, asTime(row.createdAt), asTime(row.updatedAt), row.signupMode ?? "open",
107
+ row.waitlistQuestionDefinitions?.map(({ prompt }) => prompt) ?? row.waitlistQuestions ?? [],
108
+ row.signupAudience ?? "any-email", row.signupSsoProviders ?? [], row.signupOrganization ?? "required",
109
+ row.managedSignIn ?? true, row.emailCodeSignIn ?? false, JSON.stringify(row.authCopy ?? {}),
110
+ row.directoryModel ?? "organizations", JSON.stringify(row.directoryLabels ?? {}), JSON.stringify(row.onboarding ?? {}),
111
+ row.waitlistQuestionDefinitions == null ? null : JSON.stringify(row.waitlistQuestionDefinitions), row.waitlistQuestionLayout ?? "form",
112
+ ]);
113
+ }
114
+ const ssoExchangeQuery = `SELECT exchange.* FROM sso_exchanges exchange
115
+ JOIN app_tokens token ON token.id = exchange.token_id AND token.app_id = exchange.app_id AND token.environment_id = exchange.environment_id
116
+ JOIN applications app ON app.id = token.app_id AND app.org_id = token.org_id
117
+ WHERE exchange.code_hash = $1 AND exchange.expires_at > $2::timestamptz AND app.trashed_at IS NULL AND token.revoked_at IS NULL`;
118
+ async function insertAppEnvironment(sql, row) {
119
+ await assertApplicationScope(sql, row.appId, row.orgId);
120
+ await sql.query(`INSERT INTO app_environments (
121
+ id, app_id, org_id, name, title, status, secret_enc, secret_hash, key_version,
122
+ previous_secret_enc, previous_secret_hash, previous_key_version, previous_key_expires_at, created_at, updated_at
123
+ ) VALUES (
124
+ $1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13::timestamptz, $14::timestamptz, $15::timestamptz
125
+ )`, [
126
+ row.id, row.appId, row.orgId, row.name, row.title, row.status, row.secretEnc, row.secretHash, row.keyVersion,
127
+ row.previousSecretEnc, row.previousSecretHash, row.previousKeyVersion, asTimeOrNull(row.previousKeyExpiresAt), asTime(row.createdAt), asTime(row.updatedAt),
128
+ ]);
129
+ }
130
+ async function saveStaffAccess(sql, row) {
131
+ if (typeof row.design !== "boolean")
132
+ throw new StoreError("conflict", "Invalid application staff access level.");
133
+ await assertApplicationScope(sql, row.appId, row.orgId, "conflict");
134
+ const saved = await first(sql, `INSERT INTO app_staff_access (id, org_id, app_id, environment_id, user_id, design, runtime, created_at, updated_at)
135
+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8::timestamptz, $9::timestamptz)
136
+ ON CONFLICT (environment_id, user_id) DO UPDATE SET
137
+ design = EXCLUDED.design, runtime = EXCLUDED.runtime, updated_at = EXCLUDED.updated_at
138
+ WHERE app_staff_access.org_id = EXCLUDED.org_id AND app_staff_access.app_id = EXCLUDED.app_id
139
+ RETURNING *`, [row.id, row.orgId, row.appId, row.environmentId, row.userId, row.design, row.runtime, asTime(row.createdAt), asTime(row.updatedAt)], applicationStaffAccessOf);
140
+ if (!saved)
141
+ throw new StoreError("conflict", "Application staff access must match the tenant, application, and environment.");
142
+ return saved;
143
+ }
25
144
  export function createSqlStore(database) {
26
145
  const tx = (run) => database.transaction(run);
27
146
  const store = {
147
+ ...createSqlNotificationDeliveries(database),
148
+ ...createSqlHostedHumanSessions(database),
28
149
  signup(input) {
29
150
  return tx(async (sql) => {
30
151
  const user = { ...input.user, emailVerifiedAt: asTimeOrNull(input.user.emailVerifiedAt), disabledAt: asTimeOrNull(input.user.disabledAt), createdAt: asTime(input.user.createdAt) };
@@ -33,17 +154,40 @@ export function createSqlStore(database) {
33
154
  if (membership.userId !== user.id || membership.orgId !== org.id || membership.role !== "owner") {
34
155
  throw new StoreError("conflict", "Signup requires the new organization and its owner membership.");
35
156
  }
157
+ if (input.platformAdmissionTokenHash) {
158
+ const invitation = await rows(sql, `UPDATE platform_waitlist SET status = 'admitted'
159
+ WHERE token_hash = $1 AND lower(email) = lower($2) AND status = 'invited' RETURNING id`, [input.platformAdmissionTokenHash, user.email]);
160
+ if (!invitation.length)
161
+ throw new StoreError("challenge_invalid", "Waiting list invitation is no longer available.");
162
+ const used = await rows(sql, `UPDATE directory_challenges SET used_at = $3::timestamptz WHERE token_hash = $1
163
+ AND environment_id = 'platform' AND lower(email) = lower($2) AND purpose = 'admit'
164
+ AND used_at IS NULL AND expires_at > $3::timestamptz RETURNING id`, [input.platformAdmissionTokenHash, user.email, user.createdAt]);
165
+ if (!used.length)
166
+ throw new StoreError("challenge_invalid", "Waiting list invitation is no longer available.");
167
+ }
36
168
  const email = await rows(sql, "SELECT id FROM users WHERE lower(email) = lower($1)", [user.email]);
37
169
  if (email.length)
38
170
  throw new StoreError("duplicate_email", "Email already exists.");
39
171
  const slug = await rows(sql, "SELECT id FROM orgs WHERE slug = $1", [org.slug]);
40
172
  if (slug.length)
41
173
  throw new StoreError("duplicate_slug", "Slug already exists.");
42
- await sql.query(`INSERT INTO users (id, email, password_hash, display_name, email_verified_at, disabled_at, created_at, last_org_id)
43
- VALUES ($1, $2, $3, $4, $5::timestamptz, $6::timestamptz, $7::timestamptz, $8)`, [user.id, user.email, user.passwordHash, user.displayName, user.emailVerifiedAt, user.disabledAt, user.createdAt, user.lastOrgId ?? null]);
174
+ await sql.query(`INSERT INTO users (id, email, password_hash, display_name, email_verified_at, disabled_at, created_at, last_org_id, password_change_required)
175
+ VALUES ($1, $2, $3, $4, $5::timestamptz, $6::timestamptz, $7::timestamptz, $8, $9)`, [user.id, user.email, user.passwordHash, user.displayName, user.emailVerifiedAt, user.disabledAt, user.createdAt, user.lastOrgId ?? null, user.passwordChangeRequired === true]);
44
176
  await sql.query(`INSERT INTO orgs (id, slug, name, personal, allow_never_expire, allow_device_flow, grant_max_days, policy_version, created_at)
45
177
  VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9::timestamptz)`, [org.id, org.slug, org.name, org.personal, org.policy.allowNeverExpire, org.policy.allowDeviceFlow, org.policy.grantMaxDays, org.policy.version, org.createdAt]);
46
178
  await sql.query(`INSERT INTO memberships (id, org_id, user_id, role, actions, created_at, production_access) VALUES ($1, $2, $3, $4, $5::text[], $6::timestamptz, $7)`, [membership.id, membership.orgId, membership.userId, membership.role, membership.actions, membership.createdAt, true]);
179
+ if (input.accountIdentity) {
180
+ if (input.accountIdentity.userId !== user.id)
181
+ throw new StoreError("conflict", "The sign-in identity must belong to the new user.");
182
+ await insertAccountIdentity(sql, input.accountIdentity);
183
+ }
184
+ if (input.verification) {
185
+ const { challenge, delivery } = input.verification;
186
+ if (challenge.userId !== user.id || challenge.purpose !== "verify")
187
+ throw new StoreError("conflict", "The verification challenge must belong to the new user.");
188
+ await writeEmailChallenge(sql, challenge);
189
+ await insertSqlNotificationDelivery(sql, delivery);
190
+ }
47
191
  });
48
192
  },
49
193
  createOrg(input) {
@@ -70,7 +214,7 @@ export function createSqlStore(database) {
70
214
  return tx(async (sql) => {
71
215
  const next = { ...user, emailVerifiedAt: asTimeOrNull(user.emailVerifiedAt), disabledAt: asTimeOrNull(user.disabledAt), createdAt: asTime(user.createdAt) };
72
216
  const updated = await rows(sql, `UPDATE users SET email = $2, password_hash = $3, display_name = $4, email_verified_at = $5::timestamptz,
73
- disabled_at = $6::timestamptz, created_at = $7::timestamptz, last_org_id = $8 WHERE id = $1 RETURNING id`, [next.id, next.email, next.passwordHash, next.displayName, next.emailVerifiedAt, next.disabledAt, next.createdAt, next.lastOrgId ?? null]);
217
+ disabled_at = $6::timestamptz, created_at = $7::timestamptz, last_org_id = $8, password_change_required = $9 WHERE id = $1 RETURNING id`, [next.id, next.email, next.passwordHash, next.displayName, next.emailVerifiedAt, next.disabledAt, next.createdAt, next.lastOrgId ?? null, next.passwordChangeRequired === true]);
74
218
  if (!updated.length)
75
219
  throw new StoreError("not_found", "User not found.");
76
220
  });
@@ -125,19 +269,33 @@ export function createSqlStore(database) {
125
269
  });
126
270
  },
127
271
  insertChallenge(row) {
272
+ return tx((sql) => writeEmailChallenge(sql, row));
273
+ },
274
+ reserveAccountChallenge(row, cooldownSince, delivery) {
128
275
  return tx(async (sql) => {
129
- await sql.query(`INSERT INTO email_challenges (id, user_id, purpose, token_hash, expires_at, used_at, created_at)
130
- VALUES ($1, $2, $3, $4, $5::timestamptz, $6::timestamptz, $7::timestamptz)`, [row.id, row.userId, row.purpose, row.tokenHash, asTime(row.expiresAt), asTimeOrNull(row.usedAt), asTime(row.createdAt)]);
276
+ const account = await first(sql, "SELECT * FROM users WHERE id = $1 FOR UPDATE", [row.userId], userOf);
277
+ if (!account || account.disabledAt || (row.purpose === "verify" && account.emailVerifiedAt))
278
+ return false;
279
+ const recent = await rows(sql, `SELECT id FROM email_challenges WHERE user_id = $1 AND purpose = $2
280
+ AND created_at > $3::timestamptz LIMIT 1`, [row.userId, row.purpose, asTime(cooldownSince)]);
281
+ if (recent.length)
282
+ return false;
283
+ await writeEmailChallenge(sql, row);
284
+ await insertSqlNotificationDelivery(sql, delivery);
285
+ return true;
131
286
  });
132
287
  },
133
288
  verifyEmail(tokenHash, at) {
134
289
  return tx(async (sql) => {
135
290
  const stamp = asTime(at);
136
- const mapped = await first(sql, "SELECT * FROM email_challenges WHERE token_hash = $1 AND purpose = 'verify' FOR UPDATE", [tokenHash], challengeOf);
137
- if (!mapped || mapped.usedAt || isExpired(mapped.expiresAt, stamp))
291
+ const candidate = await first(sql, "SELECT * FROM email_challenges WHERE token_hash = $1 AND purpose = 'verify'", [tokenHash], challengeOf);
292
+ if (!candidate)
138
293
  throw new StoreError("challenge_invalid", "Verification link is no longer valid.");
139
- const account = await first(sql, "SELECT * FROM users WHERE id = $1 FOR UPDATE", [mapped.userId], userOf);
140
- if (!account)
294
+ const account = await first(sql, "SELECT * FROM users WHERE id = $1 FOR UPDATE", [candidate.userId], userOf);
295
+ if (!account || account.disabledAt || account.emailVerifiedAt)
296
+ throw new StoreError("challenge_invalid", "Verification link is no longer valid.");
297
+ const mapped = await first(sql, "SELECT * FROM email_challenges WHERE id = $1 FOR UPDATE", [candidate.id], challengeOf);
298
+ if (!mapped || mapped.usedAt || isExpired(mapped.expiresAt, stamp))
141
299
  throw new StoreError("challenge_invalid", "Verification link is no longer valid.");
142
300
  await sql.query("UPDATE users SET email_verified_at = $2::timestamptz WHERE id = $1", [account.id, stamp]);
143
301
  await sql.query("UPDATE email_challenges SET used_at = $2::timestamptz WHERE id = $1", [mapped.id, stamp]);
@@ -147,31 +305,88 @@ export function createSqlStore(database) {
147
305
  resetPassword(input) {
148
306
  return tx(async (sql) => {
149
307
  const stamp = asTime(input.at);
150
- const mapped = await first(sql, "SELECT * FROM email_challenges WHERE token_hash = $1 AND purpose = 'reset' FOR UPDATE", [input.tokenHash], challengeOf);
151
- if (!mapped || mapped.usedAt || isExpired(mapped.expiresAt, stamp))
308
+ const candidate = await first(sql, "SELECT * FROM email_challenges WHERE token_hash = $1 AND purpose = 'reset'", [input.tokenHash], challengeOf);
309
+ if (!candidate)
152
310
  throw new StoreError("challenge_invalid", "Reset link is no longer valid.");
153
- const account = await first(sql, "SELECT * FROM users WHERE id = $1 FOR UPDATE", [mapped.userId], userOf);
154
- if (!account)
311
+ const account = await first(sql, "SELECT * FROM users WHERE id = $1 FOR UPDATE", [candidate.userId], userOf);
312
+ if (!account || account.disabledAt)
313
+ throw new StoreError("challenge_invalid", "Reset link is no longer valid.");
314
+ const mapped = await first(sql, "SELECT * FROM email_challenges WHERE id = $1 FOR UPDATE", [candidate.id], challengeOf);
315
+ if (!mapped || mapped.usedAt || isExpired(mapped.expiresAt, stamp))
155
316
  throw new StoreError("challenge_invalid", "Reset link is no longer valid.");
156
317
  const verified = account.emailVerifiedAt ?? stamp;
157
- await sql.query("UPDATE users SET password_hash = $2, email_verified_at = $3::timestamptz WHERE id = $1", [account.id, input.passwordHash, verified]);
158
- await sql.query("UPDATE email_challenges SET used_at = $2::timestamptz WHERE id = $1", [mapped.id, stamp]);
318
+ await sql.query("UPDATE users SET password_hash = $2, email_verified_at = $3::timestamptz, password_change_required = false WHERE id = $1", [account.id, input.passwordHash, verified]);
319
+ await sql.query("UPDATE email_challenges SET used_at = $2::timestamptz WHERE user_id = $1 AND purpose = 'reset' AND used_at IS NULL", [account.id, stamp]);
159
320
  await sql.query("DELETE FROM sessions WHERE user_id = $1", [account.id]);
160
- return { ...account, passwordHash: input.passwordHash, emailVerifiedAt: verified };
321
+ return { ...account, passwordHash: input.passwordHash, emailVerifiedAt: verified, passwordChangeRequired: false };
161
322
  });
162
323
  },
163
- insertInvite(row) {
324
+ prepareAccountPasswordChange: (tokenHash, at) => tx(async (sql) => {
325
+ const stamp = asTime(at);
326
+ const challenge = await first(sql, "SELECT * FROM email_challenges WHERE token_hash = $1 AND purpose = 'password-change'", [tokenHash], challengeOf);
327
+ if (!challenge || challenge.usedAt || isExpired(challenge.expiresAt, stamp))
328
+ return null;
329
+ const account = await first(sql, "SELECT * FROM users WHERE id = $1", [challenge.userId], userOf);
330
+ if (!account || account.disabledAt || !account.passwordHash)
331
+ return null;
332
+ return account;
333
+ }),
334
+ commitAccountPasswordChange: (input) => tx(async (sql) => {
335
+ const stamp = asTime(input.at);
336
+ const challenge = await first(sql, "SELECT * FROM email_challenges WHERE token_hash = $1 AND purpose = 'password-change' FOR UPDATE", [input.tokenHash], challengeOf);
337
+ if (!challenge || challenge.usedAt || isExpired(challenge.expiresAt, stamp))
338
+ return null;
339
+ const account = await first(sql, `UPDATE users SET password_hash = $2, password_change_required = false
340
+ WHERE id = $1 AND disabled_at IS NULL AND password_hash IS NOT NULL RETURNING *`, [challenge.userId, input.passwordHash], userOf);
341
+ if (!account)
342
+ return null;
343
+ await sql.query("UPDATE email_challenges SET used_at = $2::timestamptz WHERE id = $1 AND used_at IS NULL", [challenge.id, stamp]);
344
+ return { ...account, passwordHash: input.passwordHash, passwordChangeRequired: false };
345
+ }),
346
+ insertInvite(row, delivery) {
164
347
  return tx(async (sql) => {
165
- await sql.query(`INSERT INTO invites (id, org_id, email, role, actions, token_hash, invited_by, expires_at, accepted_at, created_at, production_access)
166
- VALUES ($1, $2, $3, $4, $5::text[], $6, $7, $8::timestamptz, $9::timestamptz, $10::timestamptz, $11)`, [row.id, row.orgId, row.email, row.role, row.actions, row.tokenHash, row.invitedBy, asTime(row.expiresAt), asTimeOrNull(row.acceptedAt), asTime(row.createdAt), row.productionAccess === true]);
348
+ await sql.query("SELECT id FROM orgs WHERE id = $1 FOR NO KEY UPDATE", [row.orgId]);
349
+ await checkPendingInvite(sql, row, row.createdAt);
350
+ await sql.query(`INSERT INTO invites (id, org_id, email, role, actions, token_hash, invited_by, expires_at, accepted_at, created_at, production_access, revoked_at, last_mail_requested_at)
351
+ VALUES ($1, $2, $3, $4, $5::text[], $6, $7, $8::timestamptz, $9::timestamptz, $10::timestamptz, $11, $12::timestamptz, $13::timestamptz)`, [row.id, row.orgId, row.email, row.role, row.actions, row.tokenHash, row.invitedBy, asTime(row.expiresAt), asTimeOrNull(row.acceptedAt), asTime(row.createdAt), row.productionAccess === true, asTimeOrNull(row.revokedAt ?? null), asTimeOrNull(row.lastMailRequestedAt ?? null)]);
352
+ await insertSqlNotificationDelivery(sql, delivery);
353
+ });
354
+ },
355
+ listOpenInvites(orgId, limit, beforeId) {
356
+ return tx(async (sql) => (await rows(sql, `SELECT invite.* FROM invites invite
357
+ WHERE invite.org_id = $1 AND invite.accepted_at IS NULL AND invite.revoked_at IS NULL
358
+ AND ($3::text IS NULL OR (invite.created_at, invite.id COLLATE "C") <
359
+ (SELECT cursor.created_at, cursor.id COLLATE "C" FROM invites cursor WHERE cursor.org_id = $1 AND cursor.id = $3))
360
+ ORDER BY invite.created_at DESC, invite.id COLLATE "C" DESC LIMIT $2`, [orgId, limit, beforeId ?? null])).map(inviteOf));
361
+ },
362
+ getOrgInvite(orgId, inviteId) {
363
+ return tx((sql) => first(sql, "SELECT * FROM invites WHERE org_id = $1 AND id = $2", [orgId, inviteId], inviteOf));
364
+ },
365
+ rotateInvite(input) {
366
+ return tx(async (sql) => {
367
+ await sql.query("SELECT id FROM orgs WHERE id = $1 FOR NO KEY UPDATE", [input.orgId]);
368
+ const row = await first(sql, `SELECT * FROM invites WHERE org_id = $1 AND id = $2 AND accepted_at IS NULL
369
+ AND revoked_at IS NULL AND COALESCE(last_mail_requested_at, created_at) <= $3::timestamptz FOR UPDATE`, [input.orgId, input.inviteId, asTime(input.cooldownSince)], inviteOf);
370
+ if (!row)
371
+ return null;
372
+ await checkPendingInvite(sql, row, input.at);
373
+ const rotated = await first(sql, `UPDATE invites SET token_hash = $2, expires_at = $3::timestamptz,
374
+ last_mail_requested_at = $4::timestamptz WHERE id = $1 RETURNING *`, [row.id, input.tokenHash, asTime(input.expiresAt), asTime(input.at)], inviteOf);
375
+ if (rotated)
376
+ await insertSqlNotificationDelivery(sql, input.delivery);
377
+ return rotated;
167
378
  });
168
379
  },
380
+ revokeInvite(orgId, inviteId, at) {
381
+ return tx(async (sql) => (await rows(sql, `UPDATE invites SET revoked_at = $3::timestamptz WHERE org_id = $1 AND id = $2
382
+ AND accepted_at IS NULL AND revoked_at IS NULL RETURNING id`, [orgId, inviteId, asTime(at)])).length > 0);
383
+ },
169
384
  acceptInvite(input) {
170
385
  return tx(async (sql) => {
171
386
  const at = asTime(input.at);
172
387
  await sql.query("SELECT id FROM users WHERE id = $1 FOR UPDATE", [input.userId]);
173
388
  const invite = await first(sql, "SELECT * FROM invites WHERE token_hash = $1 FOR UPDATE", [input.tokenHash], inviteOf);
174
- if (!invite || invite.acceptedAt || isExpired(invite.expiresAt, at))
389
+ if (!invite || invite.acceptedAt || invite.revokedAt || isExpired(invite.expiresAt, at))
175
390
  throw new StoreError("invite_invalid", "Invite is no longer valid.");
176
391
  const account = await first(sql, "SELECT * FROM users WHERE id = $1", [input.userId], userOf);
177
392
  if (!account)
@@ -394,20 +609,21 @@ export function createSqlStore(database) {
394
609
  getTrust: (id) => tx((sql) => first(sql, "SELECT * FROM workload_trusts WHERE id = $1", [id], trustOf)),
395
610
  listTrusts: (issuer, audience) => tx(async (sql) => (await rows(sql, "SELECT * FROM workload_trusts WHERE issuer = $1 AND audience = $2 ORDER BY created_at, id", [issuer, audience])).map(trustOf)),
396
611
  insertAudit(row) {
397
- return tx(async (sql) => {
398
- await sql.query(`INSERT INTO audit_events (id, at, org_id, actor_user_id, agent_id, audience, action, decision, target, detail)
399
- VALUES ($1, $2::timestamptz, $3, $4, $5, $6, $7, $8, $9, $10)`, [row.id, asTime(row.at), row.orgId, row.actorUserId, row.agentId, row.audience, row.action, row.decision, row.target, row.detail]);
400
- });
612
+ return tx((sql) => writeAudit(sql, row));
401
613
  },
402
614
  listAudit: (query) => tx(async (sql) => (await rows(sql, `SELECT * FROM audit_events
403
615
  WHERE org_id = $1
404
616
  AND ($2::text IS NULL OR action = $2)
405
- AND ($3::text IS NULL OR actor_user_id = $3 OR target = $3)
406
- AND ($4::text IS NULL OR detail LIKE '%' || $4 || '%')
617
+ AND ($3::text IS NULL OR actor_user_id = $3 OR actor_service_id = $3 OR agent_id = $3 OR target = $3)
618
+ AND ($4::text IS NULL OR detail = $4 OR left(detail, length($4) + 1) = $4 || ' ')
407
619
  AND ($5::timestamptz IS NULL OR at >= $5::timestamptz)
408
620
  AND ($6::timestamptz IS NULL OR at <= $6::timestamptz)
409
- ORDER BY at DESC, id DESC LIMIT $7 OFFSET $8`, [
621
+ AND ($9::text IS NULL OR actor_user_id = $9)
622
+ AND ($10::text IS NULL OR decision = $10)
623
+ AND ($11::timestamptz IS NULL OR (at, id COLLATE "C") < ($11::timestamptz, $12::text COLLATE "C"))
624
+ ORDER BY at DESC, id COLLATE "C" DESC LIMIT $7 OFFSET $8`, [
410
625
  query.orgId, query.action ?? null, query.subject ?? null, query.source ? `source=${query.source}` : null, query.from ?? null, query.to ?? null, query.limit, query.offset,
626
+ query.actorUserId ?? null, query.decision ?? null, query.before?.at ?? null, query.before?.id ?? null,
411
627
  ])).map(auditOf)),
412
628
  getDeniedJti: (id) => tx((sql) => first(sql, "SELECT * FROM denied_jtis WHERE id = $1", [id], deniedOf)),
413
629
  denyJti: (row) => tx(async (sql) => { await sql.query("INSERT INTO denied_jtis (id, exp) VALUES ($1, $2) ON CONFLICT (id) DO NOTHING", [row.id, row.exp]); }),
@@ -417,63 +633,320 @@ export function createSqlStore(database) {
417
633
  await sql.query("INSERT INTO idempotency_records (id, request_hash, status, body, created_at) VALUES ($1, $2, $3, $4, $5::timestamptz)", [row.id, row.requestHash, row.status, row.body, asTime(row.createdAt)]);
418
634
  });
419
635
  },
420
- insertApplication(row) {
636
+ insertApplication: (row) => tx((sql) => insertApp(sql, row)),
637
+ registerApplication({ application, environments, creatorAccess, audit }) {
421
638
  return tx(async (sql) => {
422
- await sql.query(`INSERT INTO applications (
423
- id, org_id, title, description, status, allowed_scopes, allowed_features, created_at, updated_at
424
- ) VALUES (
425
- $1, $2, $3, $4, $5, $6::text[], $7::text[], $8::timestamptz, $9::timestamptz
426
- )`, [
427
- row.id, row.orgId, row.title, row.description, row.status, row.allowedScopes, row.allowedFeatures, asTime(row.createdAt), asTime(row.updatedAt),
428
- ]);
639
+ if (!environments.length || environments.some((row) => row.appId !== application.id || row.orgId !== application.orgId)) {
640
+ throw new StoreError("conflict", "Registration needs environments for the new application.");
641
+ }
642
+ if (creatorAccess && !environments.some((row) => row.name === "development" && row.id === creatorAccess.environmentId
643
+ && row.appId === creatorAccess.appId && row.orgId === creatorAccess.orgId)) {
644
+ throw new StoreError("conflict", "Creator access must target the new development environment.");
645
+ }
646
+ if (audit && audit.orgId !== application.orgId)
647
+ throw new StoreError("conflict", "Application registration audit must match the tenant.");
648
+ await insertApp(sql, application);
649
+ for (const environment of environments)
650
+ await insertAppEnvironment(sql, environment);
651
+ if (creatorAccess)
652
+ await saveStaffAccess(sql, creatorAccess);
653
+ if (audit)
654
+ await writeAudit(sql, audit);
429
655
  });
430
656
  },
431
- getApplication: (id) => tx((sql) => first(sql, "SELECT * FROM applications WHERE id = $1", [id], applicationOf)),
432
- listApplications: (orgId) => tx(async (sql) => (await rows(sql, "SELECT * FROM applications WHERE org_id = $1 ORDER BY created_at DESC, id DESC", [orgId])).map(applicationOf)),
657
+ getApplication: (id) => tx((sql) => first(sql, "SELECT * FROM applications WHERE id = $1 AND trashed_at IS NULL", [id], applicationOf)),
658
+ listApplications: (orgId) => tx(async (sql) => (await rows(sql, "SELECT * FROM applications WHERE org_id = $1 AND trashed_at IS NULL ORDER BY created_at DESC, id DESC", [orgId])).map(applicationOf)),
659
+ listTrashedApplications: (orgId) => tx(async (sql) => (await rows(sql, `SELECT * FROM applications
660
+ WHERE org_id = $1 AND trashed_at IS NOT NULL ORDER BY trashed_at DESC, id DESC`, [orgId])).map(trashedApplicationOf)),
661
+ moveApplication: ({ appId, sourceOrgId, targetOrgId, updatedAt, environmentKeys, audit = [] }) => tx(async (sql) => {
662
+ const app = await first(sql, "SELECT * FROM applications WHERE id = $1 AND org_id = $2 AND trashed_at IS NULL FOR UPDATE", [appId, sourceOrgId], applicationOf);
663
+ if (!app)
664
+ throw new StoreError("not_found", "Application not found.");
665
+ if (sourceOrgId === targetOrgId)
666
+ throw new StoreError("conflict", "Choose a different tenant.");
667
+ const target = await rows(sql, "SELECT id FROM orgs WHERE id = $1 FOR KEY SHARE", [targetOrgId]);
668
+ if (!target.length)
669
+ throw new StoreError("not_found", "Destination tenant not found.");
670
+ if (audit.some((event) => event.orgId !== sourceOrgId && event.orgId !== targetOrgId)) {
671
+ throw new StoreError("conflict", "Application move audit must match the source or destination tenant.");
672
+ }
673
+ const stamp = applicationLifecycleTime(updatedAt, app.updatedAt);
674
+ const environments = (await rows(sql, "SELECT * FROM app_environments WHERE app_id = $1 ORDER BY id FOR UPDATE", [appId])).map(environmentOf);
675
+ const keys = applicationMoveKeys(environments, environmentKeys);
676
+ const path = `/tenants/${sourceOrgId}/apps/${appId}`;
677
+ const destinationPath = `/tenants/${targetOrgId}/apps/${appId}`;
678
+ const collision = await rows(sql, `SELECT 1 FROM audiences AS source JOIN audiences AS destination ON destination.identifier = source.identifier
679
+ WHERE source.app_id = $1 AND destination.org_id = $2 LIMIT 1`, [appId, targetOrgId]);
680
+ if (collision.length)
681
+ throw new StoreError("conflict", "The destination tenant already uses an audience identifier from this application.");
682
+ const mixed = await rows(sql, `SELECT 1 FROM gateway_routes AS route JOIN audiences AS audience ON audience.id = route.audience_id
683
+ WHERE (audience.app_id = $1 OR rtrim(route.resource, '/') = $2)
684
+ AND (audience.app_id IS DISTINCT FROM $1 OR rtrim(route.resource, '/') <> $2 OR route.org_id <> $3) LIMIT 1`, [appId, path, sourceOrgId]);
685
+ if (mixed.length)
686
+ throw new StoreError("conflict", "An application gateway route uses a shared tenant resource or audience. Update its scope before moving the application.");
687
+ await removeApplicationTenantAccess(sql, sourceOrgId, appId, stamp);
688
+ await sql.query("DELETE FROM sso_logins WHERE app_id = $1", [appId]);
689
+ await sql.query("DELETE FROM sso_exchanges WHERE app_id = $1", [appId]);
690
+ await sql.query("DELETE FROM hosted_human_codes WHERE app_id = $1", [appId]);
691
+ await sql.query("UPDATE hosted_human_clients SET revoked_at = $2::timestamptz WHERE app_id = $1 AND revoked_at IS NULL", [appId, stamp]);
692
+ await sql.query("DELETE FROM hosted_sso_profiles WHERE app_id = $1", [appId]);
693
+ await sql.query("DELETE FROM hosted_email_codes WHERE environment_id = ANY($1::text[])", [[...keys.keys()]]);
694
+ for (const key of keys.values()) {
695
+ await sql.query(`UPDATE app_environments SET org_id = $2, updated_at = $3::timestamptz, secret_enc = $4, secret_hash = $5,
696
+ key_version = $6, previous_secret_enc = NULL, previous_secret_hash = NULL, previous_key_version = NULL, previous_key_expires_at = NULL
697
+ WHERE id = $1 AND app_id = $7 AND org_id = $8`, [key.id, targetOrgId, stamp, key.secretEnc, key.secretHash, key.keyVersion, appId, sourceOrgId]);
698
+ }
699
+ await sql.query("UPDATE app_tokens SET org_id = $2, revoked_at = COALESCE(revoked_at, $3::timestamptz) WHERE app_id = $1", [appId, targetOrgId, stamp]);
700
+ await sql.query("UPDATE app_identities SET org_id = $2 WHERE app_id = $1", [appId, targetOrgId]);
701
+ await sql.query("UPDATE app_notification_settings SET org_id = $2 WHERE app_id = $1", [appId, targetOrgId]);
702
+ await sql.query("UPDATE app_notification_webhooks SET org_id = $2, enabled = false, updated_at = $3::timestamptz WHERE app_id = $1", [appId, targetOrgId, stamp]);
703
+ await sql.query("UPDATE app_product_roles SET catalog_role_id = NULL WHERE environment_id = ANY($1::text[]) AND catalog_role_id IS NOT NULL", [[...keys.keys()]]);
704
+ await sql.query(`UPDATE gateway_routes SET org_id = $2, resource = $3
705
+ WHERE org_id = $4 AND rtrim(resource, '/') = $5 AND audience_id IN (SELECT id FROM audiences WHERE app_id = $1)`, [appId, targetOrgId, destinationPath, sourceOrgId, path]);
706
+ await sql.query("UPDATE audiences SET org_id = $2 WHERE app_id = $1", [appId, targetOrgId]);
707
+ const moved = await first(sql, "UPDATE applications SET org_id = $3, updated_at = $4::timestamptz WHERE id = $1 AND org_id = $2 RETURNING *", [appId, sourceOrgId, targetOrgId, stamp], applicationOf);
708
+ if (!moved)
709
+ throw new StoreError("conflict", "Application tenant changed.");
710
+ for (const event of audit)
711
+ await writeAudit(sql, event);
712
+ return moved;
713
+ }),
714
+ trashApplication: ({ appId, orgId, trashedAt, allowProduction = true, audit }) => tx(async (sql) => {
715
+ await lockApplicationTenant(sql, orgId);
716
+ const app = await first(sql, "SELECT * FROM applications WHERE id = $1 AND org_id = $2 AND trashed_at IS NULL FOR UPDATE", [appId, orgId], applicationOf);
717
+ if (!app)
718
+ throw new StoreError("not_found", "Application not found.");
719
+ if (audit && audit.orgId !== orgId)
720
+ throw new StoreError("conflict", "Application trash audit must match the tenant.");
721
+ if (!allowProduction && (await rows(sql, "SELECT id FROM app_environments WHERE app_id = $1 AND name = 'production'", [appId])).length) {
722
+ throw new StoreError("conflict", "Production access is required to move this application to Trash.");
723
+ }
724
+ const stamp = applicationLifecycleTime(trashedAt, app.updatedAt);
725
+ const trashed = await first(sql, "UPDATE applications SET trashed_at = $3::timestamptz, updated_at = $3::timestamptz WHERE id = $1 AND org_id = $2 RETURNING *", [appId, orgId, stamp], trashedApplicationOf);
726
+ if (audit)
727
+ await writeAudit(sql, audit);
728
+ return trashed;
729
+ }),
730
+ restoreApplication: ({ appId, orgId, updatedAt, expectedTrashedAt, audit }) => tx(async (sql) => {
731
+ await lockApplicationTenant(sql, orgId);
732
+ const app = await first(sql, "SELECT * FROM applications WHERE id = $1 AND org_id = $2 AND trashed_at IS NOT NULL FOR UPDATE", [appId, orgId], trashedApplicationOf);
733
+ if (!app)
734
+ throw new StoreError("not_found", "Application not found in Trash.");
735
+ if (expectedTrashedAt && expectedTrashedAt !== app.trashedAt)
736
+ throw new StoreError("conflict", "Trash changed. Review the application before restoring it.");
737
+ if (audit && audit.orgId !== orgId)
738
+ throw new StoreError("conflict", "Application restore audit must match the tenant.");
739
+ const stamp = applicationLifecycleTime(updatedAt, app.trashedAt);
740
+ const restored = await first(sql, "UPDATE applications SET trashed_at = NULL, updated_at = $3::timestamptz WHERE id = $1 AND org_id = $2 RETURNING *", [appId, orgId, stamp], applicationOf);
741
+ if (audit)
742
+ await writeAudit(sql, audit);
743
+ return restored;
744
+ }),
745
+ emptyApplicationTrash: (orgId, confirmed, audit, allowProduction = true) => tx(async (sql) => {
746
+ await lockApplicationTenant(sql, orgId);
747
+ if (audit && audit.orgId !== orgId)
748
+ throw new StoreError("conflict", "Application trash audit must match the tenant.");
749
+ const entries = (await rows(sql, "SELECT * FROM applications WHERE org_id = $1 AND trashed_at IS NOT NULL ORDER BY id FOR UPDATE", [orgId])).map(trashedApplicationOf);
750
+ verifyApplicationTrashSnapshot(entries, confirmed);
751
+ if (!allowProduction && entries.length && (await rows(sql, "SELECT id FROM app_environments WHERE app_id = ANY($1::text[]) AND name = 'production' LIMIT 1", [entries.map(({ id }) => id)])).length) {
752
+ throw new StoreError("conflict", "Production access is required to empty this Trash.");
753
+ }
754
+ for (const entry of entries)
755
+ await purgeApplication(sql, entry);
756
+ if (audit)
757
+ await writeAudit(sql, audit);
758
+ return entries.length;
759
+ }),
760
+ listPurgedApplicationLogos: () => tx(async (sql) => (await rows(sql, "SELECT app_id FROM application_logo_purge ORDER BY app_id")).map((row) => String(row.app_id))),
761
+ clearPurgedApplicationLogo: (appId) => tx(async (sql) => { await sql.query("DELETE FROM application_logo_purge WHERE app_id = $1", [appId]); }),
433
762
  updateApplication(row) {
434
763
  return tx(async (sql) => {
764
+ let repair = { organizations: 0, workspaces: 0 };
765
+ if (row.directoryModel !== undefined) {
766
+ const current = await first(sql, "SELECT directory_model FROM applications WHERE id = $1 AND org_id = $2 AND trashed_at IS NULL FOR UPDATE", [row.id, row.orgId], (value) => value.directory_model);
767
+ if (current === null)
768
+ throw new StoreError("not_found", "Application not found.");
769
+ if (current !== row.directoryModel && row.directoryModel === "people-only") {
770
+ const existing = await rows(sql, `WITH environments AS (SELECT id FROM app_environments WHERE app_id = $1)
771
+ SELECT 1 WHERE EXISTS (SELECT 1 FROM app_identities WHERE app_id = $1 AND kind = 'organization')
772
+ OR EXISTS (SELECT 1 FROM app_workspaces WHERE app_id = $1)
773
+ OR EXISTS (SELECT 1 FROM app_identity_memberships WHERE environment_id IN (SELECT id FROM environments))
774
+ OR EXISTS (SELECT 1 FROM app_workspace_memberships WHERE environment_id IN (SELECT id FROM environments))
775
+ OR EXISTS (SELECT 1 FROM app_role_bindings WHERE environment_id IN (SELECT id FROM environments) AND (subject_type = 'organization' OR organization_id IS NOT NULL))
776
+ OR EXISTS (SELECT 1 FROM app_feature_assignments WHERE environment_id IN (SELECT id FROM environments) AND target_type = 'organization')`, [row.id]);
777
+ if (existing.length)
778
+ throw new StoreError("conflict", "Existing organizations, workspaces, memberships, or organization access rules prevent using people only.");
779
+ }
780
+ else if (current !== row.directoryModel && (row.directoryModel === "organizations" || row.directoryModel === "workspaces")) {
781
+ const conflicting = await rows(sql, `SELECT id FROM app_workspaces WHERE app_id = $1 AND
782
+ (($2 = 'organizations' AND status = 'active') OR ($2 = 'workspaces' AND organization_id IS NOT NULL))
783
+ LIMIT 1`, [row.id, row.directoryModel]);
784
+ if (conflicting.length)
785
+ throw new StoreError("conflict", "Existing workspaces are incompatible with this directory model.");
786
+ }
787
+ if (current !== row.directoryModel && row.directoryModel !== "people-only") {
788
+ repair = await repairDirectoryStructure(sql, row.id, row.orgId, row.directoryModel, row.updatedAt);
789
+ }
790
+ }
435
791
  const updated = await rows(sql, `UPDATE applications SET
436
- title = $2, description = $3, status = $4, allowed_scopes = $5::text[], allowed_features = $6::text[], updated_at = $7::timestamptz,
437
- product_name = $8, logo_url = $9, accent_color = $10, signup_mode = $11, allow_without_personal_org = $12
438
- WHERE id = $1 RETURNING id`, [
792
+ title = $2, description = $3, status = $4, allowed_scopes = $5::text[], allowed_features = $6::text[], updated_at = GREATEST(updated_at, $7::timestamptz),
793
+ product_name = $8, logo_url = $9, accent_color = $10, signup_mode = $11, allow_without_personal_org = $12,
794
+ waitlist_questions = COALESCE($13::text[], waitlist_questions), signup_audience = $14, signup_sso_providers = $15::text[], signup_organization = $16,
795
+ managed_sign_in = COALESCE($17::boolean, managed_sign_in), email_code_sign_in = COALESCE($18::boolean, email_code_sign_in),
796
+ auth_copy = COALESCE($19::jsonb, auth_copy), directory_model = COALESCE($20, directory_model),
797
+ directory_labels = COALESCE($21::jsonb, directory_labels), onboarding = onboarding || $22::jsonb,
798
+ waitlist_question_definitions = CASE WHEN $23::boolean THEN $24::jsonb ELSE waitlist_question_definitions END,
799
+ waitlist_question_layout = COALESCE($25, waitlist_question_layout)
800
+ WHERE id = $1 AND org_id = $26 AND trashed_at IS NULL RETURNING id`, [
439
801
  row.id, row.title, row.description, row.status, row.allowedScopes, row.allowedFeatures, asTime(row.updatedAt),
440
802
  row.productName || row.title, row.logoUrl ?? null, row.accentColor ?? null, row.signupMode ?? "open", row.allowRegistrationWithoutPersonalOrg === true,
803
+ row.waitlistQuestionDefinitions?.map(({ prompt }) => prompt) ?? row.waitlistQuestions ?? null,
804
+ row.signupAudience ?? "any-email", row.signupSsoProviders ?? [], row.signupOrganization ?? "required",
805
+ row.managedSignIn ?? null, row.emailCodeSignIn ?? null, row.authCopy === undefined ? null : JSON.stringify(row.authCopy),
806
+ row.directoryModel ?? null, row.directoryLabels === undefined ? null : JSON.stringify(row.directoryLabels), JSON.stringify(row.onboarding ?? {}),
807
+ row.waitlistQuestionDefinitions !== undefined || row.waitlistQuestions !== undefined,
808
+ row.waitlistQuestionDefinitions == null ? null : JSON.stringify(row.waitlistQuestionDefinitions), row.waitlistQuestionLayout ?? null, row.orgId,
441
809
  ]);
442
810
  if (!updated.length)
443
811
  throw new StoreError("not_found", "Application not found.");
812
+ return repair;
444
813
  });
445
814
  },
446
- insertEnvironment(row) {
815
+ insertEnvironment: (row) => tx((sql) => insertAppEnvironment(sql, row)),
816
+ getEnvironment: (id) => tx((sql) => first(sql, `SELECT env.* FROM app_environments env JOIN applications app ON app.id = env.app_id
817
+ WHERE env.id = $1 AND app.trashed_at IS NULL`, [id], environmentOf)),
818
+ listEnvironments: (appId, options) => tx(async (sql) => (await rows(sql, `SELECT env.* FROM app_environments env JOIN applications app ON app.id = env.app_id
819
+ WHERE env.app_id = $1 AND ($2::boolean OR app.trashed_at IS NULL) ORDER BY env.created_at, env.name`, [appId, options?.includeTrashed === true])).map(environmentOf)),
820
+ saveEnvironmentJwtProfile(environmentId, appId, orgId, profile, updatedAt) {
447
821
  return tx(async (sql) => {
448
- await sql.query(`INSERT INTO app_environments (
449
- id, app_id, org_id, name, title, status, secret_enc, secret_hash, key_version,
450
- previous_secret_enc, previous_secret_hash, previous_key_version, previous_key_expires_at, created_at, updated_at
451
- ) VALUES (
452
- $1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13::timestamptz, $14::timestamptz, $15::timestamptz
453
- )`, [
454
- row.id, row.appId, row.orgId, row.name, row.title, row.status, row.secretEnc, row.secretHash, row.keyVersion,
455
- row.previousSecretEnc, row.previousSecretHash, row.previousKeyVersion, asTimeOrNull(row.previousKeyExpiresAt), asTime(row.createdAt), asTime(row.updatedAt),
456
- ]);
822
+ await assertApplicationScope(sql, appId, orgId);
823
+ const updated = await rows(sql, `UPDATE app_environments SET jwt_profile = $4::jsonb, updated_at = $5::timestamptz
824
+ WHERE id = $1 AND app_id = $2 AND org_id = $3 RETURNING id`, [environmentId, appId, orgId, profile ? JSON.stringify(profile) : null, asTime(updatedAt)]);
825
+ if (!updated.length)
826
+ throw new StoreError("not_found", "Environment not found.");
457
827
  });
458
828
  },
459
- getEnvironment: (id) => tx((sql) => first(sql, "SELECT * FROM app_environments WHERE id = $1", [id], environmentOf)),
460
- listEnvironments: (appId) => tx(async (sql) => (await rows(sql, "SELECT * FROM app_environments WHERE app_id = $1 ORDER BY created_at, name", [appId])).map(environmentOf)),
461
829
  updateEnvironment(row) {
462
830
  return tx(async (sql) => {
831
+ await assertApplicationScope(sql, row.appId, row.orgId);
463
832
  const updated = await rows(sql, `UPDATE app_environments SET
464
833
  title = $2, status = $3, secret_enc = $4, secret_hash = $5, key_version = $6,
465
834
  previous_secret_enc = $7, previous_secret_hash = $8, previous_key_version = $9,
466
835
  previous_key_expires_at = $10::timestamptz, updated_at = $11::timestamptz
467
- WHERE id = $1 RETURNING id`, [
836
+ WHERE id = $1 AND app_id = $12 AND org_id = $13 AND name = $14
837
+ AND ((key_version = $6 AND secret_hash = $5) OR (key_version = $6 - 1 AND secret_hash = $8)) RETURNING id`, [
468
838
  row.id, row.title, row.status, row.secretEnc, row.secretHash, row.keyVersion,
469
- row.previousSecretEnc, row.previousSecretHash, row.previousKeyVersion, asTimeOrNull(row.previousKeyExpiresAt), asTime(row.updatedAt),
839
+ row.previousSecretEnc, row.previousSecretHash, row.previousKeyVersion, asTimeOrNull(row.previousKeyExpiresAt), asTime(row.updatedAt), row.appId, row.orgId, row.name,
470
840
  ]);
471
841
  if (!updated.length)
472
842
  throw new StoreError("not_found", "Environment not found.");
473
843
  });
474
844
  },
845
+ getNotificationSettings: (environmentId) => tx((sql) => first(sql, "SELECT * FROM app_notification_settings WHERE environment_id = $1", [environmentId], notificationSettingsOf)),
846
+ saveNotificationSettings(row, expectedUpdatedAt, audit) {
847
+ return tx(async (sql) => {
848
+ if (row.delivery !== "keyrox" && row.delivery !== "both" && row.delivery !== "webhook")
849
+ throw new StoreError("conflict", "Invalid notification delivery.");
850
+ await assertApplicationScope(sql, row.appId, row.orgId);
851
+ const environment = await first(sql, "SELECT * FROM app_environments WHERE id = $1 FOR UPDATE", [row.environmentId], environmentOf);
852
+ if (!environment || environment.appId !== row.appId || environment.orgId !== row.orgId)
853
+ throw new StoreError("conflict", "Notification settings must match the environment.");
854
+ const existing = await first(sql, "SELECT * FROM app_notification_settings WHERE environment_id = $1", [row.environmentId], notificationSettingsOf);
855
+ if (expectedUpdatedAt !== undefined && (existing?.updatedAt ?? null) !== expectedUpdatedAt)
856
+ return false;
857
+ if (row.delivery === "webhook" && !(await rows(sql, "SELECT id FROM app_notification_webhooks WHERE environment_id = $1 AND enabled LIMIT 1", [row.environmentId])).length) {
858
+ throw new StoreError("conflict", "webhook_required");
859
+ }
860
+ const saved = await rows(sql, `INSERT INTO app_notification_settings (environment_id, app_id, org_id, delivery, templates, updated_at)
861
+ VALUES ($1, $2, $3, $4, $5::jsonb, $6::timestamptz)
862
+ ON CONFLICT (environment_id) DO UPDATE SET delivery = EXCLUDED.delivery, templates = EXCLUDED.templates, updated_at = EXCLUDED.updated_at
863
+ WHERE app_notification_settings.app_id = EXCLUDED.app_id AND app_notification_settings.org_id = EXCLUDED.org_id
864
+ RETURNING environment_id`, [row.environmentId, row.appId, row.orgId, row.delivery, JSON.stringify(row.templates), asTime(row.updatedAt)]);
865
+ if (!saved.length)
866
+ throw new StoreError("conflict", "Notification settings must match the environment.");
867
+ if (audit) {
868
+ if (audit.orgId !== row.orgId)
869
+ throw new StoreError("conflict", "Notification audit must match the tenant.");
870
+ await writeAudit(sql, audit);
871
+ }
872
+ return true;
873
+ });
874
+ },
875
+ listNotificationWebhooks: (environmentId) => tx(async (sql) => (await rows(sql, "SELECT * FROM app_notification_webhooks WHERE environment_id = $1 ORDER BY created_at, id", [environmentId])).map(notificationWebhookOf)),
876
+ insertNotificationWebhook(row) {
877
+ return tx(async (sql) => {
878
+ await assertApplicationScope(sql, row.appId, row.orgId);
879
+ const environment = await first(sql, "SELECT * FROM app_environments WHERE id = $1 FOR UPDATE", [row.environmentId], environmentOf);
880
+ if (!environment || environment.appId !== row.appId || environment.orgId !== row.orgId)
881
+ throw new StoreError("conflict", "A webhook must match the environment.");
882
+ const count = Number((await rows(sql, "SELECT count(*)::int AS count FROM app_notification_webhooks WHERE environment_id = $1", [row.environmentId]))[0]?.count ?? 0);
883
+ if (count >= 5)
884
+ throw new StoreError("conflict", "webhook_limit");
885
+ await sql.query(`INSERT INTO app_notification_webhooks (
886
+ id, environment_id, app_id, org_id, url, secret_enc, enabled, created_at, updated_at
887
+ ) VALUES ($1, $2, $3, $4, $5, $6, $7, $8::timestamptz, $9::timestamptz)`, [
888
+ row.id, row.environmentId, row.appId, row.orgId, row.url, row.secretEnc, row.enabled, asTime(row.createdAt), asTime(row.updatedAt),
889
+ ]);
890
+ });
891
+ },
892
+ updateNotificationWebhook(row) {
893
+ return tx(async (sql) => {
894
+ await assertApplicationScope(sql, row.appId, row.orgId);
895
+ await rows(sql, "SELECT id FROM app_environments WHERE id = $1 FOR UPDATE", [row.environmentId]);
896
+ if (!row.enabled)
897
+ await ensureAnotherNotificationWebhook(sql, row.environmentId, row.id);
898
+ const updated = await rows(sql, `UPDATE app_notification_webhooks SET
899
+ url = $3, secret_enc = $4, enabled = $5, updated_at = $6::timestamptz
900
+ WHERE id = $1 AND environment_id = $2 AND app_id = $7 AND org_id = $8
901
+ RETURNING id`, [row.id, row.environmentId, row.url, row.secretEnc, row.enabled, asTime(row.updatedAt), row.appId, row.orgId]);
902
+ if (!updated.length)
903
+ throw new StoreError("not_found", "Webhook not found.");
904
+ });
905
+ },
906
+ deleteNotificationWebhook(environmentId, id, orgId) {
907
+ return tx(async (sql) => {
908
+ const scope = await rows(sql, `SELECT app.id FROM app_environments env JOIN applications app ON app.id = env.app_id
909
+ WHERE env.id = $1 AND app.trashed_at IS NULL AND ($2::text IS NULL OR app.org_id = $2) FOR SHARE OF app`, [environmentId, orgId ?? null]);
910
+ if (!scope.length)
911
+ return false;
912
+ await rows(sql, "SELECT id FROM app_environments WHERE id = $1 FOR UPDATE", [environmentId]);
913
+ await ensureAnotherNotificationWebhook(sql, environmentId, id);
914
+ const deleted = await rows(sql, `DELETE FROM app_notification_webhooks WHERE environment_id = $1 AND id = $2
915
+ AND ($3::text IS NULL OR org_id = $3) RETURNING id`, [environmentId, id, orgId ?? null]);
916
+ return deleted.length > 0;
917
+ });
918
+ },
919
+ listApplicationStaffAccess: (orgId, userId) => tx(async (sql) => (await rows(sql, `SELECT staff.* FROM app_staff_access staff
920
+ JOIN applications app ON app.id = staff.app_id WHERE staff.org_id = $1 AND app.trashed_at IS NULL
921
+ AND ($2::text IS NULL OR staff.user_id = $2) ORDER BY staff.created_at, staff.id`, [orgId, userId ?? null])).map(applicationStaffAccessOf)),
922
+ saveApplicationStaffAccess(row, audit) {
923
+ return tx(async (sql) => {
924
+ if (audit && audit.orgId !== row.orgId)
925
+ throw new StoreError("conflict", "Application staff audit must match the tenant.");
926
+ const saved = await saveStaffAccess(sql, row);
927
+ if (audit)
928
+ await writeAudit(sql, audit);
929
+ return saved;
930
+ });
931
+ },
932
+ deleteApplicationStaffAccess(orgId, appId, environmentId, userId, audit) {
933
+ return tx(async (sql) => {
934
+ if (audit && audit.orgId !== orgId)
935
+ throw new StoreError("conflict", "Application staff audit must match the tenant.");
936
+ const removed = await rows(sql, "DELETE FROM app_staff_access WHERE org_id = $1 AND app_id = $2 AND environment_id = $3 AND user_id = $4 RETURNING id", [orgId, appId, environmentId, userId]);
937
+ if (!removed.length)
938
+ return false;
939
+ if (audit)
940
+ await writeAudit(sql, audit);
941
+ return true;
942
+ });
943
+ },
475
944
  insertAppToken(row) {
476
945
  return tx(async (sql) => {
946
+ await assertApplicationScope(sql, row.appId, row.orgId);
947
+ const environment = await rows(sql, `SELECT id FROM app_environments WHERE id = $1 AND app_id = $2 AND org_id = $3 AND key_version = $4 FOR SHARE`, [row.environmentId, row.appId, row.orgId, row.payload.keyVersion]);
948
+ if (!environment.length)
949
+ throw new StoreError("conflict", "The environment or its key changed during token issuance.");
477
950
  await sql.query(`INSERT INTO app_tokens (
478
951
  id, app_id, environment_id, org_id, owner_identity_id, identity_type, payload, encrypted, revoked_at, expires_at, created_at
479
952
  ) VALUES ($1, $2, $3, $4, $5, $6, $7::jsonb, $8, $9::timestamptz, $10::timestamptz, $11::timestamptz)`, [
@@ -482,58 +955,298 @@ export function createSqlStore(database) {
482
955
  ]);
483
956
  });
484
957
  },
485
- getAppToken: (id) => tx((sql) => first(sql, "SELECT * FROM app_tokens WHERE id = $1", [id], appTokenOf)),
486
- listAppTokens: (filter) => tx(async (sql) => (await rows(sql, `SELECT * FROM app_tokens
487
- WHERE ($1::text IS NULL OR app_id = $1) AND ($2::text IS NULL OR environment_id = $2) AND ($3::text IS NULL OR owner_identity_id = $3) AND ($4::text IS NULL OR org_id = $4)
488
- ORDER BY created_at DESC, id DESC`, [filter.appId ?? null, filter.environmentId ?? null, filter.identityId ?? null, filter.orgId ?? null])).map(appTokenOf)),
958
+ getAppToken: (id) => tx((sql) => first(sql, `SELECT token.* FROM app_tokens token JOIN applications app ON app.id = token.app_id
959
+ WHERE token.id = $1 AND app.trashed_at IS NULL`, [id], appTokenOf)),
960
+ listAppTokens: (filter) => tx(async (sql) => (await rows(sql, `SELECT token.* FROM app_tokens token
961
+ JOIN applications app ON app.id = token.app_id WHERE app.trashed_at IS NULL
962
+ AND ($1::text IS NULL OR token.app_id = $1) AND ($2::text IS NULL OR token.environment_id = $2)
963
+ AND ($3::text IS NULL OR token.owner_identity_id = $3) AND ($4::text IS NULL OR token.org_id = $4)
964
+ ORDER BY token.created_at DESC, token.id DESC`, [filter.appId ?? null, filter.environmentId ?? null, filter.identityId ?? null, filter.orgId ?? null])).map(appTokenOf)),
489
965
  revokeAppToken: (id, at) => tx(async (sql) => {
490
- await sql.query("UPDATE app_tokens SET revoked_at = $2::timestamptz WHERE id = $1 AND revoked_at IS NULL", [id, asTime(at)]);
491
- return first(sql, "SELECT * FROM app_tokens WHERE id = $1", [id], appTokenOf);
966
+ await sql.query(`UPDATE app_tokens SET revoked_at = $2::timestamptz WHERE id = $1 AND revoked_at IS NULL
967
+ AND EXISTS (SELECT 1 FROM applications app WHERE app.id = app_tokens.app_id AND app.trashed_at IS NULL)`, [id, asTime(at)]);
968
+ return first(sql, `SELECT token.* FROM app_tokens token JOIN applications app ON app.id = token.app_id
969
+ WHERE token.id = $1 AND app.trashed_at IS NULL`, [id], appTokenOf);
492
970
  }),
493
971
  revokeAppTokens: (filter, at) => tx(async (sql) => {
494
972
  const updated = await rows(sql, `UPDATE app_tokens SET revoked_at = $5::timestamptz
495
973
  WHERE revoked_at IS NULL AND ($1::text IS NULL OR app_id = $1) AND ($2::text IS NULL OR environment_id = $2) AND ($3::text IS NULL OR owner_identity_id = $3) AND ($4::text IS NULL OR org_id = $4)
974
+ AND EXISTS (SELECT 1 FROM applications app WHERE app.id = app_tokens.app_id AND app.trashed_at IS NULL)
496
975
  RETURNING id`, [filter.appId ?? null, filter.environmentId ?? null, filter.identityId ?? null, filter.orgId ?? null, asTime(at)]);
497
976
  return updated.length;
498
977
  }),
978
+ savePlatformSignIn: (row) => tx(async (sql) => {
979
+ const saved = await first(sql, `INSERT INTO platform_sign_in (id, provider, client_id, client_secret_enc, directory_id, issuer, created_at, managed_for_apps)
980
+ VALUES ($1, $2, $3, $4, $5, $6, $7::timestamptz,
981
+ ($2 <> 'oidc' AND ($2 <> 'microsoft' OR $5 IS NOT DISTINCT FROM 'common')) AND COALESCE($8::boolean, false))
982
+ ON CONFLICT (provider) DO UPDATE SET client_id = EXCLUDED.client_id, client_secret_enc = EXCLUDED.client_secret_enc,
983
+ directory_id = EXCLUDED.directory_id, issuer = EXCLUDED.issuer, managed_for_apps =
984
+ (EXCLUDED.provider <> 'oidc' AND (EXCLUDED.provider <> 'microsoft' OR EXCLUDED.directory_id IS NOT DISTINCT FROM 'common'))
985
+ AND COALESCE($8::boolean, platform_sign_in.managed_for_apps)
986
+ RETURNING *`, [row.id, row.provider, row.clientId, row.clientSecretEnc, row.directoryId, row.issuer, asTime(row.createdAt), row.managedForApps ?? null], platformSignInOf);
987
+ return saved;
988
+ }),
989
+ setPlatformSignInManaged: (provider, managedForApps) => tx((sql) => first(sql, `UPDATE platform_sign_in SET managed_for_apps = $2
990
+ WHERE provider = $1 AND (NOT $2::boolean OR (provider <> 'oidc' AND (provider <> 'microsoft' OR directory_id IS NOT DISTINCT FROM 'common')))
991
+ RETURNING *`, [provider, managedForApps], platformSignInOf)),
992
+ listPlatformSignIn: () => tx(async (sql) => (await rows(sql, "SELECT * FROM platform_sign_in ORDER BY provider", [])).map(platformSignInOf)),
993
+ deletePlatformSignIn: (provider) => tx(async (sql) => { await sql.query("DELETE FROM platform_sign_in WHERE provider = $1", [provider]); }),
994
+ findAccountIdentity: (provider, subject) => tx((sql) => first(sql, "SELECT * FROM account_identities WHERE provider = $1 AND subject = $2", [provider, subject], accountIdentityOf)),
995
+ findUserAccountIdentity: (userId, provider) => tx((sql) => first(sql, "SELECT * FROM account_identities WHERE user_id = $1 AND provider = $2", [userId, provider], accountIdentityOf)),
996
+ saveAccountIdentity: (row) => tx((sql) => insertAccountIdentity(sql, row)),
997
+ insertAccountSsoLogin: (row) => tx(async (sql) => {
998
+ await sql.query(`INSERT INTO account_sso_logins (id, state_hash, nonce, verifier, provider, next_path, link_user_id, link_session_hash, expires_at, created_at) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9::timestamptz, $10::timestamptz)`, [row.id, row.stateHash, row.nonce, row.verifier, row.provider, row.nextPath ?? null, row.linkUserId ?? null, row.linkSessionHash ?? null, asTime(row.expiresAt), asTime(row.createdAt)]);
999
+ }),
1000
+ takeAccountSsoLogin: (stateHash, at) => tx(async (sql) => {
1001
+ const found = await first(sql, "DELETE FROM account_sso_logins WHERE state_hash = $1 RETURNING *", [stateHash], accountSsoLoginOf);
1002
+ if (!found || Date.parse(found.expiresAt) <= Date.parse(asTime(at)))
1003
+ return null;
1004
+ return found;
1005
+ }),
1006
+ insertAccountSsoProfile: (row) => tx(async (sql) => {
1007
+ const createdAt = asTime(row.createdAt);
1008
+ await sql.query("DELETE FROM account_sso_profiles WHERE expires_at <= $1::timestamptz", [createdAt]);
1009
+ await sql.query(`INSERT INTO account_sso_profiles (id, code_hash, browser_hash, provider, connection_fingerprint, subject, email, next_path, expires_at, created_at)
1010
+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9::timestamptz, $10::timestamptz)`, [row.id, row.codeHash, row.browserHash, row.provider, row.connectionFingerprint, row.subject, row.email, row.nextPath, asTime(row.expiresAt), createdAt]);
1011
+ }),
1012
+ takeAccountSsoProfile: (codeHash, browserHash, at) => tx(async (sql) => {
1013
+ const found = await first(sql, "DELETE FROM account_sso_profiles WHERE code_hash = $1 AND browser_hash = $2 RETURNING *", [codeHash, browserHash], accountSsoProfileOf);
1014
+ return found && !isExpired(found.expiresAt, asTime(at)) ? found : null;
1015
+ }),
1016
+ insertAccountHandoff: (row) => tx(async (sql) => {
1017
+ await sql.query(`INSERT INTO account_handoffs (id, code_hash, session_token, expires_at, created_at) VALUES ($1, $2, $3, $4::timestamptz, $5::timestamptz)`, [row.id, row.codeHash, row.sessionToken, asTime(row.expiresAt), asTime(row.createdAt)]);
1018
+ }),
1019
+ takeAccountHandoff: (codeHash, at) => tx(async (sql) => {
1020
+ const found = await first(sql, "DELETE FROM account_handoffs WHERE code_hash = $1 RETURNING *", [codeHash], accountHandoffOf);
1021
+ if (!found || Date.parse(found.expiresAt) <= Date.parse(asTime(at)))
1022
+ return null;
1023
+ return found;
1024
+ }),
1025
+ insertCliLoginCode: (row) => tx(async (sql) => {
1026
+ const createdAt = asTime(row.createdAt);
1027
+ await sql.query("DELETE FROM cli_login_codes WHERE expires_at <= $1::timestamptz", [createdAt]);
1028
+ await sql.query(`INSERT INTO cli_login_codes (code_hash, request_hash, code_challenge, redirect_uri, user_id, org_id, browser_session_hash, expires_at, created_at, consumed_at)
1029
+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8::timestamptz, $9::timestamptz, $10::timestamptz)`, [row.codeHash, row.requestHash, row.codeChallenge, row.redirectUri, row.userId, row.orgId, row.browserSessionHash,
1030
+ asTime(row.expiresAt), createdAt, asTimeOrNull(row.consumedAt)]);
1031
+ }),
1032
+ takeCliLoginCode: (codeHash, codeChallenge, redirectUri, at) => tx((sql) => first(sql, `UPDATE cli_login_codes SET consumed_at = $4::timestamptz
1033
+ WHERE code_hash = $1 AND code_challenge = $2 AND redirect_uri = $3 AND consumed_at IS NULL AND expires_at > $4::timestamptz
1034
+ RETURNING *`, [codeHash, codeChallenge, redirectUri, asTime(at)], cliLoginCodeOf)),
499
1035
  saveSignInConnection: (row) => tx(async (sql) => {
500
- await sql.query(`INSERT INTO sign_in_connections (id, org_id, provider, client_id, client_secret_enc, directory_id, issuer, created_at)
501
- VALUES ($1, $2, $3, $4, $5, $6, $7, $8::timestamptz)
502
- ON CONFLICT (org_id, provider) DO UPDATE SET client_id = EXCLUDED.client_id, client_secret_enc = EXCLUDED.client_secret_enc, directory_id = EXCLUDED.directory_id, issuer = EXCLUDED.issuer`, [row.id, row.orgId, row.provider, row.clientId, row.clientSecretEnc, row.directoryId, row.issuer, asTime(row.createdAt)]);
1036
+ await assertApplicationScope(sql, row.appId, row.orgId, "conflict");
1037
+ const saved = await rows(sql, `INSERT INTO app_sign_in_connections (id, app_id, provider, client_id, client_secret_enc, directory_id, issuer, created_at)
1038
+ SELECT $1, app.id, $4, $5, $6, $7, $8, $9::timestamptz FROM applications app WHERE app.id = $2 AND app.org_id = $3
1039
+ ON CONFLICT (app_id, provider) DO UPDATE SET client_id = EXCLUDED.client_id, client_secret_enc = EXCLUDED.client_secret_enc, directory_id = EXCLUDED.directory_id, issuer = EXCLUDED.issuer
1040
+ RETURNING id`, [row.id, row.appId, row.orgId, row.provider, row.clientId, row.clientSecretEnc, row.directoryId, row.issuer, asTime(row.createdAt)]);
1041
+ if (!saved.length)
1042
+ throw new StoreError("conflict", "The sign-in connection must belong to the application tenant.");
1043
+ await retireLegacyAppSignIn(sql, row.appId, row.provider);
1044
+ }),
1045
+ listSignInConnections: (appId) => tx(async (sql) => (await rows(sql, `SELECT connection.*, app.org_id FROM app_sign_in_connections connection
1046
+ JOIN applications app ON app.id = connection.app_id WHERE connection.app_id = $1 AND app.trashed_at IS NULL ORDER BY connection.provider`, [appId])).map(signInOf)),
1047
+ listOrgSignInConnections: (orgId) => tx(async (sql) => (await rows(sql, `SELECT connection.*, app.org_id FROM app_sign_in_connections connection
1048
+ JOIN applications app ON app.id = connection.app_id WHERE app.org_id = $1 AND app.trashed_at IS NULL ORDER BY connection.provider, connection.app_id`, [orgId])).map(signInOf)),
1049
+ deleteSignInConnection: (appId, provider, orgId) => tx(async (sql) => {
1050
+ const scope = await rows(sql, `SELECT id FROM applications WHERE id = $1 AND trashed_at IS NULL
1051
+ AND ($2::text IS NULL OR org_id = $2) FOR SHARE`, [appId, orgId ?? null]);
1052
+ if (!scope.length)
1053
+ throw new StoreError("not_found", "Application not found.");
1054
+ await sql.query("DELETE FROM app_sign_in_connections WHERE app_id = $1 AND provider = $2", [appId, provider]);
1055
+ await retireLegacyAppSignIn(sql, appId, provider);
503
1056
  }),
504
- listSignInConnections: (orgId) => tx(async (sql) => (await rows(sql, "SELECT * FROM sign_in_connections WHERE org_id = $1 ORDER BY provider", [orgId])).map(signInOf)),
505
- deleteSignInConnection: (orgId, provider) => tx(async (sql) => { await sql.query("DELETE FROM sign_in_connections WHERE org_id = $1 AND provider = $2", [orgId, provider]); }),
506
1057
  saveAppSignIn: (appId, providers) => tx(async (sql) => {
507
1058
  await sql.query(`INSERT INTO app_sign_in (app_id, providers) VALUES ($1, $2) ON CONFLICT (app_id) DO UPDATE SET providers = EXCLUDED.providers`, [appId, providers]);
508
1059
  }),
509
1060
  getAppSignIn: (appId) => tx(async (sql) => textsOf(await first(sql, "SELECT providers FROM app_sign_in WHERE app_id = $1", [appId], (row) => row))),
510
- saveRedirects: (environmentId, uris) => tx(async (sql) => {
1061
+ saveRedirects: (environmentId, uris, orgId) => tx(async (sql) => {
1062
+ const scope = await rows(sql, `SELECT app.id FROM app_environments env JOIN applications app ON app.id = env.app_id
1063
+ WHERE env.id = $1 AND app.trashed_at IS NULL AND ($2::text IS NULL OR app.org_id = $2) FOR SHARE OF app`, [environmentId, orgId ?? null]);
1064
+ if (!scope.length)
1065
+ throw new StoreError("not_found", "Application environment not found.");
511
1066
  await sql.query(`INSERT INTO environment_redirects (environment_id, uris) VALUES ($1, $2) ON CONFLICT (environment_id) DO UPDATE SET uris = EXCLUDED.uris`, [environmentId, uris]);
512
1067
  }),
513
1068
  getRedirects: (environmentId) => tx(async (sql) => textsOf(await first(sql, "SELECT uris FROM environment_redirects WHERE environment_id = $1", [environmentId], (row) => row))),
1069
+ insertHostedHumanClient: (row) => tx(async (sql) => {
1070
+ await assertApplicationScope(sql, row.appId, row.orgId);
1071
+ const inserted = await rows(sql, `INSERT INTO hosted_human_clients
1072
+ (id, app_id, environment_id, org_id, name, redirect_uri, audience, secret_hash, created_at, revoked_at)
1073
+ SELECT $1, env.app_id, env.id, env.org_id, $5, $6, $7, $8, $9::timestamptz, $10::timestamptz
1074
+ FROM app_environments env WHERE env.app_id = $2 AND env.id = $3 AND env.org_id = $4 RETURNING id`, [row.id, row.appId, row.environmentId, row.orgId, row.name, row.redirectUri, row.audience, row.secretHash,
1075
+ asTime(row.createdAt), asTimeOrNull(row.revokedAt)]);
1076
+ if (!inserted.length)
1077
+ throw new StoreError("not_found", "Application environment not found.");
1078
+ }),
1079
+ getHostedHumanClient: (clientId) => tx((sql) => first(sql, "SELECT * FROM hosted_human_clients WHERE id = $1", [clientId], hostedHumanClientOf)),
1080
+ listHostedHumanClients: (appId, environmentId) => tx(async (sql) => (await rows(sql, `SELECT client.* FROM hosted_human_clients client
1081
+ JOIN applications app ON app.id = client.app_id AND app.org_id = client.org_id
1082
+ WHERE client.app_id = $1 AND client.environment_id = $2 AND app.trashed_at IS NULL ORDER BY client.created_at, client.id`, [appId, environmentId])).map(hostedHumanClientOf)),
1083
+ revokeHostedHumanClient: (appId, environmentId, clientId, at) => tx(async (sql) => {
1084
+ const revoked = await rows(sql, `UPDATE hosted_human_clients client
1085
+ SET revoked_at = COALESCE(client.revoked_at, $4::timestamptz) FROM applications app
1086
+ WHERE client.app_id = $1 AND client.environment_id = $2 AND client.id = $3
1087
+ AND app.id = client.app_id AND app.org_id = client.org_id AND app.trashed_at IS NULL RETURNING client.id`, [appId, environmentId, clientId, asTime(at)]);
1088
+ if (!revoked.length)
1089
+ return false;
1090
+ await sql.query("DELETE FROM hosted_human_codes WHERE client_id = $1", [clientId]);
1091
+ return true;
1092
+ }),
1093
+ insertHostedHumanCode: (row) => tx(async (sql) => (await rows(sql, `INSERT INTO hosted_human_codes
1094
+ (code_hash, client_id, app_id, environment_id, org_id, redirect_uri, code_challenge, identity_id, provider, created_at, expires_at)
1095
+ SELECT $1, client.id, client.app_id, client.environment_id, client.org_id, client.redirect_uri, $7, identity.id, $9, $10::timestamptz, $11::timestamptz
1096
+ FROM hosted_human_clients client
1097
+ JOIN applications app ON app.id = client.app_id AND app.org_id = client.org_id
1098
+ JOIN app_environments env ON env.id = client.environment_id AND env.app_id = client.app_id AND env.org_id = client.org_id
1099
+ JOIN environment_redirects redirects ON redirects.environment_id = env.id AND client.redirect_uri = ANY(redirects.uris)
1100
+ JOIN app_identities identity ON identity.id = $8 AND identity.app_id = client.app_id
1101
+ AND identity.environment_id = client.environment_id AND identity.org_id = client.org_id
1102
+ WHERE client.id = $2 AND client.app_id = $3 AND client.environment_id = $4 AND client.org_id = $5 AND client.redirect_uri = $6
1103
+ AND client.revoked_at IS NULL AND app.trashed_at IS NULL AND app.status = 'active' AND app.signup_mode = 'waiting-list'
1104
+ AND env.status = 'active' AND identity.kind = 'user' AND identity.status = 'active'
1105
+ AND identity.email IS NOT NULL AND identity.email_verified_at IS NOT NULL AND identity.email_proof_at IS NOT NULL
1106
+ FOR SHARE OF app, env, client, identity, redirects RETURNING code_hash`, [row.codeHash, row.clientId, row.appId, row.environmentId, row.orgId, row.redirectUri, row.codeChallenge,
1107
+ row.identityId, row.provider, asTime(row.createdAt), asTime(row.expiresAt)])).length === 1),
1108
+ takeHostedHumanCode: (input) => tx(async (sql) => {
1109
+ const found = await first(sql, `SELECT code.* FROM hosted_human_codes code
1110
+ JOIN hosted_human_clients client ON client.id = code.client_id AND client.app_id = code.app_id
1111
+ AND client.environment_id = code.environment_id AND client.org_id = code.org_id AND client.redirect_uri = code.redirect_uri
1112
+ JOIN applications app ON app.id = code.app_id AND app.org_id = code.org_id
1113
+ JOIN app_environments env ON env.id = code.environment_id AND env.app_id = code.app_id AND env.org_id = code.org_id
1114
+ JOIN environment_redirects redirects ON redirects.environment_id = env.id AND code.redirect_uri = ANY(redirects.uris)
1115
+ JOIN app_identities identity ON identity.id = code.identity_id AND identity.app_id = code.app_id
1116
+ AND identity.environment_id = code.environment_id AND identity.org_id = code.org_id
1117
+ WHERE code.code_hash = $1 AND code.client_id = $2 AND code.app_id = $3 AND code.environment_id = $4
1118
+ AND code.redirect_uri = $5 AND code.code_challenge = $6 AND client.secret_hash = $7 AND code.expires_at > $8::timestamptz
1119
+ AND client.revoked_at IS NULL AND app.trashed_at IS NULL AND app.status = 'active' AND app.signup_mode = 'waiting-list'
1120
+ AND env.status = 'active' AND identity.kind = 'user' AND identity.status = 'active'
1121
+ AND identity.email IS NOT NULL AND identity.email_verified_at IS NOT NULL AND identity.email_proof_at IS NOT NULL
1122
+ FOR SHARE OF app, env, client, identity, redirects`, [input.codeHash, input.clientId, input.appId, input.environmentId, input.redirectUri, input.codeChallenge, input.secretHash, asTime(input.at)], hostedHumanCodeOf);
1123
+ return found ? first(sql, "DELETE FROM hosted_human_codes WHERE code_hash = $1 RETURNING *", [found.codeHash], hostedHumanCodeOf) : null;
1124
+ }),
514
1125
  insertSsoLogin: (row) => tx(async (sql) => {
515
- await sql.query(`INSERT INTO sso_logins (id, state_hash, nonce, verifier, app_id, environment_id, org_id, provider, redirect_uri, app_state, expires_at, created_at)
516
- VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11::timestamptz,$12::timestamptz)`, [
517
- row.id, row.stateHash, row.nonce, row.verifier, row.appId, row.environmentId, row.orgId, row.provider, row.redirectUri, row.appState, asTime(row.expiresAt), asTime(row.createdAt),
1126
+ await assertApplicationScope(sql, row.appId, row.orgId);
1127
+ await sql.query(`INSERT INTO sso_logins (id, state_hash, nonce, verifier, app_id, environment_id, org_id, provider, redirect_uri, app_state,
1128
+ expires_at, created_at, connection_authority, waitlist_in_app, human_binding, invitation_token_hash)
1129
+ VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11::timestamptz,$12::timestamptz,$13,$14,$15::jsonb,$16)`, [
1130
+ row.id, row.stateHash, row.nonce, row.verifier, row.appId, row.environmentId, row.orgId, row.provider, row.redirectUri, row.appState,
1131
+ asTime(row.expiresAt), asTime(row.createdAt), row.connectionAuthority ?? null, row.waitlistInApp === true,
1132
+ row.humanBinding ? JSON.stringify(row.humanBinding) : null, row.invitationTokenHash ?? null,
518
1133
  ]);
519
1134
  }),
520
1135
  takeSsoLogin: (stateHash, at) => tx(async (sql) => {
1136
+ const scope = await rows(sql, `SELECT app.id FROM sso_logins login JOIN applications app ON app.id = login.app_id
1137
+ WHERE login.state_hash = $1 AND app.org_id = login.org_id AND app.trashed_at IS NULL FOR SHARE OF app`, [stateHash]);
1138
+ if (!scope.length)
1139
+ return null;
521
1140
  const found = await first(sql, "DELETE FROM sso_logins WHERE state_hash = $1 RETURNING *", [stateHash], ssoLoginOf);
522
1141
  if (!found || Date.parse(found.expiresAt) <= Date.parse(asTime(at)))
523
1142
  return null;
524
1143
  return found;
525
1144
  }),
1145
+ putHostedEmailCode: (row) => tx(async (sql) => {
1146
+ const createdAt = asTime(row.createdAt);
1147
+ const expiresAt = asTime(row.expiresAt);
1148
+ if (isExpired(expiresAt, createdAt))
1149
+ throw new StoreError("conflict", "Email code expiry must follow issuance.");
1150
+ const now = Date.parse(createdAt);
1151
+ const windowStart = new Date(now - hostedEmailCodePolicy.sendWindowMs).toISOString();
1152
+ const cooldownEnd = new Date(now - hostedEmailCodePolicy.resendDelayMs).toISOString();
1153
+ const inserted = await rows(sql, `INSERT INTO hosted_email_codes AS current_code
1154
+ (environment_id, email, id, challenge_hash, code_hash, created_at, expires_at, attempts_remaining, send_history)
1155
+ SELECT env.id, $3, $4, $5, $6, $7::timestamptz, $8::timestamptz, $9, ARRAY[$7::timestamptz]
1156
+ FROM app_environments env JOIN applications app ON app.id = env.app_id
1157
+ WHERE app.id = $1 AND env.id = $2 AND app.trashed_at IS NULL AND app.status = 'active' AND env.status = 'active'
1158
+ FOR SHARE OF app
1159
+ ON CONFLICT (environment_id, email) DO UPDATE SET id = EXCLUDED.id, challenge_hash = EXCLUDED.challenge_hash,
1160
+ code_hash = EXCLUDED.code_hash, created_at = EXCLUDED.created_at, expires_at = EXCLUDED.expires_at,
1161
+ attempts_remaining = EXCLUDED.attempts_remaining, consumed_at = NULL,
1162
+ send_history = ARRAY(SELECT sent_at FROM unnest(current_code.send_history) AS sent(sent_at)
1163
+ WHERE sent_at > $10::timestamptz) || EXCLUDED.send_history
1164
+ WHERE current_code.challenge_hash <> EXCLUDED.challenge_hash
1165
+ AND current_code.created_at <= $11::timestamptz
1166
+ AND (SELECT count(*) FROM unnest(current_code.send_history) AS sent(sent_at) WHERE sent_at > $10::timestamptz) < $12
1167
+ RETURNING id`, [
1168
+ row.appId, row.environmentId, row.email.trim().toLowerCase(), row.id, row.challengeHash, row.codeHash,
1169
+ createdAt, expiresAt, hostedEmailCodePolicy.maxAttempts, windowStart, cooldownEnd, hostedEmailCodePolicy.maxSends,
1170
+ ]);
1171
+ return inserted.length ? "sent" : "cooldown";
1172
+ }),
1173
+ verifyHostedEmailCode: (appId, environmentId, challengeHash, codeHash, at) => tx((sql) => first(sql, `UPDATE hosted_email_codes AS code SET
1174
+ attempts_remaining = code.attempts_remaining - 1,
1175
+ consumed_at = CASE WHEN code.code_hash = $4 THEN $5::timestamptz ELSE NULL END
1176
+ FROM app_environments env JOIN applications app ON app.id = env.app_id
1177
+ WHERE code.environment_id = env.id AND app.id = $1 AND env.id = $2 AND code.challenge_hash = $3
1178
+ AND app.trashed_at IS NULL AND app.status = 'active' AND env.status = 'active'
1179
+ AND code.consumed_at IS NULL AND code.attempts_remaining > 0 AND code.expires_at > $5::timestamptz
1180
+ RETURNING code.*, app.id AS app_id`, [appId, environmentId, challengeHash, codeHash, asTime(at)], (row) => row.consumed_at ? hostedEmailCodeOf(row) : null)),
1181
+ insertHostedSsoProfile: (row) => tx(async (sql) => {
1182
+ await assertApplicationScope(sql, row.appId, row.orgId);
1183
+ const inserted = await rows(sql, `INSERT INTO hosted_sso_profiles
1184
+ (id, challenge_hash, browser_hash, app_id, environment_id, org_id, provider, authority, subject, email, redirect_uri, app_state,
1185
+ expires_at, created_at, display_name, connection_fingerprint, waitlist_in_app, human_binding)
1186
+ SELECT $1, $2, $3, app.id, env.id, app.org_id, $7, $8, $9, $10, $11, $12, $13::timestamptz, $14::timestamptz, $15, $16, $17, $18::jsonb
1187
+ FROM app_environments env JOIN applications app ON app.id = env.app_id
1188
+ WHERE app.id = $4 AND env.id = $5 AND app.org_id = $6 RETURNING id`, [
1189
+ row.id, row.challengeHash, row.browserHash, row.appId, row.environmentId, row.orgId, row.provider,
1190
+ row.authority, row.subject, row.email, row.redirectUri, row.appState, asTime(row.expiresAt), asTime(row.createdAt),
1191
+ row.displayName ?? null, row.connectionFingerprint ?? null, row.waitlistInApp === true,
1192
+ row.humanBinding ? JSON.stringify(row.humanBinding) : null,
1193
+ ]);
1194
+ if (!inserted.length)
1195
+ throw new StoreError("conflict", "Hosted sign-in environment is missing.");
1196
+ }),
1197
+ getHostedSsoProfile: (challengeHash, browserHash, at) => tx((sql) => first(sql, `SELECT profile.* FROM hosted_sso_profiles profile
1198
+ JOIN applications app ON app.id = profile.app_id AND app.org_id = profile.org_id
1199
+ WHERE profile.challenge_hash = $1 AND profile.browser_hash = $2 AND profile.expires_at > $3::timestamptz AND app.trashed_at IS NULL`, [challengeHash, browserHash, asTime(at)], hostedSsoProfileOf)),
1200
+ takeHostedSsoProfile: (challengeHash, browserHash, at) => tx(async (sql) => {
1201
+ if (!await lockHostedSsoApplication(sql, challengeHash, browserHash))
1202
+ return null;
1203
+ return first(sql, `DELETE FROM hosted_sso_profiles WHERE challenge_hash = $1 AND browser_hash = $2 AND expires_at > $3::timestamptz RETURNING *`, [challengeHash, browserHash, asTime(at)], hostedSsoProfileOf);
1204
+ }),
1205
+ beginHostedSsoEmail: (challengeHash, browserHash, proof) => tx(async (sql) => {
1206
+ const createdAt = asTime(proof.createdAt);
1207
+ const expiresAt = asTime(proof.expiresAt);
1208
+ if (proof.purpose !== "hosted-sso-email" || proof.usedAt !== null || isExpired(expiresAt, createdAt))
1209
+ return false;
1210
+ const profile = await lockHostedSsoEmailProfile(sql, challengeHash, browserHash, createdAt);
1211
+ if (!profile || profile.id !== proof.identityId || profile.environmentId !== proof.environmentId)
1212
+ return false;
1213
+ const inserted = await rows(sql, `INSERT INTO hosted_sso_email_proofs (profile_id, token_hash, email, created_at, expires_at)
1214
+ VALUES ($1, $2, $3, $4::timestamptz, $5::timestamptz)
1215
+ ON CONFLICT (profile_id) DO UPDATE SET token_hash = EXCLUDED.token_hash, email = EXCLUDED.email,
1216
+ created_at = EXCLUDED.created_at, expires_at = EXCLUDED.expires_at
1217
+ WHERE hosted_sso_email_proofs.created_at <= EXCLUDED.created_at - INTERVAL '60 seconds'
1218
+ RETURNING profile_id`, [profile.id, proof.tokenHash, proof.email, createdAt, expiresAt]);
1219
+ return inserted.length > 0;
1220
+ }),
1221
+ takeHostedSsoEmail: (challengeHash, browserHash, tokenHash, at) => tx(async (sql) => {
1222
+ const stamp = asTime(at);
1223
+ const profile = await lockHostedSsoEmailProfile(sql, challengeHash, browserHash, stamp);
1224
+ if (!profile)
1225
+ return null;
1226
+ const proof = await first(sql, `SELECT email FROM hosted_sso_email_proofs
1227
+ WHERE profile_id = $1 AND token_hash = $2 AND expires_at > $3::timestamptz`, [profile.id, tokenHash, stamp], (row) => String(row.email));
1228
+ if (proof === null)
1229
+ return null;
1230
+ await sql.query("DELETE FROM hosted_sso_profiles WHERE id = $1", [profile.id]);
1231
+ return { ...profile, email: proof };
1232
+ }),
526
1233
  insertSsoExchange: (row) => tx(async (sql) => {
527
- await sql.query(`INSERT INTO sso_exchanges (id, code_hash, app_id, environment_id, token, token_id, subject, provider, expires_at, created_at)
528
- VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9::timestamptz,$10::timestamptz)`, [
529
- row.id, row.codeHash, row.appId, row.environmentId, row.token, row.tokenId, row.subject, row.provider, asTime(row.expiresAt), asTime(row.createdAt),
1234
+ const token = await rows(sql, `SELECT token.id FROM app_tokens token JOIN applications app ON app.id = token.app_id
1235
+ WHERE token.id = $1 AND token.app_id = $2 AND token.environment_id = $3 AND token.org_id = app.org_id
1236
+ AND app.trashed_at IS NULL AND token.revoked_at IS NULL FOR SHARE OF app, token`, [row.tokenId, row.appId, row.environmentId]);
1237
+ if (!token.length)
1238
+ throw new StoreError("conflict", "The sign-in token is unavailable.");
1239
+ await sql.query(`INSERT INTO sso_exchanges (id, code_hash, app_id, environment_id, token, token_id, subject, provider, expires_at, created_at, redirect_uri)
1240
+ VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9::timestamptz,$10::timestamptz,$11)`, [
1241
+ row.id, row.codeHash, row.appId, row.environmentId, row.token, row.tokenId, row.subject, row.provider, asTime(row.expiresAt), asTime(row.createdAt), row.redirectUri ?? null,
530
1242
  ]);
531
1243
  }),
1244
+ getSsoExchange: (codeHash, at) => tx((sql) => first(sql, ssoExchangeQuery, [codeHash, asTime(at)], ssoExchangeOf)),
532
1245
  takeSsoExchange: (codeHash, at) => tx(async (sql) => {
533
- const found = await first(sql, "DELETE FROM sso_exchanges WHERE code_hash = $1 RETURNING *", [codeHash], ssoExchangeOf);
534
- if (!found || Date.parse(found.expiresAt) <= Date.parse(asTime(at)))
1246
+ const exchange = await first(sql, `${ssoExchangeQuery} FOR SHARE OF app, token`, [codeHash, asTime(at)], ssoExchangeOf);
1247
+ if (!exchange)
535
1248
  return null;
536
- return found;
1249
+ return first(sql, "DELETE FROM sso_exchanges WHERE id = $1 RETURNING *", [exchange.id], ssoExchangeOf);
537
1250
  }),
538
1251
  insertServiceCredential: (row) => tx(async (sql) => {
539
1252
  await sql.query(`INSERT INTO service_credentials (id, org_id, name, secret_hash, app_ids, permissions, revoked_at, created_at)
@@ -555,19 +1268,75 @@ export function createSqlStore(database) {
555
1268
  }),
556
1269
  listWorkloadCredentials: (principalId) => tx(async (sql) => (await rows(sql, "SELECT * FROM workload_credentials WHERE principal_id = $1", [principalId])).map(workloadCredentialOf)),
557
1270
  insertAudience: (row) => tx(async (sql) => {
558
- await sql.query(`INSERT INTO audiences (id, org_id, name, identifier, app_id, created_at) VALUES ($1,$2,$3,$4,$5,$6::timestamptz)`, [row.id, row.orgId, row.name, row.identifier, row.appId, asTime(row.createdAt)]);
1271
+ if (row.appId)
1272
+ await assertApplicationScope(sql, row.appId, row.orgId, "conflict");
1273
+ if (row.environmentId) {
1274
+ const environment = await first(sql, "SELECT * FROM app_environments WHERE id = $1", [row.environmentId], environmentOf);
1275
+ if (!environment || environment.orgId !== row.orgId || (row.appId && environment.appId !== row.appId)) {
1276
+ throw new StoreError("conflict", "Choose an environment from this tenant.");
1277
+ }
1278
+ }
1279
+ await sql.query(`INSERT INTO audiences (id, org_id, name, identifier, app_id, environment_id, created_at) VALUES ($1,$2,$3,$4,$5,$6,$7::timestamptz)`, [row.id, row.orgId, row.name, row.identifier, row.appId, row.environmentId ?? null, asTime(row.createdAt)]);
1280
+ }),
1281
+ listAudiences: (orgId) => tx(async (sql) => (await rows(sql, `SELECT audience.* FROM audiences audience
1282
+ WHERE audience.org_id = $1 AND (audience.app_id IS NULL OR EXISTS (SELECT 1 FROM applications app
1283
+ WHERE app.id = audience.app_id AND app.org_id = $1 AND app.trashed_at IS NULL))`, [orgId])).map(audienceOf)),
1284
+ findAudience: (orgId, identifier) => tx((sql) => first(sql, `SELECT audience.* FROM audiences audience
1285
+ WHERE audience.org_id = $1 AND audience.identifier = $2 AND (audience.app_id IS NULL OR EXISTS (SELECT 1 FROM applications app
1286
+ WHERE app.id = audience.app_id AND app.org_id = $1 AND app.trashed_at IS NULL))`, [orgId, identifier], audienceOf)),
1287
+ findAudiencesForJwt: (audience) => tx(async (sql) => (await rows(sql, `SELECT audience.* FROM audiences audience
1288
+ LEFT JOIN app_environments env ON env.id = audience.environment_id
1289
+ WHERE (audience.identifier = $1 OR env.jwt_profile->>'audience' = $1)
1290
+ AND (audience.app_id IS NULL OR EXISTS (SELECT 1 FROM applications app
1291
+ WHERE app.id = audience.app_id AND app.org_id = audience.org_id AND app.trashed_at IS NULL))`, [audience])).map(audienceOf)),
1292
+ updateAudienceEnvironment: (id, orgId, environmentId) => tx(async (sql) => {
1293
+ if (environmentId) {
1294
+ const environment = await first(sql, "SELECT * FROM app_environments WHERE id = $1", [environmentId], environmentOf);
1295
+ const current = await first(sql, "SELECT * FROM audiences WHERE id = $1 AND org_id = $2", [id, orgId], audienceOf);
1296
+ if (!current)
1297
+ return null;
1298
+ if (!environment || environment.orgId !== orgId || (current.appId && environment.appId !== current.appId)) {
1299
+ throw new StoreError("conflict", "Choose an environment from this tenant.");
1300
+ }
1301
+ }
1302
+ return first(sql, `UPDATE audiences SET environment_id = $3 WHERE id = $1 AND org_id = $2
1303
+ AND (app_id IS NULL OR EXISTS (SELECT 1 FROM applications app WHERE app.id = audiences.app_id AND app.org_id = $2 AND app.trashed_at IS NULL))
1304
+ RETURNING *`, [id, orgId, environmentId], audienceOf);
559
1305
  }),
560
- listAudiences: (orgId) => tx(async (sql) => (await rows(sql, "SELECT * FROM audiences WHERE org_id = $1", [orgId])).map(audienceOf)),
561
- findAudience: (orgId, identifier) => tx((sql) => first(sql, "SELECT * FROM audiences WHERE org_id = $1 AND identifier = $2", [orgId, identifier], audienceOf)),
562
1306
  insertRole: (row) => tx(async (sql) => {
563
1307
  await sql.query(`INSERT INTO role_definitions (id, org_id, name, actions, created_at) VALUES ($1,$2,$3,$4,$5::timestamptz)`, [row.id, row.orgId, row.name, row.actions, asTime(row.createdAt)]);
564
1308
  }),
565
1309
  listRoles: (orgId) => tx(async (sql) => (await rows(sql, "SELECT * FROM role_definitions WHERE org_id = $1", [orgId])).map(roleOf)),
566
1310
  insertAssignment: (row) => tx(async (sql) => {
1311
+ // Serialize grants to the same identity so concurrent requests cannot create duplicates.
1312
+ const [principal] = await rows(sql, "SELECT enabled FROM workload_principals WHERE id = $1 AND org_id = $2 FOR UPDATE", [row.principalId, row.orgId]);
1313
+ const role = await rows(sql, "SELECT id FROM role_definitions WHERE id = $1 AND org_id = $2", [row.roleId, row.orgId]);
1314
+ if (!principal || !role.length)
1315
+ throw new StoreError("conflict", "Choose an app identity and role from this tenant.");
1316
+ if (!principal.enabled)
1317
+ throw new StoreError("conflict", "This app identity is disabled.");
1318
+ const duplicate = await rows(sql, `SELECT id FROM role_assignments
1319
+ WHERE org_id = $1 AND principal_id = $2 AND role_id = $3 AND rtrim(scope, '/') = rtrim($4, '/') LIMIT 1`, [row.orgId, row.principalId, row.roleId, row.scope]);
1320
+ if (duplicate.length)
1321
+ throw new StoreError("duplicate", "Role assignment already exists.");
567
1322
  await sql.query(`INSERT INTO role_assignments (id, org_id, principal_id, role_id, scope, created_at) VALUES ($1,$2,$3,$4,$5,$6::timestamptz)`, [row.id, row.orgId, row.principalId, row.roleId, row.scope, asTime(row.createdAt)]);
568
1323
  }),
569
1324
  listAssignments: (orgId, principalId) => tx(async (sql) => (await rows(sql, "SELECT * FROM role_assignments WHERE org_id = $1 AND ($2::text IS NULL OR principal_id = $2)", [orgId, principalId ?? null])).map(assignmentOf)),
1325
+ deleteAssignment: (id, orgId, audit) => tx(async (sql) => {
1326
+ const removed = await rows(sql, "DELETE FROM role_assignments WHERE id = $1 AND org_id = $2 RETURNING id", [id, orgId]);
1327
+ if (!removed.length)
1328
+ return false;
1329
+ await writeAudit(sql, audit);
1330
+ return true;
1331
+ }),
570
1332
  insertGatewayRoute: (row) => tx(async (sql) => {
1333
+ const audience = await first(sql, "SELECT * FROM audiences WHERE id = $1 AND org_id = $2", [row.audienceId, row.orgId], audienceOf);
1334
+ if (!audience)
1335
+ throw new StoreError("conflict", "Choose an audience from this tenant.");
1336
+ const applicationIds = new Set([audience.appId, appIdFromTenantResource(row.orgId, row.resource)].sort());
1337
+ for (const appId of applicationIds)
1338
+ if (appId)
1339
+ await assertApplicationScope(sql, appId, row.orgId, "conflict");
571
1340
  await sql.query(`INSERT INTO gateway_routes (id, org_id, audience_id, method, path, data_action, resource, created_at) VALUES ($1,$2,$3,$4,$5,$6,$7,$8::timestamptz)`, [row.id, row.orgId, row.audienceId, row.method, row.path, row.dataAction, row.resource, asTime(row.createdAt)]);
572
1341
  }),
573
1342
  listGatewayRoutes: (orgId) => tx(async (sql) => (await rows(sql, "SELECT * FROM gateway_routes WHERE ($1::text IS NULL OR org_id = $1)", [orgId ?? null])).map(gatewayRouteOf)),
@@ -577,16 +1346,21 @@ export function createSqlStore(database) {
577
1346
  throw new StoreError("not_found", "Route not found.");
578
1347
  }),
579
1348
  ...createSqlDirectory(tx),
1349
+ ...createSqlNotificationWebhookJobs(tx),
580
1350
  ping: () => tx(async (sql) => { await sql.query("SELECT 1"); }),
581
1351
  purgeExpired(at) {
582
1352
  return tx(async (sql) => {
583
1353
  const stamp = asTime(at);
584
1354
  const seconds = Math.floor(Date.parse(stamp) / 1000);
585
1355
  await sql.query("DELETE FROM sessions WHERE expires_at <= $1::timestamptz", [stamp]);
1356
+ await pruneSqlHostedHumanCredentials(sql, stamp);
1357
+ await sql.query("DELETE FROM cli_login_codes WHERE expires_at <= $1::timestamptz", [stamp]);
586
1358
  await sql.query("DELETE FROM email_challenges WHERE expires_at <= $1::timestamptz", [stamp]);
587
1359
  await sql.query("DELETE FROM authorization_requests WHERE expires_at <= $1::timestamptz", [stamp]);
588
1360
  await sql.query("DELETE FROM denied_jtis WHERE exp <= $1", [seconds]);
589
1361
  await sql.query("DELETE FROM sso_logins WHERE expires_at <= $1::timestamptz", [stamp]);
1362
+ await sql.query("DELETE FROM hosted_email_codes WHERE expires_at <= $1::timestamptz AND created_at <= $2::timestamptz", [stamp, new Date(Date.parse(stamp) - hostedEmailCodePolicy.sendWindowMs).toISOString()]);
1363
+ await sql.query("DELETE FROM hosted_sso_profiles WHERE expires_at <= $1::timestamptz", [stamp]);
590
1364
  await sql.query("DELETE FROM sso_exchanges WHERE expires_at <= $1::timestamptz", [stamp]);
591
1365
  });
592
1366
  },