@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
@@ -1,4 +1,9 @@
1
- import { asTime, asTimeOrNull, isExpired, StoreError } from "@x12i/keyrox-store";
1
+ import { randomBytes } from "node:crypto";
2
+ import { asTime, asTimeOrNull, invitationLifecycle, invitationPreview, isExpired, StoreError } from "@x12i/keyrox-store";
3
+ import { directoryHasOrganizations, directoryHasWorkspaces } from "@x12i/keyrox-types";
4
+ import { applySqlDirectoryAccess, clearSqlDirectoryProductRole, listSqlAccessChecks, saveSqlAccessCheck } from "./directory-access-sql.js";
5
+ import { insertSqlNotificationDelivery } from "./notification-deliveries.js";
6
+ import { hostedSsoIdentityOf } from "./rows.js";
2
7
  async function rows(sql, text, values = []) {
3
8
  const result = await sql.query(text, values);
4
9
  return result.rows;
@@ -63,11 +68,13 @@ function integerOrNull(row, key) {
63
68
  throw new Error(`Expected number ${key}.`);
64
69
  }
65
70
  function identityOf(row) {
71
+ const emailProofAt = timeOrNull(row, "email_proof_at");
66
72
  return {
67
73
  id: text(row, "id"), appId: text(row, "app_id"), environmentId: text(row, "environment_id"), orgId: text(row, "org_id"),
68
74
  kind: text(row, "kind"), email: textOrNull(row, "email"), passwordHash: textOrNull(row, "password_hash"),
69
75
  displayName: text(row, "display_name"), status: text(row, "status"),
70
- emailVerifiedAt: timeOrNull(row, "email_verified_at"), metadata: json(row, "metadata"),
76
+ emailVerifiedAt: timeOrNull(row, "email_verified_at"), ...(emailProofAt && { emailProofAt }),
77
+ ...(flag(row, "password_change_required") ? { passwordChangeRequired: true } : {}), metadata: json(row, "metadata"),
71
78
  createdAt: time(row, "created_at"), updatedAt: time(row, "updated_at"),
72
79
  };
73
80
  }
@@ -77,11 +84,41 @@ function membershipOf(row) {
77
84
  organizationId: text(row, "organization_id"), relation: text(row, "relation"), createdAt: time(row, "created_at"),
78
85
  };
79
86
  }
87
+ function workspaceOf(row) {
88
+ return {
89
+ id: text(row, "id"), appId: text(row, "app_id"), environmentId: text(row, "environment_id"),
90
+ organizationId: textOrNull(row, "organization_id"), name: text(row, "name"), status: text(row, "status"),
91
+ createdAt: time(row, "created_at"), updatedAt: time(row, "updated_at"),
92
+ };
93
+ }
94
+ function workspaceMemberOf(row) {
95
+ const roleId = textOrNull(row, "role_id");
96
+ return {
97
+ id: text(row, "id"), environmentId: text(row, "environment_id"), workspaceId: text(row, "workspace_id"),
98
+ identityId: text(row, "identity_id"), relation: text(row, "relation"), createdAt: time(row, "created_at"),
99
+ ...(roleId ? { roleId } : {}),
100
+ };
101
+ }
102
+ function onboardingResponseOf(row) {
103
+ const questions = typeof row.questions === "string" ? JSON.parse(row.questions) : row.questions;
104
+ return {
105
+ environmentId: text(row, "environment_id"), target: text(row, "target"),
106
+ subjectId: text(row, "subject_id"), questions: questions,
107
+ answers: json(row, "answers"), updatedAt: time(row, "updated_at"),
108
+ };
109
+ }
80
110
  function permissionOf(row) {
81
111
  return { id: text(row, "id"), environmentId: text(row, "environment_id"), key: text(row, "key"), description: text(row, "description"), createdAt: time(row, "created_at") };
82
112
  }
83
113
  function roleOf(row) {
84
- return { id: text(row, "id"), environmentId: text(row, "environment_id"), name: text(row, "name"), permissions: texts(row, "permissions"), inherits: texts(row, "inherits"), createdAt: time(row, "created_at") };
114
+ return {
115
+ id: text(row, "id"), environmentId: text(row, "environment_id"), name: text(row, "name"), permissions: texts(row, "permissions"),
116
+ inherits: texts(row, "inherits"), catalogRoleId: textOrNull(row, "catalog_role_id"), allowsOrganizationlessSignup: flag(row, "allows_organizationless_signup"),
117
+ ...(flag(row, "owner_access") ? { ownerAccess: true } : {}), createdAt: time(row, "created_at"),
118
+ };
119
+ }
120
+ function tenantRoleOf(row) {
121
+ return { id: text(row, "id"), orgId: text(row, "org_id"), name: text(row, "name"), description: text(row, "description"), createdAt: time(row, "created_at") };
85
122
  }
86
123
  function groupOf(row) {
87
124
  return { id: text(row, "id"), environmentId: text(row, "environment_id"), name: text(row, "name"), createdAt: time(row, "created_at") };
@@ -97,7 +134,8 @@ function bindingOf(row) {
97
134
  };
98
135
  }
99
136
  function featureOf(row) {
100
- return { id: text(row, "id"), environmentId: text(row, "environment_id"), key: text(row, "key"), enabled: flag(row, "enabled"), config: json(row, "config"), createdAt: time(row, "created_at") };
137
+ return { id: text(row, "id"), environmentId: text(row, "environment_id"), key: text(row, "key"), kind: text(row, "kind"),
138
+ enabled: flag(row, "enabled"), config: json(row, "config"), createdAt: time(row, "created_at") };
101
139
  }
102
140
  function assignmentOf(row) {
103
141
  return {
@@ -107,11 +145,35 @@ function assignmentOf(row) {
107
145
  };
108
146
  }
109
147
  function appWaitOf(row) {
148
+ const answers = Array.isArray(row.answers) ? row.answers : [];
149
+ const workspaceId = textOrNull(row, "invitation_workspace_id");
150
+ const roleId = textOrNull(row, "invitation_role_id");
151
+ const organizationId = textOrNull(row, "invitation_organization_id");
152
+ const delivery = textOrNull(row, "invitation_delivery");
153
+ const pendingWorkspaceIdentityId = textOrNull(row, "pending_workspace_identity_id");
154
+ const auditId = textOrNull(row, "invitation_audit_id");
155
+ const revokedAt = timeOrNull(row, "revoked_at");
110
156
  return {
111
157
  id: text(row, "id"), appId: text(row, "app_id"), environmentId: text(row, "environment_id"), email: text(row, "email"),
112
- status: text(row, "status"), tokenHash: textOrNull(row, "token_hash"), createdAt: time(row, "created_at"),
158
+ status: text(row, "status"), tokenHash: textOrNull(row, "token_hash"), createdAt: time(row, "created_at"), answers,
159
+ ...(roleId ? { invitation: {
160
+ roleId, ...(workspaceId ? { workspaceId } : {}), ...(organizationId ? { organizationId } : {}),
161
+ ...(delivery === "email" || delivery === "link" ? { delivery } : {}),
162
+ } } : {}),
163
+ ...(pendingWorkspaceIdentityId ? { pendingWorkspaceIdentityId } : {}),
164
+ ...(auditId ? { auditId } : {}),
165
+ ...(revokedAt ? { revokedAt } : {}),
113
166
  };
114
167
  }
168
+ function appWaitValues(row) {
169
+ return [row.id, row.appId, row.environmentId, row.email.toLowerCase(), row.status, row.tokenHash, asTime(row.createdAt), JSON.stringify(row.answers ?? []),
170
+ row.invitation?.workspaceId ?? null, row.invitation?.roleId ?? null, row.pendingWorkspaceIdentityId ?? null,
171
+ row.invitation?.organizationId ?? null, row.invitation?.delivery ?? null, row.auditId ?? null, asTimeOrNull(row.revokedAt ?? null)];
172
+ }
173
+ const appWaitlistInsert = `INSERT INTO app_waitlist (id, app_id, environment_id, email, status, token_hash, created_at, answers,
174
+ invitation_workspace_id, invitation_role_id, pending_workspace_identity_id,
175
+ invitation_organization_id, invitation_delivery, invitation_audit_id, revoked_at, confirmation_pending)
176
+ VALUES ($1, $2, $3, $4, $5, $6, $7::timestamptz, $8::jsonb, $9, $10, $11, $12, $13, $14, $15::timestamptz, $16)`;
115
177
  function platformWaitOf(row) {
116
178
  return { id: text(row, "id"), email: text(row, "email"), status: text(row, "status"), tokenHash: textOrNull(row, "token_hash"), createdAt: time(row, "created_at") };
117
179
  }
@@ -127,6 +189,212 @@ function signupOf(row) {
127
189
  return { mode: mode === "waiting-list" ? "waiting-list" : "open", explicit: flag(row, "explicit"), operators: texts(row, "operators") };
128
190
  }
129
191
  const openSignup = { mode: "open", explicit: false, operators: [] };
192
+ function identityValues(row) {
193
+ return [row.id, row.appId, row.environmentId, row.orgId, row.kind, row.email, row.passwordHash, row.displayName, row.status,
194
+ asTimeOrNull(row.emailVerifiedAt), JSON.stringify(row.metadata), asTime(row.createdAt), asTime(row.updatedAt), asTimeOrNull(row.emailProofAt ?? null),
195
+ row.passwordChangeRequired === true];
196
+ }
197
+ async function insertIdentity(sql, values) {
198
+ await sql.query(`INSERT INTO app_identities (
199
+ id, app_id, environment_id, org_id, kind, email, password_hash, display_name, status, email_verified_at, metadata, created_at, updated_at, email_proof_at, password_change_required
200
+ ) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10::timestamptz, $11::jsonb, $12::timestamptz, $13::timestamptz, $14::timestamptz, $15)`, values);
201
+ }
202
+ async function insertChallenge(sql, row, delivery) {
203
+ if (row.environmentId !== "platform") {
204
+ const scope = (await rows(sql, `SELECT application.org_id, environment.key_version FROM applications application
205
+ JOIN app_environments environment ON environment.app_id = application.id
206
+ WHERE environment.id = $1 AND application.trashed_at IS NULL FOR SHARE OF application, environment`, [row.environmentId]))[0];
207
+ if (!scope)
208
+ throw new StoreError("not_found", "Application environment not found.");
209
+ if (delivery && (delivery.environmentId !== row.environmentId || delivery.organizationId !== scope.org_id ||
210
+ delivery.environmentKeyVersion !== Number(scope.key_version)))
211
+ throw new StoreError("conflict", "Notification scope changed.");
212
+ }
213
+ else if (delivery) {
214
+ throw new StoreError("conflict", "Notification scope changed.");
215
+ }
216
+ await sql.query(`INSERT INTO directory_challenges (id, environment_id, identity_id, purpose, email, token_hash, expires_at, used_at, created_at)
217
+ VALUES ($1, $2, $3, $4, $5, $6, $7::timestamptz, $8::timestamptz, $9::timestamptz)`, [row.id, row.environmentId, row.identityId, row.purpose, row.email, row.tokenHash, asTime(row.expiresAt), asTimeOrNull(row.usedAt), asTime(row.createdAt)]);
218
+ await insertSqlNotificationDelivery(sql, delivery);
219
+ }
220
+ async function assertWorkspaceScope(sql, workspace) {
221
+ const model = await first(sql, `SELECT application.directory_model FROM applications AS application
222
+ JOIN app_environments AS environment ON environment.app_id = application.id
223
+ WHERE application.id = $1 AND environment.id = $2 AND application.trashed_at IS NULL AND application.status = 'active' AND environment.status = 'active'
224
+ FOR SHARE OF application, environment`, [workspace.appId, workspace.environmentId], (row) => text(row, "directory_model"));
225
+ if (!model || !directoryHasWorkspaces(model) || (model === "organizations-and-workspaces") !== (workspace.organizationId !== null)) {
226
+ throw new StoreError("conflict", "This workspace is incompatible with the application directory model.");
227
+ }
228
+ if (workspace.organizationId) {
229
+ const parent = await rows(sql, `SELECT id FROM app_identities WHERE id = $1 AND environment_id = $2 AND app_id = $3
230
+ AND kind = 'organization' AND status = 'active' FOR SHARE`, [workspace.organizationId, workspace.environmentId, workspace.appId]);
231
+ if (!parent.length)
232
+ throw new StoreError("conflict", "The workspace organization is unavailable in this environment.");
233
+ }
234
+ }
235
+ async function requireOrganizationScope(sql, environmentId) {
236
+ const model = await first(sql, `SELECT application.directory_model FROM applications AS application
237
+ JOIN app_environments AS environment ON environment.app_id = application.id
238
+ WHERE environment.id = $1 AND application.trashed_at IS NULL FOR SHARE OF application`, [environmentId], (row) => text(row, "directory_model"));
239
+ if (model === "people-only")
240
+ throw new StoreError("conflict", "Organizations are unavailable for this application.");
241
+ }
242
+ async function lockDirectoryChallengeApplication(sql, tokenHash, allowPlatform) {
243
+ if (allowPlatform && (await rows(sql, "SELECT id FROM directory_challenges WHERE token_hash = $1 AND environment_id = 'platform'", [tokenHash])).length)
244
+ return true;
245
+ const scope = await rows(sql, `SELECT app.id FROM directory_challenges challenge
246
+ JOIN app_environments env ON env.id = challenge.environment_id JOIN applications app ON app.id = env.app_id
247
+ WHERE challenge.token_hash = $1 AND app.trashed_at IS NULL FOR SHARE OF app`, [tokenHash]);
248
+ return scope.length > 0;
249
+ }
250
+ async function assertProductRoleCatalog(sql, environmentId, catalogRoleId) {
251
+ const scope = await rows(sql, `SELECT app.id FROM app_environments env JOIN applications app ON app.id = env.app_id
252
+ JOIN tenant_product_roles catalog ON catalog.org_id = app.org_id
253
+ WHERE env.id = $1 AND catalog.id = $2 AND app.trashed_at IS NULL FOR SHARE OF app`, [environmentId, catalogRoleId]);
254
+ if (!scope.length)
255
+ throw new StoreError("conflict", "Catalog role must belong to the application tenant.");
256
+ }
257
+ async function insertWorkspaceMember(sql, workspace, row) {
258
+ if (row.workspaceId !== workspace.id || row.environmentId !== workspace.environmentId) {
259
+ throw new StoreError("conflict", "The workspace member is unavailable in this environment.");
260
+ }
261
+ const identity = await rows(sql, `SELECT id FROM app_identities WHERE id = $1 AND environment_id = $2 AND app_id = $3
262
+ AND kind <> 'organization' AND status = 'active' FOR SHARE`, [row.identityId, row.environmentId, workspace.appId]);
263
+ if (!identity.length)
264
+ throw new StoreError("conflict", "The workspace member is unavailable in this environment.");
265
+ if (workspace.organizationId) {
266
+ const parentMembership = await rows(sql, `SELECT id FROM app_identity_memberships
267
+ WHERE environment_id = $1 AND identity_id = $2 AND organization_id = $3 FOR SHARE`, [row.environmentId, row.identityId, workspace.organizationId]);
268
+ if (!parentMembership.length)
269
+ throw new StoreError("conflict", "The workspace member must belong to its organization.");
270
+ }
271
+ await sql.query(`INSERT INTO app_workspace_memberships (id, environment_id, workspace_id, identity_id, relation, created_at, role_id)
272
+ VALUES ($1, $2, $3, $4, $5, $6::timestamptz, $7)`, [row.id, row.environmentId, row.workspaceId, row.identityId, row.relation, asTime(row.createdAt), row.roleId ?? null]);
273
+ }
274
+ async function workspaceInvitationTarget(sql, invite) {
275
+ if (!invite.invitation?.workspaceId)
276
+ return null;
277
+ const workspace = await first(sql, `SELECT workspace.* FROM app_workspaces AS workspace
278
+ JOIN app_environments AS environment ON environment.id = workspace.environment_id
279
+ JOIN applications AS application ON application.id = environment.app_id
280
+ JOIN app_product_roles AS role ON role.id = $4 AND role.environment_id = environment.id
281
+ WHERE workspace.app_id = $1 AND workspace.environment_id = $2 AND workspace.id = $3 AND workspace.status = 'active'
282
+ AND environment.status = 'active' AND application.status = 'active' AND application.trashed_at IS NULL
283
+ AND ((application.directory_model = 'workspaces' AND workspace.organization_id IS NULL)
284
+ OR (application.directory_model = 'organizations-and-workspaces' AND workspace.organization_id IS NOT NULL))
285
+ FOR SHARE OF workspace, role, environment, application`, [invite.appId, invite.environmentId, invite.invitation.workspaceId, invite.invitation.roleId], workspaceOf);
286
+ if (!workspace?.organizationId)
287
+ return workspace;
288
+ const parent = await rows(sql, `SELECT id FROM app_identities WHERE id = $1 AND kind = 'organization'
289
+ AND app_id = $2 AND environment_id = $3 AND status = 'active' FOR SHARE`, [workspace.organizationId, invite.appId, invite.environmentId]);
290
+ return parent.length ? workspace : null;
291
+ }
292
+ async function applyWorkspaceInvitation(sql, invite, challengeId, identityId, at) {
293
+ const workspace = await workspaceInvitationTarget(sql, invite);
294
+ if (!workspace || !invite.invitation)
295
+ return false;
296
+ if (workspace.organizationId) {
297
+ await sql.query(`INSERT INTO app_identity_memberships (id, environment_id, identity_id, organization_id, relation, created_at)
298
+ VALUES ($1, $2, $3, $4, 'member', $5::timestamptz) ON CONFLICT (identity_id, organization_id) DO NOTHING`, [`dms_${challengeId}`, invite.environmentId, identityId, workspace.organizationId, at]);
299
+ }
300
+ await sql.query(`INSERT INTO app_workspace_memberships (id, environment_id, workspace_id, identity_id, relation, created_at, role_id)
301
+ VALUES ($1, $2, $3, $4, 'member', $5::timestamptz, $6)
302
+ ON CONFLICT (environment_id, workspace_id, identity_id) DO UPDATE SET role_id = EXCLUDED.role_id`, [`wsm_${challengeId}`, invite.environmentId, workspace.id, identityId, at, invite.invitation.roleId]);
303
+ await sql.query("UPDATE directory_challenges SET used_at = COALESCE(used_at, $2::timestamptz) WHERE id = $1", [challengeId, at]);
304
+ await sql.query("UPDATE app_waitlist SET status = 'admitted', pending_workspace_identity_id = NULL WHERE id = $1", [invite.id]);
305
+ return true;
306
+ }
307
+ async function invitationIsAvailable(sql, invite) {
308
+ if (!invite.invitation?.roleId)
309
+ return false;
310
+ const model = await first(sql, `SELECT application.directory_model FROM applications AS application
311
+ JOIN app_environments AS environment ON environment.app_id = application.id
312
+ WHERE application.id = $1 AND environment.id = $2 AND application.trashed_at IS NULL AND application.status = 'active' AND environment.status = 'active'
313
+ FOR SHARE OF application, environment`, [invite.appId, invite.environmentId], (row) => text(row, "directory_model"));
314
+ const role = await rows(sql, "SELECT id FROM app_product_roles WHERE id = $1 AND environment_id = $2", [invite.invitation.roleId, invite.environmentId]);
315
+ if (!model || !role.length)
316
+ return false;
317
+ if (invite.invitation.workspaceId)
318
+ return !invite.invitation.organizationId && Boolean(await workspaceInvitationTarget(sql, invite));
319
+ if (model === "people-only")
320
+ return !invite.invitation.organizationId;
321
+ if (model !== "organizations" || !invite.invitation.organizationId)
322
+ return false;
323
+ const organization = await rows(sql, `SELECT id FROM app_identities WHERE id = $1 AND app_id = $2 AND environment_id = $3
324
+ AND kind = 'organization' AND status = 'active'`, [invite.invitation.organizationId, invite.appId, invite.environmentId]);
325
+ return organization.length > 0;
326
+ }
327
+ function invitationGrantRequest(invite, identityId, at, ids, ownerRoleId) {
328
+ const invitation = invite.invitation;
329
+ return {
330
+ appId: invite.appId, environmentId: invite.environmentId, identityId, roleId: invitation.roleId,
331
+ ...(invitation.workspaceId ? { workspaceId: invitation.workspaceId } : {}),
332
+ ...(!invitation.workspaceId && invitation.organizationId ? { organizationId: invitation.organizationId } : {}),
333
+ ownerRoleId, at, newMembershipId: ids.membershipId, newBindingId: ids.bindingId, newOrganizationMembershipId: ids.organizationMembershipId,
334
+ };
335
+ }
336
+ async function applyStoredInvitation(sql, invite, challengeId, identityId, at) {
337
+ if (!invite.invitation || invite.invitation.delivery === "link")
338
+ return false;
339
+ if (invite.invitation.workspaceId)
340
+ return applyWorkspaceInvitation(sql, invite, challengeId, identityId, at);
341
+ if (!await invitationIsAvailable(sql, invite))
342
+ return false;
343
+ const owner = await first(sql, "SELECT id FROM app_product_roles WHERE environment_id = $1 AND owner_access", [invite.environmentId], (row) => text(row, "id"));
344
+ const saved = await applySqlDirectoryAccess(sql, invitationGrantRequest(invite, identityId, at, {
345
+ membershipId: `wsm_${challengeId}`, bindingId: `rbd_${challengeId}`, organizationMembershipId: `dms_${challengeId}`,
346
+ }, owner));
347
+ if (!saved.roleId)
348
+ return false;
349
+ await sql.query("UPDATE directory_challenges SET used_at = COALESCE(used_at, $2::timestamptz) WHERE id = $1", [challengeId, at]);
350
+ await sql.query("UPDATE app_waitlist SET status = 'admitted', pending_workspace_identity_id = NULL WHERE id = $1", [invite.id]);
351
+ return true;
352
+ }
353
+ async function savedInvitationGrant(sql, invite, identityId) {
354
+ const invitation = invite.invitation;
355
+ if (!invitation)
356
+ return { membershipId: null, bindingId: null, roleId: "" };
357
+ if (invitation.workspaceId) {
358
+ const membership = await first(sql, `SELECT id, role_id FROM app_workspace_memberships
359
+ WHERE environment_id = $1 AND workspace_id = $2 AND identity_id = $3`, [invite.environmentId, invitation.workspaceId, identityId], (row) => ({ id: text(row, "id"), roleId: textOrNull(row, "role_id") }));
360
+ return { membershipId: membership?.id ?? null, bindingId: null, roleId: membership?.roleId ?? invitation.roleId };
361
+ }
362
+ const binding = await first(sql, `SELECT id, role_id FROM app_role_bindings
363
+ WHERE environment_id = $1 AND subject_type = 'identity' AND subject_id = $2 AND resource IS NULL
364
+ AND organization_id IS NOT DISTINCT FROM $3::text
365
+ ORDER BY created_at, id LIMIT 1`, [invite.environmentId, identityId, invitation.organizationId ?? null], (row) => ({ id: text(row, "id"), roleId: text(row, "role_id") }));
366
+ return { membershipId: null, bindingId: binding?.id ?? null, roleId: binding?.roleId ?? invitation.roleId };
367
+ }
368
+ async function acceptWorkspaceInvitation(sql, identity, at, expectedTokenHash) {
369
+ if (!identity.emailVerifiedAt || identity.status !== "active" || identity.kind !== "user" || !identity.email)
370
+ return false;
371
+ const invite = await first(sql, `SELECT * FROM app_waitlist WHERE app_id = $1 AND environment_id = $2 AND lower(email) = lower($3)
372
+ AND status = 'invited' AND invitation_role_id IS NOT NULL AND invitation_delivery IS DISTINCT FROM 'link' FOR UPDATE`, [identity.appId, identity.environmentId, identity.email], appWaitOf);
373
+ if (!invite || (expectedTokenHash && (invite.tokenHash !== expectedTokenHash || invite.pendingWorkspaceIdentityId)))
374
+ return false;
375
+ const challenge = await first(sql, `SELECT * FROM directory_challenges WHERE token_hash = $1 AND environment_id = $2
376
+ AND lower(email) = lower($3) AND purpose = 'admit' FOR UPDATE`, [invite.tokenHash, invite.environmentId, invite.email], challengeOf);
377
+ if (!challenge)
378
+ return false;
379
+ if (isExpired(challenge.expiresAt, at) || (invite.pendingWorkspaceIdentityId
380
+ ? invite.pendingWorkspaceIdentityId !== identity.id || !challenge.usedAt : Boolean(challenge.usedAt)))
381
+ return false;
382
+ return applyStoredInvitation(sql, invite, challenge.id, identity.id, at);
383
+ }
384
+ function findHostedSsoLink(sql, environmentId, authority, subject) {
385
+ return first(sql, `SELECT * FROM hosted_sso_identities WHERE environment_id = $1 AND authority = $2 AND subject = $3`, [environmentId, authority, subject], hostedSsoIdentityOf);
386
+ }
387
+ async function saveHostedSsoLink(sql, row) {
388
+ const { environmentId, authority, subject, identityId } = row;
389
+ const identity = await rows(sql, "SELECT id FROM app_identities WHERE id = $1 AND environment_id = $2 AND kind = 'user'", [identityId, environmentId]);
390
+ if (!identity.length)
391
+ throw new StoreError("conflict", "Hosted sign-in identity is missing.");
392
+ const inserted = await rows(sql, `INSERT INTO hosted_sso_identities (environment_id, authority, subject, identity_id)
393
+ VALUES ($1, $2, $3, $4) ON CONFLICT (environment_id, authority, subject) DO NOTHING RETURNING identity_id`, [environmentId, authority, subject, identityId]);
394
+ if (inserted.length)
395
+ return true;
396
+ return (await findHostedSsoLink(sql, environmentId, authority, subject))?.identityId === identityId;
397
+ }
130
398
  export function createSqlDirectory(tx) {
131
399
  return {
132
400
  countUsers: () => tx(async (sql) => Number((await rows(sql, "SELECT count(*)::int AS count FROM users"))[0]?.count ?? 0)),
@@ -135,40 +403,237 @@ export function createSqlDirectory(tx) {
135
403
  await sql.query(`INSERT INTO platform_settings (id, signup_mode, explicit, operators) VALUES ('platform', $1, $2, $3::text[])
136
404
  ON CONFLICT (id) DO UPDATE SET signup_mode = $1, explicit = $2, operators = $3::text[]`, [row.mode, row.explicit, row.operators]);
137
405
  }),
138
- savePlatformWaitlist: (row) => tx(async (sql) => {
406
+ insertPlatformWaitlist: (row) => tx(async (sql) => (await rows(sql, `INSERT INTO platform_waitlist
407
+ (id, email, status, token_hash, created_at, confirmation_pending) VALUES ($1, $2, $3, $4, $5::timestamptz, true)
408
+ ON CONFLICT DO NOTHING RETURNING id`, [row.id, row.email.toLowerCase(), row.status, row.tokenHash, asTime(row.createdAt)])).length > 0),
409
+ savePlatformWaitlist: (row, challenge) => tx(async (sql) => {
139
410
  const updated = await rows(sql, "UPDATE platform_waitlist SET email = $2, status = $3, token_hash = $4, created_at = $5::timestamptz WHERE id = $1 RETURNING id", [row.id, row.email, row.status, row.tokenHash, asTime(row.createdAt)]);
140
411
  if (!updated.length) {
141
412
  await sql.query("INSERT INTO platform_waitlist (id, email, status, token_hash, created_at) VALUES ($1, $2, $3, $4, $5::timestamptz)", [row.id, row.email, row.status, row.tokenHash, asTime(row.createdAt)]);
142
413
  }
414
+ if (challenge)
415
+ await insertChallenge(sql, challenge);
143
416
  }),
144
417
  listPlatformWaitlist: () => tx(async (sql) => (await rows(sql, "SELECT * FROM platform_waitlist ORDER BY created_at, id")).map(platformWaitOf)),
145
418
  findPlatformWaitlist: (email) => tx((sql) => first(sql, "SELECT * FROM platform_waitlist WHERE lower(email) = lower($1)", [email], platformWaitOf)),
146
419
  saveDirectoryIdentity: (row) => tx(async (sql) => {
147
- const values = [row.id, row.appId, row.environmentId, row.orgId, row.kind, row.email, row.passwordHash, row.displayName, row.status, asTimeOrNull(row.emailVerifiedAt), JSON.stringify(row.metadata), asTime(row.createdAt), asTime(row.updatedAt)];
420
+ const model = await first(sql, `SELECT application.directory_model FROM applications application
421
+ JOIN app_environments environment ON application.id = environment.app_id
422
+ WHERE application.id = $1 AND environment.id = $2 AND application.org_id = $3 AND application.trashed_at IS NULL
423
+ FOR SHARE OF application`, [row.appId, row.environmentId, row.orgId], (application) => text(application, "directory_model"));
424
+ if (!model)
425
+ throw new StoreError("conflict", "Identity must match its application environment and tenant.");
426
+ if (row.kind === "organization" && model === "people-only")
427
+ throw new StoreError("conflict", "Organizations are unavailable for this application.");
428
+ const values = identityValues(row);
148
429
  const updated = await rows(sql, `UPDATE app_identities SET app_id = $2, environment_id = $3, org_id = $4, kind = $5, email = $6, password_hash = $7,
149
- display_name = $8, status = $9, email_verified_at = $10::timestamptz, metadata = $11::jsonb, created_at = $12::timestamptz, updated_at = $13::timestamptz
150
- WHERE id = $1 RETURNING id`, values);
430
+ display_name = $8, status = $9,
431
+ email_verified_at = CASE WHEN lower(email) = lower($6) AND email_proof_at IS NOT NULL
432
+ THEN COALESCE($10::timestamptz, email_verified_at) ELSE $10::timestamptz END,
433
+ email_proof_at = CASE WHEN $5 = 'user' AND lower(email) = lower($6) THEN email_proof_at END,
434
+ metadata = $11::jsonb, created_at = $12::timestamptz, updated_at = $13::timestamptz, password_change_required = $14
435
+ WHERE id = $1 AND app_id = $2 AND environment_id = $3 AND org_id = $4 RETURNING id`, [...values.slice(0, 13), values[14]]);
151
436
  if (!updated.length) {
152
- await sql.query(`INSERT INTO app_identities (
153
- id, app_id, environment_id, org_id, kind, email, password_hash, display_name, status, email_verified_at, metadata, created_at, updated_at
154
- ) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10::timestamptz, $11::jsonb, $12::timestamptz, $13::timestamptz)`, values);
437
+ if (row.kind === "organization" && model === "workspaces")
438
+ throw new StoreError("conflict", "New organizations are unavailable for this application.");
439
+ await insertIdentity(sql, values);
155
440
  }
156
441
  }),
442
+ proveDirectoryEmail: (identityId, environmentId, email, at) => tx((sql) => first(sql, `UPDATE app_identities AS identity
443
+ SET email_verified_at = COALESCE(identity.email_verified_at, $4::timestamptz),
444
+ email_proof_at = GREATEST(identity.email_proof_at, $4::timestamptz),
445
+ updated_at = GREATEST(identity.updated_at, $4::timestamptz)
446
+ FROM applications AS application, app_environments AS environment
447
+ WHERE identity.id = $1 AND identity.environment_id = $2 AND lower(identity.email) = lower($3)
448
+ AND identity.kind = 'user' AND identity.status = 'active'
449
+ AND application.id = identity.app_id AND application.org_id = identity.org_id
450
+ AND application.trashed_at IS NULL AND application.status = 'active'
451
+ AND environment.id = identity.environment_id AND environment.app_id = application.id
452
+ AND environment.org_id = application.org_id AND environment.status = 'active'
453
+ RETURNING identity.*`, [identityId, environmentId, email, asTime(at)], identityOf)),
454
+ signupDirectoryPerson: ({ identity, organization, membership, bindingId, challenge, allowOrganizationless, admissionTokenHash, hostedSsoLink, notificationDelivery }) => tx(async (sql) => {
455
+ const environmentId = identity.environmentId;
456
+ const environment = (await rows(sql, `SELECT environment.default_signup_role_id, application.directory_model, environment.key_version
457
+ FROM app_environments AS environment JOIN applications AS application ON application.id = environment.app_id
458
+ WHERE environment.id = $1 AND application.id = $2 AND application.org_id = $3 AND application.trashed_at IS NULL
459
+ FOR SHARE OF application, environment`, [environmentId, identity.appId, identity.orgId]))[0];
460
+ if (!environment)
461
+ throw new StoreError("not_found", "Environment not found.");
462
+ let workspaceInvite;
463
+ if (admissionTokenHash) {
464
+ const invite = await first(sql, `SELECT * FROM app_waitlist WHERE token_hash = $1 AND app_id = $2 AND environment_id = $3
465
+ AND lower(email) = lower($4) AND status = 'invited' FOR UPDATE`, [admissionTokenHash, identity.appId, environmentId, identity.email], appWaitOf);
466
+ if (!invite)
467
+ throw new StoreError("challenge_invalid", "Waiting list invitation is no longer available.");
468
+ if (invite.invitation?.delivery === "link")
469
+ throw new StoreError("challenge_invalid", "Waiting list invitation is no longer available.");
470
+ const used = await rows(sql, "UPDATE directory_challenges SET used_at = $4::timestamptz WHERE token_hash = $1 AND environment_id = $2 AND lower(email) = lower($3) AND purpose = 'admit' AND used_at IS NULL AND expires_at > $4::timestamptz RETURNING id", [admissionTokenHash, environmentId, identity.email, asTime(identity.createdAt)]);
471
+ if (!used.length)
472
+ throw new StoreError("challenge_invalid", "Waiting list invitation is no longer available.");
473
+ if (invite.invitation) {
474
+ if (!await workspaceInvitationTarget(sql, invite))
475
+ throw new StoreError("challenge_invalid", "The invited workspace or role is no longer available.");
476
+ workspaceInvite = { invite, challengeId: text(used[0], "id") };
477
+ await sql.query("UPDATE app_waitlist SET pending_workspace_identity_id = $2 WHERE id = $1", [invite.id, identity.id]);
478
+ }
479
+ else
480
+ await sql.query("UPDATE app_waitlist SET status = 'admitted' WHERE id = $1", [invite.id]);
481
+ }
482
+ const roleId = workspaceInvite ? null : textOrNull(environment, "default_signup_role_id");
483
+ const roleAllows = allowOrganizationless && roleId ? await first(sql, "SELECT allows_organizationless_signup FROM app_product_roles WHERE id = $1 AND environment_id = $2 FOR SHARE", [roleId, environmentId], (row) => flag(row, "allows_organizationless_signup")) : false;
484
+ const organizationCreated = !workspaceInvite && directoryHasOrganizations(text(environment, "directory_model")) && roleAllows !== true;
485
+ await insertIdentity(sql, identityValues(identity));
486
+ if (workspaceInvite && identity.emailVerifiedAt && !await applyWorkspaceInvitation(sql, workspaceInvite.invite, workspaceInvite.challengeId, identity.id, asTime(identity.createdAt))) {
487
+ throw new StoreError("challenge_invalid", "The invited workspace or role is no longer available.");
488
+ }
489
+ if (hostedSsoLink && (hostedSsoLink.identityId !== identity.id || hostedSsoLink.environmentId !== environmentId ||
490
+ !await saveHostedSsoLink(sql, hostedSsoLink))) {
491
+ throw new StoreError("conflict", "This provider account is linked to another profile.");
492
+ }
493
+ if (organizationCreated) {
494
+ await insertIdentity(sql, identityValues(organization));
495
+ await sql.query("INSERT INTO app_identity_memberships (id, environment_id, identity_id, organization_id, relation, created_at) VALUES ($1, $2, $3, $4, $5, $6::timestamptz)", [membership.id, environmentId, identity.id, organization.id, membership.relation, asTime(membership.createdAt)]);
496
+ }
497
+ if (challenge)
498
+ await insertChallenge(sql, challenge);
499
+ if (roleId)
500
+ await sql.query(`INSERT INTO app_role_bindings (id, environment_id, role_id, subject_type, subject_id, organization_id, resource, created_at)
501
+ VALUES ($1, $2, $3, 'identity', $4, NULL, NULL, $5::timestamptz)`, [bindingId, environmentId, roleId, identity.id, asTime(identity.createdAt)]);
502
+ if (notificationDelivery && (notificationDelivery.environmentId !== environmentId || notificationDelivery.organizationId !== identity.orgId ||
503
+ notificationDelivery.environmentKeyVersion !== Number(environment.key_version)))
504
+ throw new StoreError("conflict", "Notification scope changed.");
505
+ await insertSqlNotificationDelivery(sql, notificationDelivery);
506
+ return { organizationCreated };
507
+ }),
508
+ getDirectorySignupRole: (environmentId) => tx(async (sql) => {
509
+ return first(sql, "SELECT default_signup_role_id FROM app_environments WHERE id = $1", [environmentId], (row) => textOrNull(row, "default_signup_role_id"));
510
+ }),
511
+ findHostedSsoIdentity: (environmentId, authority, subject) => tx((sql) => findHostedSsoLink(sql, environmentId, authority, subject)),
512
+ listHostedSsoIdentityIds: (environmentId) => tx(async (sql) => (await rows(sql, "SELECT DISTINCT identity_id FROM hosted_sso_identities WHERE environment_id = $1", [environmentId])).map((row) => text(row, "identity_id"))),
513
+ saveHostedSsoIdentity: (row) => tx((sql) => saveHostedSsoLink(sql, row)),
514
+ setDirectorySignupRole: (environmentId, roleId) => tx(async (sql) => {
515
+ const updated = await rows(sql, `UPDATE app_environments SET default_signup_role_id = $2
516
+ WHERE id = $1 AND ($2::text IS NULL OR EXISTS (SELECT 1 FROM app_product_roles WHERE id = $2 AND environment_id = $1))
517
+ RETURNING id`, [environmentId, roleId]);
518
+ if (!updated.length)
519
+ throw new StoreError("not_found", "The role is unavailable in this environment.");
520
+ }),
157
521
  getDirectoryIdentity: (id) => tx((sql) => first(sql, "SELECT * FROM app_identities WHERE id = $1", [id], identityOf)),
158
522
  listDirectoryIdentities: (environmentId) => tx(async (sql) => (await rows(sql, "SELECT * FROM app_identities WHERE environment_id = $1 ORDER BY created_at, id", [environmentId])).map(identityOf)),
159
- findDirectoryIdentityByEmail: (environmentId, email) => tx((sql) => first(sql, "SELECT * FROM app_identities WHERE environment_id = $1 AND lower(email) = lower($2)", [environmentId, email], identityOf)),
523
+ findDirectoryIdentityByEmail: (environmentId, email) => tx((sql) => first(sql, `SELECT * FROM app_identities
524
+ WHERE environment_id = $1 AND lower(email) = lower($2) AND kind <> 'organization'
525
+ ORDER BY CASE kind WHEN 'user' THEN 0 WHEN 'account' THEN 1 ELSE 2 END, id LIMIT 1`, [environmentId, email], identityOf)),
160
526
  saveDirectoryMembership: (row) => tx(async (sql) => {
527
+ await requireOrganizationScope(sql, row.environmentId);
161
528
  const updated = await rows(sql, "UPDATE app_identity_memberships SET environment_id = $2, identity_id = $3, organization_id = $4, relation = $5, created_at = $6::timestamptz WHERE id = $1 RETURNING id", [row.id, row.environmentId, row.identityId, row.organizationId, row.relation, asTime(row.createdAt)]);
162
529
  if (!updated.length) {
163
530
  await sql.query("INSERT INTO app_identity_memberships (id, environment_id, identity_id, organization_id, relation, created_at) VALUES ($1, $2, $3, $4, $5, $6::timestamptz)", [row.id, row.environmentId, row.identityId, row.organizationId, row.relation, asTime(row.createdAt)]);
164
531
  }
165
532
  }),
166
533
  deleteDirectoryMembership: (id) => tx(async (sql) => {
167
- const removed = await rows(sql, "DELETE FROM app_identity_memberships WHERE id = $1 RETURNING id", [id]);
168
- if (!removed.length)
169
- throw new StoreError("not_found", "Record not found.");
534
+ const member = await first(sql, "SELECT * FROM app_identity_memberships WHERE id = $1", [id], membershipOf);
535
+ if (!member)
536
+ throw new StoreError("not_found", "Membership not found.");
537
+ await sql.query("SELECT id FROM app_identities WHERE id = $1 AND environment_id = $2 FOR UPDATE", [member.organizationId, member.environmentId]);
538
+ const current = await first(sql, "SELECT * FROM app_identity_memberships WHERE id = $1 FOR UPDATE", [id], membershipOf);
539
+ if (!current || current.organizationId !== member.organizationId || current.environmentId !== member.environmentId) {
540
+ throw new StoreError("not_found", "Membership not found.");
541
+ }
542
+ if (current.relation === "owner") {
543
+ const replacement = await rows(sql, `SELECT id FROM app_identity_memberships
544
+ WHERE organization_id = $1 AND environment_id = $2 AND relation = 'owner' AND id <> $3 LIMIT 1`, [current.organizationId, current.environmentId, id]);
545
+ if (!replacement.length)
546
+ throw new StoreError("last_owner", "An organization must keep an owner.");
547
+ }
548
+ await sql.query("DELETE FROM app_identity_memberships WHERE id = $1", [id]);
170
549
  }),
171
550
  listDirectoryMemberships: (environmentId) => tx(async (sql) => (await rows(sql, "SELECT * FROM app_identity_memberships WHERE environment_id = $1 ORDER BY created_at, id", [environmentId])).map(membershipOf)),
551
+ createDirectoryWorkspace: (workspace, owner, organizationMembership) => tx(async (sql) => {
552
+ if (organizationMembership) {
553
+ await requireOrganizationScope(sql, organizationMembership.environmentId);
554
+ const existing = await rows(sql, `SELECT id FROM app_identity_memberships
555
+ WHERE environment_id = $1 AND identity_id = $2 AND organization_id = $3`, [organizationMembership.environmentId, organizationMembership.identityId, organizationMembership.organizationId]);
556
+ if (existing.length)
557
+ throw new StoreError("duplicate", "Duplicate key.");
558
+ await sql.query(`INSERT INTO app_identity_memberships (id, environment_id, identity_id, organization_id, relation, created_at)
559
+ VALUES ($1, $2, $3, $4, $5, $6::timestamptz)`, [
560
+ organizationMembership.id, organizationMembership.environmentId, organizationMembership.identityId,
561
+ organizationMembership.organizationId, organizationMembership.relation, asTime(organizationMembership.createdAt),
562
+ ]);
563
+ }
564
+ await assertWorkspaceScope(sql, workspace);
565
+ if (owner.relation !== "owner")
566
+ throw new StoreError("conflict", "A workspace must have an owner.");
567
+ await sql.query(`INSERT INTO app_workspaces (id, app_id, environment_id, organization_id, name, status, created_at, updated_at)
568
+ VALUES ($1, $2, $3, $4, $5, $6, $7::timestamptz, $8::timestamptz)`, [
569
+ workspace.id, workspace.appId, workspace.environmentId, workspace.organizationId, workspace.name, workspace.status,
570
+ asTime(workspace.createdAt), asTime(workspace.updatedAt),
571
+ ]);
572
+ await insertWorkspaceMember(sql, workspace, owner);
573
+ }),
574
+ getDirectoryWorkspace: (environmentId, id) => tx((sql) => first(sql, "SELECT * FROM app_workspaces WHERE environment_id = $1 AND id = $2", [environmentId, id], workspaceOf)),
575
+ listDirectoryWorkspaces: (environmentId) => tx(async (sql) => (await rows(sql, "SELECT * FROM app_workspaces WHERE environment_id = $1 ORDER BY created_at, id", [environmentId])).map(workspaceOf)),
576
+ updateDirectoryWorkspace: (environmentId, id, patch) => tx(async (sql) => {
577
+ if (patch.status === "active") {
578
+ const workspace = await first(sql, "SELECT * FROM app_workspaces WHERE environment_id = $1 AND id = $2", [environmentId, id], workspaceOf);
579
+ if (!workspace)
580
+ return null;
581
+ await assertWorkspaceScope(sql, workspace);
582
+ }
583
+ return first(sql, `UPDATE app_workspaces SET name = COALESCE($3, name), status = COALESCE($4, status), updated_at = $5::timestamptz
584
+ WHERE environment_id = $1 AND id = $2 RETURNING *`, [environmentId, id, patch.name ?? null, patch.status ?? null, asTime(patch.updatedAt)], workspaceOf);
585
+ }),
586
+ addDirectoryWorkspaceMembership: (row) => tx(async (sql) => {
587
+ const scope = [row.environmentId, row.workspaceId];
588
+ const workspace = await first(sql, "SELECT * FROM app_workspaces WHERE environment_id = $1 AND id = $2 AND status = 'active'", scope, workspaceOf);
589
+ if (!workspace)
590
+ throw new StoreError("not_found", "Workspace not found.");
591
+ await assertWorkspaceScope(sql, workspace);
592
+ const locked = await rows(sql, "SELECT id FROM app_workspaces WHERE environment_id = $1 AND id = $2 AND status = 'active' FOR UPDATE", scope);
593
+ if (!locked.length)
594
+ throw new StoreError("not_found", "Workspace not found.");
595
+ await insertWorkspaceMember(sql, workspace, row);
596
+ }),
597
+ listDirectoryWorkspaceMemberships: (environmentId) => tx(async (sql) => (await rows(sql, "SELECT * FROM app_workspace_memberships WHERE environment_id = $1 ORDER BY created_at, id", [environmentId])).map(workspaceMemberOf)),
598
+ removeDirectoryWorkspaceMembership: (environmentId, workspaceId, membershipId) => tx(async (sql) => {
599
+ await sql.query("SELECT id FROM app_workspaces WHERE environment_id = $1 AND id = $2 FOR UPDATE", [environmentId, workspaceId]);
600
+ const membership = await first(sql, "SELECT * FROM app_workspace_memberships WHERE environment_id = $1 AND workspace_id = $2 AND id = $3", [environmentId, workspaceId, membershipId], workspaceMemberOf);
601
+ if (!membership)
602
+ throw new StoreError("not_found", "Workspace membership not found.");
603
+ if (membership.relation === "owner") {
604
+ const replacement = await rows(sql, `SELECT id FROM app_workspace_memberships
605
+ WHERE environment_id = $1 AND workspace_id = $2 AND id <> $3 AND relation = 'owner' LIMIT 1`, [environmentId, workspaceId, membershipId]);
606
+ if (!replacement.length)
607
+ throw new StoreError("last_owner", "A workspace must keep an owner.");
608
+ }
609
+ if (membership.roleId) {
610
+ const ownerRole = await rows(sql, "SELECT id FROM app_product_roles WHERE environment_id = $1 AND owner_access AND id = $2", [environmentId, membership.roleId]);
611
+ if (ownerRole.length) {
612
+ const replacement = await rows(sql, `SELECT id FROM app_workspace_memberships
613
+ WHERE environment_id = $1 AND workspace_id = $2 AND id <> $3 AND role_id = $4 LIMIT 1`, [environmentId, workspaceId, membershipId, membership.roleId]);
614
+ if (!replacement.length)
615
+ throw new StoreError("last_owner_access", "Assign owner access to another person in this scope first.");
616
+ }
617
+ }
618
+ await sql.query("DELETE FROM app_access_checks WHERE environment_id = $1 AND identity_id = $2 AND workspace_id = $3", [environmentId, membership.identityId, workspaceId]);
619
+ await sql.query("DELETE FROM app_workspace_memberships WHERE id = $1", [membership.id]);
620
+ }),
621
+ applyDirectoryAccess: (request) => tx((sql) => applySqlDirectoryAccess(sql, request)),
622
+ clearDirectoryProductRole: (input) => tx((sql) => clearSqlDirectoryProductRole(sql, input)),
623
+ saveDirectoryAccessCheck: (row) => tx((sql) => saveSqlAccessCheck(sql, row)),
624
+ listDirectoryAccessChecks: (environmentId, identityId) => tx((sql) => listSqlAccessChecks(sql, environmentId, identityId)),
625
+ getDirectoryOnboardingResponse: (environmentId, target, subjectId) => tx((sql) => first(sql, "SELECT * FROM app_onboarding_responses WHERE environment_id = $1 AND target = $2 AND subject_id = $3", [environmentId, target, subjectId], onboardingResponseOf)),
626
+ saveDirectoryOnboardingResponse: (row) => tx(async (sql) => {
627
+ const subject = row.target === "workspace"
628
+ ? await rows(sql, "SELECT id FROM app_workspaces WHERE environment_id = $1 AND id = $2", [row.environmentId, row.subjectId])
629
+ : await rows(sql, "SELECT id FROM app_identities WHERE environment_id = $1 AND id = $2 AND kind = $3", [row.environmentId, row.subjectId, row.target]);
630
+ if (!subject.length)
631
+ throw new StoreError("not_found", "Onboarding subject not found.");
632
+ await sql.query(`INSERT INTO app_onboarding_responses (environment_id, target, subject_id, questions, answers, updated_at)
633
+ VALUES ($1, $2, $3, $4::jsonb, $5::jsonb, $6::timestamptz)
634
+ ON CONFLICT (environment_id, target, subject_id) DO UPDATE SET
635
+ questions = EXCLUDED.questions, answers = EXCLUDED.answers, updated_at = EXCLUDED.updated_at`, [row.environmentId, row.target, row.subjectId, JSON.stringify(row.questions), JSON.stringify(row.answers), asTime(row.updatedAt)]);
636
+ }),
172
637
  saveProductPermission: (row) => tx(async (sql) => {
173
638
  const updated = await rows(sql, "UPDATE app_permissions SET environment_id = $2, key = $3, description = $4, created_at = $5::timestamptz WHERE id = $1 RETURNING id", [row.id, row.environmentId, row.key, row.description, asTime(row.createdAt)]);
174
639
  if (!updated.length)
@@ -181,9 +646,12 @@ export function createSqlDirectory(tx) {
181
646
  }),
182
647
  listProductPermissions: (environmentId) => tx(async (sql) => (await rows(sql, "SELECT * FROM app_permissions WHERE environment_id = $1 ORDER BY created_at, id", [environmentId])).map(permissionOf)),
183
648
  saveProductRole: (row) => tx(async (sql) => {
184
- const updated = await rows(sql, "UPDATE app_product_roles SET environment_id = $2, name = $3, permissions = $4::text[], inherits = $5::text[], created_at = $6::timestamptz WHERE id = $1 RETURNING id", [row.id, row.environmentId, row.name, row.permissions, row.inherits, asTime(row.createdAt)]);
649
+ if (row.catalogRoleId)
650
+ await assertProductRoleCatalog(sql, row.environmentId, row.catalogRoleId);
651
+ const fields = [row.id, row.environmentId, row.name, row.permissions, row.inherits, asTime(row.createdAt), row.allowsOrganizationlessSignup === true, row.ownerAccess === true];
652
+ const updated = await rows(sql, "UPDATE app_product_roles SET environment_id = $2, name = $3, permissions = $4::text[], inherits = $5::text[], created_at = $6::timestamptz, allows_organizationless_signup = $7, owner_access = $8 WHERE id = $1 RETURNING id", fields);
185
653
  if (!updated.length)
186
- await sql.query("INSERT INTO app_product_roles (id, environment_id, name, permissions, inherits, created_at) VALUES ($1, $2, $3, $4::text[], $5::text[], $6::timestamptz)", [row.id, row.environmentId, row.name, row.permissions, row.inherits, asTime(row.createdAt)]);
654
+ await sql.query("INSERT INTO app_product_roles (id, environment_id, name, permissions, inherits, created_at, allows_organizationless_signup, owner_access, catalog_role_id) VALUES ($1, $2, $3, $4::text[], $5::text[], $6::timestamptz, $7, $8, $9)", [...fields, row.catalogRoleId ?? null]);
187
655
  }),
188
656
  deleteProductRole: (id) => tx(async (sql) => {
189
657
  const removed = await rows(sql, "DELETE FROM app_product_roles WHERE id = $1 RETURNING id", [id]);
@@ -191,6 +659,29 @@ export function createSqlDirectory(tx) {
191
659
  throw new StoreError("not_found", "Record not found.");
192
660
  }),
193
661
  listProductRoles: (environmentId) => tx(async (sql) => (await rows(sql, "SELECT * FROM app_product_roles WHERE environment_id = $1 ORDER BY created_at, id", [environmentId])).map(roleOf)),
662
+ insertTenantProductRole: (row) => tx(async (sql) => {
663
+ await sql.query("INSERT INTO tenant_product_roles (id, org_id, name, description, created_at) VALUES ($1, $2, $3, $4, $5::timestamptz)", [row.id, row.orgId, row.name, row.description, asTime(row.createdAt)]);
664
+ }),
665
+ listTenantProductRoles: (orgId) => tx(async (sql) => (await rows(sql, "SELECT * FROM tenant_product_roles WHERE org_id = $1 ORDER BY created_at, id", [orgId])).map(tenantRoleOf)),
666
+ updateTenantProductRole: (orgId, id, name, description) => tx(async (sql) => {
667
+ const updated = await first(sql, "UPDATE tenant_product_roles SET name = $3, description = $4 WHERE org_id = $1 AND id = $2 RETURNING *", [orgId, id, name, description], tenantRoleOf);
668
+ if (!updated)
669
+ throw new StoreError("not_found", "Catalog role not found.");
670
+ return updated;
671
+ }),
672
+ deleteTenantProductRole: (orgId, id) => tx(async (sql) => {
673
+ const removed = await rows(sql, "DELETE FROM tenant_product_roles WHERE org_id = $1 AND id = $2 RETURNING id", [orgId, id]);
674
+ if (!removed.length)
675
+ throw new StoreError("not_found", "Catalog role not found.");
676
+ }),
677
+ setProductRoleCatalogLink: (environmentId, roleId, catalogRoleId, expectedCatalogRoleId) => tx(async (sql) => {
678
+ if (catalogRoleId)
679
+ await assertProductRoleCatalog(sql, environmentId, catalogRoleId);
680
+ const updated = await first(sql, "UPDATE app_product_roles SET catalog_role_id = $3 WHERE environment_id = $1 AND id = $2 AND catalog_role_id IS NOT DISTINCT FROM $4::text RETURNING *", [environmentId, roleId, catalogRoleId, expectedCatalogRoleId], roleOf);
681
+ if (!updated)
682
+ throw new StoreError("conflict", "The role link changed.");
683
+ return updated;
684
+ }),
194
685
  saveDirectoryGroup: (row) => tx(async (sql) => {
195
686
  const updated = await rows(sql, "UPDATE app_groups SET environment_id = $2, name = $3, created_at = $4::timestamptz WHERE id = $1 RETURNING id", [row.id, row.environmentId, row.name, asTime(row.createdAt)]);
196
687
  if (!updated.length)
@@ -214,6 +705,8 @@ export function createSqlDirectory(tx) {
214
705
  }),
215
706
  listGroupMembers: (environmentId) => tx(async (sql) => (await rows(sql, "SELECT * FROM app_group_members WHERE environment_id = $1 ORDER BY created_at, id", [environmentId])).map(groupMemberOf)),
216
707
  saveRoleBinding: (row) => tx(async (sql) => {
708
+ if (row.subjectType === "organization" || row.organizationId !== null)
709
+ await requireOrganizationScope(sql, row.environmentId);
217
710
  const updated = await rows(sql, `UPDATE app_role_bindings SET environment_id = $2, role_id = $3, subject_type = $4, subject_id = $5, organization_id = $6, resource = $7, created_at = $8::timestamptz
218
711
  WHERE id = $1 RETURNING id`, [row.id, row.environmentId, row.roleId, row.subjectType, row.subjectId, row.organizationId, row.resource, asTime(row.createdAt)]);
219
712
  if (!updated.length)
@@ -221,15 +714,40 @@ export function createSqlDirectory(tx) {
221
714
  VALUES ($1, $2, $3, $4, $5, $6, $7, $8::timestamptz)`, [row.id, row.environmentId, row.roleId, row.subjectType, row.subjectId, row.organizationId, row.resource, asTime(row.createdAt)]);
222
715
  }),
223
716
  deleteRoleBinding: (id) => tx(async (sql) => {
224
- const removed = await rows(sql, "DELETE FROM app_role_bindings WHERE id = $1 RETURNING id", [id]);
225
- if (!removed.length)
717
+ const [binding] = await rows(sql, "SELECT * FROM app_role_bindings WHERE id = $1 FOR UPDATE", [id]);
718
+ if (!binding)
226
719
  throw new StoreError("not_found", "Record not found.");
720
+ const roleId = text(binding, "role_id");
721
+ const environmentId = text(binding, "environment_id");
722
+ const ownerRole = await rows(sql, "SELECT id FROM app_product_roles WHERE environment_id = $1 AND owner_access AND id = $2", [environmentId, roleId]);
723
+ if (ownerRole.length && text(binding, "subject_type") === "identity" && textOrNull(binding, "resource") === null) {
724
+ const replacement = await rows(sql, `SELECT id FROM app_role_bindings
725
+ WHERE environment_id = $1 AND id <> $2 AND subject_type = 'identity' AND resource IS NULL AND role_id = $3
726
+ AND organization_id IS NOT DISTINCT FROM $4::text LIMIT 1`, [environmentId, id, roleId, textOrNull(binding, "organization_id")]);
727
+ if (!replacement.length)
728
+ throw new StoreError("last_owner_access", "Assign owner access to another person in this scope first.");
729
+ }
730
+ if (text(binding, "subject_type") === "identity") {
731
+ await sql.query(`DELETE FROM app_access_checks WHERE environment_id = $1 AND identity_id = $2 AND workspace_id IS NULL
732
+ AND organization_id IS NOT DISTINCT FROM $3::text`, [environmentId, text(binding, "subject_id"), textOrNull(binding, "organization_id")]);
733
+ }
734
+ await sql.query("DELETE FROM app_role_bindings WHERE id = $1", [id]);
227
735
  }),
228
736
  listRoleBindings: (environmentId) => tx(async (sql) => (await rows(sql, "SELECT * FROM app_role_bindings WHERE environment_id = $1 ORDER BY created_at, id", [environmentId])).map(bindingOf)),
229
737
  saveFeatureDefinition: (row) => tx(async (sql) => {
230
- const updated = await rows(sql, "UPDATE app_features SET environment_id = $2, key = $3, enabled = $4, config = $5::jsonb, created_at = $6::timestamptz WHERE id = $1 RETURNING id", [row.id, row.environmentId, row.key, row.enabled, JSON.stringify(row.config), asTime(row.createdAt)]);
738
+ const values = [row.id, row.environmentId, row.key, row.enabled, JSON.stringify(row.config), asTime(row.createdAt), row.kind ?? null];
739
+ const updated = await rows(sql, `UPDATE app_features SET environment_id = $2, key = $3, enabled = $4, config = $5::jsonb,
740
+ created_at = $6::timestamptz, kind = COALESCE($7, kind) WHERE id = $1 RETURNING id`, values);
231
741
  if (!updated.length)
232
- await sql.query("INSERT INTO app_features (id, environment_id, key, enabled, config, created_at) VALUES ($1, $2, $3, $4, $5::jsonb, $6::timestamptz)", [row.id, row.environmentId, row.key, row.enabled, JSON.stringify(row.config), asTime(row.createdAt)]);
742
+ await sql.query(`INSERT INTO app_features (id, environment_id, key, enabled, config, created_at, kind)
743
+ VALUES ($1, $2, $3, $4, $5::jsonb, $6::timestamptz, COALESCE($7, 'feature'))`, values);
744
+ }),
745
+ updateFeatureDefinition: (environmentId, id, changes) => tx(async (sql) => {
746
+ const updated = await first(sql, `UPDATE app_features SET enabled = COALESCE($3, enabled), config = COALESCE($4::jsonb, config)
747
+ WHERE environment_id = $1 AND id = $2 RETURNING *`, [environmentId, id, changes.enabled ?? null, changes.config === undefined ? null : JSON.stringify(changes.config)], featureOf);
748
+ if (!updated)
749
+ throw new StoreError("not_found", "Feature definition not found.");
750
+ return updated;
233
751
  }),
234
752
  deleteFeatureDefinition: (id) => tx(async (sql) => {
235
753
  const removed = await rows(sql, "DELETE FROM app_features WHERE id = $1 RETURNING id", [id]);
@@ -238,6 +756,8 @@ export function createSqlDirectory(tx) {
238
756
  }),
239
757
  listFeatureDefinitions: (environmentId) => tx(async (sql) => (await rows(sql, "SELECT * FROM app_features WHERE environment_id = $1 ORDER BY created_at, id", [environmentId])).map(featureOf)),
240
758
  saveFeatureAssignment: (row) => tx(async (sql) => {
759
+ if (row.targetType === "organization")
760
+ await requireOrganizationScope(sql, row.environmentId);
241
761
  const updated = await rows(sql, `UPDATE app_feature_assignments SET environment_id = $2, feature_id = $3, target_type = $4, target_id = $5, enabled = $6, feature_limit = $7, config = $8::jsonb, created_at = $9::timestamptz
242
762
  WHERE id = $1 RETURNING id`, [row.id, row.environmentId, row.featureId, row.targetType, row.targetId, row.enabled, row.limit, JSON.stringify(row.config), asTime(row.createdAt)]);
243
763
  if (!updated.length)
@@ -250,25 +770,307 @@ export function createSqlDirectory(tx) {
250
770
  throw new StoreError("not_found", "Record not found.");
251
771
  }),
252
772
  listFeatureAssignments: (environmentId) => tx(async (sql) => (await rows(sql, "SELECT * FROM app_feature_assignments WHERE environment_id = $1 ORDER BY created_at, id", [environmentId])).map(assignmentOf)),
253
- saveAppWaitlist: (row) => tx(async (sql) => {
254
- const updated = await rows(sql, "UPDATE app_waitlist SET app_id = $2, environment_id = $3, email = $4, status = $5, token_hash = $6, created_at = $7::timestamptz WHERE id = $1 RETURNING id", [row.id, row.appId, row.environmentId, row.email, row.status, row.tokenHash, asTime(row.createdAt)]);
773
+ insertAppWaitlist: (row) => tx(async (sql) => (await rows(sql, appWaitlistInsert + " ON CONFLICT DO NOTHING RETURNING id", [...appWaitValues(row), true])).length > 0),
774
+ saveAppWaitlist: (row, challenge) => tx(async (sql) => {
775
+ if (row.invitation && !await invitationIsAvailable(sql, row))
776
+ throw new StoreError("conflict", "The invited workspace or role is unavailable.");
777
+ const previous = await first(sql, "SELECT token_hash FROM app_waitlist WHERE id = $1 FOR UPDATE", [row.id], (item) => textOrNull(item, "token_hash"));
778
+ if (challenge && previous && previous !== challenge.tokenHash) {
779
+ await sql.query(`UPDATE directory_challenges SET used_at = $3::timestamptz
780
+ WHERE environment_id = $1 AND token_hash = $2 AND purpose = 'admit' AND used_at IS NULL`, [row.environmentId, previous, asTime(challenge.createdAt)]);
781
+ }
782
+ if (challenge)
783
+ await insertChallenge(sql, challenge);
784
+ const updated = await rows(sql, `UPDATE app_waitlist SET app_id = $2, environment_id = $3, email = $4,
785
+ status = $5, token_hash = $6, created_at = $7::timestamptz, answers = $8::jsonb, invitation_workspace_id = $9,
786
+ invitation_role_id = $10, pending_workspace_identity_id = $11, invitation_organization_id = $12,
787
+ invitation_delivery = $13, invitation_audit_id = $14, revoked_at = $15::timestamptz WHERE id = $1 RETURNING id`, appWaitValues(row));
255
788
  if (!updated.length)
256
- await sql.query("INSERT INTO app_waitlist (id, app_id, environment_id, email, status, token_hash, created_at) VALUES ($1, $2, $3, $4, $5, $6, $7::timestamptz)", [row.id, row.appId, row.environmentId, row.email, row.status, row.tokenHash, asTime(row.createdAt)]);
789
+ await sql.query(appWaitlistInsert, [...appWaitValues(row), false]);
790
+ }),
791
+ readDirectoryInvitation: (environmentId, tokenHash, at) => tx(async (sql) => {
792
+ const invite = await first(sql, "SELECT * FROM app_waitlist WHERE environment_id = $1 AND token_hash = $2", [environmentId, tokenHash], appWaitOf);
793
+ if (!invite)
794
+ return null;
795
+ const challenge = await first(sql, "SELECT * FROM directory_challenges WHERE environment_id = $1 AND token_hash = $2 AND purpose = 'admit'", [environmentId, tokenHash], challengeOf);
796
+ return invitationPreview(invite, challenge, asTime(at));
797
+ }),
798
+ listDirectoryInvitations: (environmentId, at) => tx(async (sql) => {
799
+ const stamp = asTime(at);
800
+ const invites = (await rows(sql, "SELECT * FROM app_waitlist WHERE environment_id = $1 AND (invitation_role_id IS NOT NULL OR status = 'revoked') ORDER BY created_at, id", [environmentId])).map(appWaitOf);
801
+ const previews = [];
802
+ for (const invite of invites) {
803
+ const challenge = invite.tokenHash
804
+ ? await first(sql, "SELECT * FROM directory_challenges WHERE environment_id = $1 AND token_hash = $2 AND purpose = 'admit'", [environmentId, invite.tokenHash], challengeOf)
805
+ : null;
806
+ const preview = invitationPreview(invite, challenge, stamp);
807
+ if (preview)
808
+ previews.push(preview);
809
+ }
810
+ return previews;
811
+ }),
812
+ setDirectoryInvitationAudit: (environmentId, id, auditId) => tx(async (sql) => {
813
+ const updated = await rows(sql, "UPDATE app_waitlist SET invitation_audit_id = $3 WHERE environment_id = $1 AND id = $2 RETURNING id", [environmentId, id, auditId]);
814
+ if (!updated.length)
815
+ throw new StoreError("not_found", "Invitation not found.");
816
+ }),
817
+ revokeDirectoryInvitation: (environmentId, id, at) => tx(async (sql) => {
818
+ const invite = await first(sql, "SELECT * FROM app_waitlist WHERE environment_id = $1 AND id = $2 FOR UPDATE", [environmentId, id], appWaitOf);
819
+ if (!invite)
820
+ return "missing";
821
+ const challenge = invite.tokenHash
822
+ ? await first(sql, "SELECT * FROM directory_challenges WHERE environment_id = $1 AND token_hash = $2 AND purpose = 'admit' FOR UPDATE", [environmentId, invite.tokenHash], challengeOf)
823
+ : null;
824
+ const stamp = asTime(at);
825
+ if (invitationLifecycle(invite.status, challenge, stamp) !== "pending")
826
+ return "closed";
827
+ await sql.query("UPDATE app_waitlist SET status = 'revoked', revoked_at = $2::timestamptz WHERE id = $1", [invite.id, stamp]);
828
+ if (challenge && !challenge.usedAt)
829
+ await sql.query("UPDATE directory_challenges SET used_at = $2::timestamptz WHERE id = $1 AND used_at IS NULL", [challenge.id, stamp]);
830
+ return "revoked";
831
+ }),
832
+ redeemDirectoryInvitation: (input) => tx(async (sql) => {
833
+ const stamp = asTime(input.at);
834
+ const challenge = await first(sql, `SELECT * FROM directory_challenges
835
+ WHERE environment_id = $1 AND token_hash = $2 AND purpose = 'admit' FOR UPDATE`, [input.environmentId, input.tokenHash], challengeOf);
836
+ const invite = challenge
837
+ ? await first(sql, "SELECT * FROM app_waitlist WHERE environment_id = $1 AND token_hash = $2 FOR UPDATE", [input.environmentId, input.tokenHash], appWaitOf)
838
+ : null;
839
+ if (!invite?.invitation || (invite.invitation.delivery !== "link" && invite.invitation.delivery !== "email") || !challenge)
840
+ return { outcome: "unavailable" };
841
+ const identity = await first(sql, "SELECT * FROM app_identities WHERE id = $1 FOR UPDATE", [input.identityId], identityOf);
842
+ if (!identity || identity.environmentId !== input.environmentId || identity.appId !== invite.appId || identity.status !== "active")
843
+ return { outcome: "unavailable" };
844
+ if ((identity.kind !== "user" && identity.kind !== "account") || !identity.email
845
+ || identity.email.toLowerCase() !== invite.email.toLowerCase() || identity.email.toLowerCase() !== challenge.email.toLowerCase()) {
846
+ return { outcome: "recipient" };
847
+ }
848
+ const status = invitationLifecycle(invite.status, challenge, stamp);
849
+ if (status === "accepted") {
850
+ const current = await savedInvitationGrant(sql, invite, identity.id);
851
+ return { outcome: "existing", identityId: identity.id, roleId: current.roleId, membershipId: current.membershipId, bindingId: current.bindingId };
852
+ }
853
+ if (status !== "pending" || !await invitationIsAvailable(sql, invite))
854
+ return { outcome: "unavailable" };
855
+ if (!identity.emailVerifiedAt && !identity.emailProofAt)
856
+ return { outcome: "unverified" };
857
+ const owner = await first(sql, "SELECT id FROM app_product_roles WHERE environment_id = $1 AND owner_access", [invite.environmentId], (row) => text(row, "id"));
858
+ const saved = await applySqlDirectoryAccess(sql, invitationGrantRequest(invite, identity.id, stamp, {
859
+ membershipId: input.newMembershipId, bindingId: input.newBindingId, organizationMembershipId: input.newOrganizationMembershipId,
860
+ }, owner));
861
+ await sql.query("UPDATE directory_challenges SET used_at = $2::timestamptz WHERE id = $1 AND used_at IS NULL", [challenge.id, stamp]);
862
+ await sql.query("UPDATE app_waitlist SET status = 'admitted', pending_workspace_identity_id = NULL WHERE id = $1", [invite.id]);
863
+ return {
864
+ outcome: "applied", identityId: identity.id, roleId: saved.roleId ?? invite.invitation.roleId,
865
+ membershipId: saved.membership?.id ?? null, bindingId: saved.binding?.id ?? null,
866
+ };
867
+ }),
868
+ acceptDirectoryWorkspaceInvitation: (identityId, at) => tx(async (sql) => {
869
+ const identity = await first(sql, "SELECT * FROM app_identities WHERE id = $1 FOR UPDATE", [identityId], identityOf);
870
+ return identity ? acceptWorkspaceInvitation(sql, identity, asTime(at)) : false;
871
+ }),
872
+ acceptDirectoryWorkspaceInvitationByToken: (environmentId, tokenHash, at) => tx(async (sql) => {
873
+ const identity = await first(sql, `SELECT identity.* FROM directory_challenges AS challenge
874
+ JOIN app_identities AS identity ON identity.environment_id = challenge.environment_id AND lower(identity.email) = lower(challenge.email)
875
+ AND identity.kind IN ('user', 'account')
876
+ WHERE challenge.environment_id = $1 AND challenge.token_hash = $2 AND challenge.purpose = 'admit'
877
+ ORDER BY CASE identity.kind WHEN 'user' THEN 0 ELSE 1 END, identity.id LIMIT 1 FOR UPDATE OF identity`, [environmentId, tokenHash], identityOf);
878
+ const stamp = asTime(at);
879
+ if (!identity || !await acceptWorkspaceInvitation(sql, identity, stamp, tokenHash))
880
+ return false;
881
+ await sql.query("UPDATE app_identities SET email_proof_at = $2::timestamptz, updated_at = $2::timestamptz WHERE id = $1", [identity.id, stamp]);
882
+ return true;
883
+ }),
884
+ completeDirectoryPasswordSetup: (environmentId, tokenHash, passwordHash, at) => tx(async (sql) => {
885
+ const challenge = await first(sql, `SELECT * FROM directory_challenges
886
+ WHERE environment_id = $1 AND token_hash = $2 AND purpose = 'admit' FOR UPDATE`, [environmentId, tokenHash], challengeOf);
887
+ const stamp = asTime(at);
888
+ if (!challenge || challenge.usedAt || isExpired(challenge.expiresAt, stamp))
889
+ return false;
890
+ const identity = await first(sql, `SELECT * FROM app_identities
891
+ WHERE environment_id = $1 AND lower(email) = lower($2) AND kind IN ('user', 'account')
892
+ ORDER BY CASE kind WHEN 'user' THEN 0 ELSE 1 END, id LIMIT 1 FOR UPDATE`, [environmentId, challenge.email], identityOf);
893
+ if (!identity || identity.status !== "active" || (identity.kind !== "user" && identity.kind !== "account") || identity.passwordHash)
894
+ return false;
895
+ const invite = await first(sql, `SELECT * FROM app_waitlist
896
+ WHERE environment_id = $1 AND lower(email) = lower($2) AND status = 'invited' FOR UPDATE`, [environmentId, challenge.email], appWaitOf);
897
+ if (invite && invite.tokenHash !== tokenHash)
898
+ return false;
899
+ if (invite?.invitation?.delivery === "link")
900
+ return false;
901
+ if (invite?.invitation && !await invitationIsAvailable(sql, invite))
902
+ return false;
903
+ const saved = await first(sql, `UPDATE app_identities
904
+ SET password_hash = $2, email_verified_at = COALESCE(email_verified_at, $3::timestamptz),
905
+ email_proof_at = $3::timestamptz, updated_at = $3::timestamptz
906
+ WHERE id = $1 AND password_hash IS NULL RETURNING *`, [identity.id, passwordHash, stamp], identityOf);
907
+ if (!saved)
908
+ return false;
909
+ saved.emailVerifiedAt = saved.emailVerifiedAt ?? stamp;
910
+ if (invite?.invitation) {
911
+ if (!await applyStoredInvitation(sql, invite, challenge.id, saved.id, stamp)) {
912
+ throw new StoreError("conflict", "The invitation could not be applied.");
913
+ }
914
+ return true;
915
+ }
916
+ await sql.query("UPDATE directory_challenges SET used_at = $2::timestamptz WHERE id = $1 AND used_at IS NULL", [challenge.id, stamp]);
917
+ if (invite)
918
+ await sql.query("UPDATE app_waitlist SET status = 'admitted', pending_workspace_identity_id = NULL WHERE id = $1 AND status = 'invited'", [invite.id]);
919
+ return true;
920
+ }),
921
+ prepareDirectoryPasswordChange: (environmentId, tokenHash, at) => tx(async (sql) => {
922
+ const stamp = asTime(at);
923
+ const challenge = await first(sql, `SELECT * FROM directory_challenges
924
+ WHERE environment_id = $1 AND token_hash = $2 AND purpose = 'password-change'`, [environmentId, tokenHash], challengeOf);
925
+ if (!challenge || challenge.usedAt || isExpired(challenge.expiresAt, stamp))
926
+ return null;
927
+ return first(sql, "SELECT * FROM app_identities WHERE id = $1 AND environment_id = $2 AND status = 'active'", [challenge.identityId, environmentId], identityOf);
928
+ }),
929
+ commitDirectoryPasswordChange: (input) => tx(async (sql) => {
930
+ const stamp = asTime(input.at);
931
+ const challenge = await first(sql, `SELECT * FROM directory_challenges
932
+ WHERE environment_id = $1 AND token_hash = $2 AND purpose = 'password-change' FOR UPDATE`, [input.environmentId, input.tokenHash], challengeOf);
933
+ if (!challenge || challenge.usedAt || isExpired(challenge.expiresAt, stamp))
934
+ return null;
935
+ const saved = await first(sql, `UPDATE app_identities
936
+ SET password_hash = $2, password_change_required = false, updated_at = $3::timestamptz
937
+ WHERE id = $1 AND environment_id = $4 AND status = 'active' AND password_hash IS NOT NULL RETURNING *`, [challenge.identityId, input.passwordHash, stamp, input.environmentId], identityOf);
938
+ if (!saved)
939
+ return null;
940
+ await sql.query("UPDATE directory_challenges SET used_at = $2::timestamptz WHERE id = $1 AND used_at IS NULL", [challenge.id, stamp]);
941
+ return saved;
257
942
  }),
258
943
  listAppWaitlist: (environmentId) => tx(async (sql) => (await rows(sql, "SELECT * FROM app_waitlist WHERE environment_id = $1 ORDER BY created_at, id", [environmentId])).map(appWaitOf)),
259
944
  findAppWaitlist: (environmentId, email) => tx((sql) => first(sql, "SELECT * FROM app_waitlist WHERE environment_id = $1 AND lower(email) = lower($2)", [environmentId, email], appWaitOf)),
260
- insertDirectoryChallenge: (row) => tx(async (sql) => {
261
- await sql.query(`INSERT INTO directory_challenges (id, environment_id, identity_id, purpose, email, token_hash, expires_at, used_at, created_at)
262
- VALUES ($1, $2, $3, $4, $5, $6, $7::timestamptz, $8::timestamptz, $9::timestamptz)`, [row.id, row.environmentId, row.identityId, row.purpose, row.email, row.tokenHash, asTime(row.expiresAt), asTimeOrNull(row.usedAt), asTime(row.createdAt)]);
945
+ claimWaitlistConfirmation: (list, entryId, at, staleAt) => tx(async (sql) => {
946
+ const table = list === "app" ? "app_waitlist" : "platform_waitlist";
947
+ return (await rows(sql, `UPDATE ${table} SET confirmation_claimed_at = $2::timestamptz
948
+ WHERE id = $1 AND status = 'waiting' AND confirmation_pending
949
+ AND (confirmation_claimed_at IS NULL OR confirmation_claimed_at <= $3::timestamptz) RETURNING id`, [entryId, asTime(at), asTime(staleAt)])).length > 0;
950
+ }),
951
+ finishWaitlistConfirmation: (list, entryId, claimedAt, accepted) => tx(async (sql) => {
952
+ const table = list === "app" ? "app_waitlist" : "platform_waitlist";
953
+ await sql.query(`UPDATE ${table} SET confirmation_claimed_at = NULL, confirmation_pending = $3
954
+ WHERE id = $1 AND confirmation_claimed_at = $2::timestamptz`, [entryId, asTime(claimedAt), !accepted]);
955
+ }),
956
+ insertDirectoryChallenge: (row, delivery) => tx((sql) => insertChallenge(sql, row, delivery)),
957
+ insertDirectoryChallengeWithCooldown: (row, after, delivery) => tx(async (sql) => {
958
+ const identity = await rows(sql, `SELECT identity.id FROM app_identities identity
959
+ JOIN app_environments env ON env.id = identity.environment_id JOIN applications app ON app.id = env.app_id
960
+ WHERE identity.id = $1 AND identity.environment_id = $2 AND identity.email = $3 AND identity.status = 'active'
961
+ AND app.trashed_at IS NULL AND app.status = 'active' AND env.status = 'active' FOR SHARE OF app, env FOR UPDATE OF identity`, [row.identityId, row.environmentId, row.email]);
962
+ if (!identity.length)
963
+ return false;
964
+ const recent = await rows(sql, `SELECT id FROM directory_challenges WHERE environment_id = $1 AND identity_id = $2
965
+ AND purpose = $3 AND created_at > $4::timestamptz LIMIT 1`, [row.environmentId, row.identityId, row.purpose, asTime(after)]);
966
+ if (recent.length)
967
+ return false;
968
+ await insertChallenge(sql, row, delivery);
969
+ return true;
263
970
  }),
264
- takeDirectoryChallenge: (tokenHash, at) => tx(async (sql) => {
971
+ takeDirectoryChallenge: (tokenHash, at, scope) => tx(async (sql) => {
265
972
  const stamp = asTime(at);
973
+ if (!await lockDirectoryChallengeApplication(sql, tokenHash, true))
974
+ return null;
266
975
  const row = await first(sql, "SELECT * FROM directory_challenges WHERE token_hash = $1 FOR UPDATE", [tokenHash], challengeOf);
267
- if (!row || row.usedAt || isExpired(row.expiresAt, stamp))
976
+ if (!row || row.usedAt || isExpired(row.expiresAt, stamp)
977
+ || (scope?.environmentId && row.environmentId !== scope.environmentId) || (scope?.purpose && row.purpose !== scope.purpose))
268
978
  return null;
269
979
  await sql.query("UPDATE directory_challenges SET used_at = $2::timestamptz WHERE id = $1", [row.id, stamp]);
270
980
  return { ...row, usedAt: stamp };
271
981
  }),
982
+ verifyDirectoryEmail: (tokenHash, at, environmentId) => tx(async (sql) => {
983
+ const stamp = asTime(at);
984
+ if (!await lockDirectoryChallengeApplication(sql, tokenHash, false))
985
+ return null;
986
+ const row = await first(sql, "SELECT * FROM directory_challenges WHERE token_hash = $1 AND purpose = 'verify' FOR UPDATE", [tokenHash], challengeOf);
987
+ if (!row || row.usedAt || isExpired(row.expiresAt, stamp) || (environmentId && row.environmentId !== environmentId))
988
+ return null;
989
+ const identity = await first(sql, `UPDATE app_identities SET
990
+ email_verified_at = COALESCE(email_verified_at, $4::timestamptz),
991
+ email_proof_at = CASE WHEN kind = 'user' THEN GREATEST(email_proof_at, $4::timestamptz) END,
992
+ updated_at = $4::timestamptz
993
+ WHERE id = $1 AND environment_id = $2 AND lower(email) = lower($3) AND status = 'active' RETURNING *`, [row.identityId, row.environmentId, row.email, stamp], identityOf);
994
+ if (!identity)
995
+ return null;
996
+ await sql.query("UPDATE directory_challenges SET used_at = $2::timestamptz WHERE id = $1", [row.id, stamp]);
997
+ await acceptWorkspaceInvitation(sql, identity, stamp);
998
+ return identity;
999
+ }),
272
1000
  };
273
1001
  }
1002
+ function directoryRecordId(prefix) {
1003
+ return `${prefix}_${randomBytes(16).toString("base64url")}`;
1004
+ }
1005
+ async function insertOrganization(sql, appId, environmentId, orgId, displayName, at) {
1006
+ const id = directoryRecordId("idn");
1007
+ await insertIdentity(sql, identityValues({
1008
+ id, appId, environmentId, orgId, kind: "organization", email: null, passwordHash: null, displayName, status: "active",
1009
+ emailVerifiedAt: null, metadata: {}, createdAt: at, updatedAt: at,
1010
+ }));
1011
+ return id;
1012
+ }
1013
+ async function insertOrganizationMember(sql, environmentId, identityId, organizationId, relation, at) {
1014
+ const existing = await rows(sql, `SELECT id FROM app_identity_memberships
1015
+ WHERE environment_id = $1 AND identity_id = $2 AND organization_id = $3`, [environmentId, identityId, organizationId]);
1016
+ if (existing.length)
1017
+ return;
1018
+ await sql.query(`INSERT INTO app_identity_memberships (id, environment_id, identity_id, organization_id, relation, created_at)
1019
+ VALUES ($1, $2, $3, $4, $5, $6::timestamptz)`, [directoryRecordId("dms"), environmentId, identityId, organizationId, relation, asTime(at)]);
1020
+ }
1021
+ export async function repairDirectoryStructure(sql, appId, orgId, model, at) {
1022
+ const hasOrganizations = directoryHasOrganizations(model);
1023
+ const hasWorkspaces = directoryHasWorkspaces(model);
1024
+ const repair = { organizations: 0, workspaces: 0 };
1025
+ const environments = await rows(sql, "SELECT id FROM app_environments WHERE app_id = $1 ORDER BY id FOR UPDATE", [appId]);
1026
+ for (const environment of environments) {
1027
+ const environmentId = text(environment, "id");
1028
+ const people = await rows(sql, `SELECT id, display_name, created_at FROM app_identities
1029
+ WHERE app_id = $1 AND environment_id = $2 AND kind IN ('user', 'account') ORDER BY created_at, id`, [appId, environmentId]);
1030
+ if (hasOrganizations) {
1031
+ for (const person of people) {
1032
+ const identityId = text(person, "id");
1033
+ const joined = await rows(sql, "SELECT id FROM app_identity_memberships WHERE environment_id = $1 AND identity_id = $2 LIMIT 1", [environmentId, identityId]);
1034
+ if (joined.length)
1035
+ continue;
1036
+ const organizationId = await insertOrganization(sql, appId, environmentId, orgId, text(person, "display_name"), at);
1037
+ await insertOrganizationMember(sql, environmentId, identityId, organizationId, "owner", at);
1038
+ repair.organizations += 1;
1039
+ }
1040
+ if (model === "organizations-and-workspaces") {
1041
+ const orphans = await rows(sql, `SELECT id, name FROM app_workspaces
1042
+ WHERE app_id = $1 AND environment_id = $2 AND organization_id IS NULL ORDER BY created_at, id FOR UPDATE`, [appId, environmentId]);
1043
+ for (const workspace of orphans) {
1044
+ const workspaceId = text(workspace, "id");
1045
+ const organizationId = await insertOrganization(sql, appId, environmentId, orgId, text(workspace, "name"), at);
1046
+ const owners = await rows(sql, `SELECT identity_id FROM app_workspace_memberships
1047
+ WHERE environment_id = $1 AND workspace_id = $2 AND relation = 'owner' ORDER BY created_at, id`, [environmentId, workspaceId]);
1048
+ for (const owner of owners)
1049
+ await insertOrganizationMember(sql, environmentId, text(owner, "identity_id"), organizationId, "member", at);
1050
+ await sql.query("UPDATE app_workspaces SET organization_id = $3, updated_at = $4::timestamptz WHERE id = $1 AND environment_id = $2", [workspaceId, environmentId, organizationId, asTime(at)]);
1051
+ repair.organizations += 1;
1052
+ }
1053
+ }
1054
+ }
1055
+ if (!hasWorkspaces)
1056
+ continue;
1057
+ for (const person of people) {
1058
+ const identityId = text(person, "id");
1059
+ const joined = await rows(sql, "SELECT id FROM app_workspace_memberships WHERE environment_id = $1 AND identity_id = $2 LIMIT 1", [environmentId, identityId]);
1060
+ if (joined.length)
1061
+ continue;
1062
+ const parent = hasOrganizations ? await first(sql, `SELECT organization_id FROM app_identity_memberships
1063
+ WHERE environment_id = $1 AND identity_id = $2 ORDER BY created_at, id LIMIT 1`, [environmentId, identityId], (row) => text(row, "organization_id")) : null;
1064
+ if (hasOrganizations && !parent)
1065
+ continue;
1066
+ const workspaceId = directoryRecordId("wsp");
1067
+ await sql.query(`INSERT INTO app_workspaces (id, app_id, environment_id, organization_id, name, status, created_at, updated_at)
1068
+ VALUES ($1, $2, $3, $4, $5, 'active', $6::timestamptz, $6::timestamptz)`, [workspaceId, appId, environmentId, parent, text(person, "display_name"), asTime(at)]);
1069
+ await sql.query(`INSERT INTO app_workspace_memberships (id, environment_id, workspace_id, identity_id, relation, created_at)
1070
+ VALUES ($1, $2, $3, $4, 'owner', $5::timestamptz)`, [directoryRecordId("wsm"), environmentId, workspaceId, identityId, asTime(at)]);
1071
+ repair.workspaces += 1;
1072
+ }
1073
+ }
1074
+ return repair;
1075
+ }
274
1076
  //# sourceMappingURL=directory-sql.js.map