@x12i/keyrox-store-pg 0.1.0 → 0.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/database.d.ts.map +1 -1
- package/dist/database.js +2 -0
- package/dist/database.js.map +1 -1
- package/dist/directory-access-sql.d.ts +12 -0
- package/dist/directory-access-sql.d.ts.map +1 -0
- package/dist/directory-access-sql.js +253 -0
- package/dist/directory-access-sql.js.map +1 -0
- package/dist/directory-sql.d.ts +4 -2
- package/dist/directory-sql.d.ts.map +1 -1
- package/dist/directory-sql.js +808 -30
- package/dist/directory-sql.js.map +1 -1
- package/dist/hosted-human-sessions.d.ts +5 -0
- package/dist/hosted-human-sessions.d.ts.map +1 -0
- package/dist/hosted-human-sessions.js +105 -0
- package/dist/hosted-human-sessions.js.map +1 -0
- package/dist/migrate.d.ts.map +1 -1
- package/dist/migrate.js +24 -1
- package/dist/migrate.js.map +1 -1
- package/dist/notification-deliveries.d.ts +5 -0
- package/dist/notification-deliveries.d.ts.map +1 -0
- package/dist/notification-deliveries.js +81 -0
- package/dist/notification-deliveries.js.map +1 -0
- package/dist/notification-webhook-sql.d.ts +4 -0
- package/dist/notification-webhook-sql.d.ts.map +1 -0
- package/dist/notification-webhook-sql.js +109 -0
- package/dist/notification-webhook-sql.js.map +1 -0
- package/dist/rows.d.ts +19 -1
- package/dist/rows.d.ts.map +1 -1
- package/dist/rows.js +153 -3
- package/dist/rows.js.map +1 -1
- package/dist/sql-store.d.ts.map +1 -1
- package/dist/sql-store.js +796 -78
- package/dist/sql-store.js.map +1 -1
- package/migrations/007_account_sso.sql +40 -0
- package/migrations/008_app_sign_in.sql +26 -0
- package/migrations/009_account_sso_next.sql +4 -0
- package/migrations/010_account_sso_profile.sql +14 -0
- package/migrations/011_hosted_sso_profiles.sql +26 -0
- package/migrations/012_app_signup_roles.sql +2 -0
- package/migrations/013_product_role_catalog.sql +14 -0
- package/migrations/014_application_staff_access.sql +21 -0
- package/migrations/015_audit_service_actor.sql +7 -0
- package/migrations/016_app_waitlist_questions.sql +2 -0
- package/migrations/017_app_signup_policy.sql +9 -0
- package/migrations/018_managed_app_sign_in.sql +8 -0
- package/migrations/019_hosted_sso_email_proofs.sql +12 -0
- package/migrations/020_cli_login_codes.sql +15 -0
- package/migrations/021_hosted_email_codes.sql +18 -0
- package/migrations/022_sso_waitlist_callback.sql +3 -0
- package/migrations/023_app_email_code_sign_in.sql +1 -0
- package/migrations/024_hosted_auth_copy.sql +2 -0
- package/migrations/025_app_directory_workspaces.sql +55 -0
- package/migrations/027_role_features_and_configuration.sql +17 -0
- package/migrations/028_sso_only_signup_audience.sql +4 -0
- package/migrations/029_people_only_directory_model.sql +3 -0
- package/migrations/030_typed_questionnaires.sql +3 -0
- package/migrations/031_app_notifications.sql +22 -0
- package/migrations/032_agent_grant_duration.sql +10 -0
- package/migrations/033_application_lifecycle.sql +67 -0
- package/migrations/034_notification_deliveries.sql +25 -0
- package/migrations/035_app_notification_webhook_jobs.sql +28 -0
- package/migrations/036_account_notification_recovery.sql +11 -0
- package/migrations/037_waitlist_confirmation.sql +7 -0
- package/migrations/039_hosted_human_sessions.sql +45 -0
- package/migrations/040_hosted_human_clients.sql +35 -0
- package/migrations/041_app_workspace_invitations.sql +9 -0
- package/migrations/042_directory_email_proof.sql +16 -0
- package/migrations/043_sso_exchange_redirect_uri.sql +1 -0
- package/migrations/044_repair_app_sign_in_connections.sql +30 -0
- package/migrations/045_directory_integrity.sql +140 -0
- package/migrations/046_person_email_across_organizations.sql +7 -0
- package/migrations/047_owner_access.sql +35 -0
- package/migrations/048_invitation_links.sql +28 -0
- 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 {
|
|
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,6 +154,17 @@ 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.");
|
|
@@ -44,6 +176,18 @@ export function createSqlStore(database) {
|
|
|
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) {
|
|
@@ -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
|
|
130
|
-
|
|
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
|
|
137
|
-
if (!
|
|
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", [
|
|
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,66 @@ export function createSqlStore(database) {
|
|
|
147
305
|
resetPassword(input) {
|
|
148
306
|
return tx(async (sql) => {
|
|
149
307
|
const stamp = asTime(input.at);
|
|
150
|
-
const
|
|
151
|
-
if (!
|
|
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", [
|
|
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
318
|
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
|
|
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
321
|
return { ...account, passwordHash: input.passwordHash, emailVerifiedAt: verified };
|
|
161
322
|
});
|
|
162
323
|
},
|
|
163
|
-
insertInvite(row) {
|
|
324
|
+
insertInvite(row, delivery) {
|
|
325
|
+
return tx(async (sql) => {
|
|
326
|
+
await sql.query("SELECT id FROM orgs WHERE id = $1 FOR NO KEY UPDATE", [row.orgId]);
|
|
327
|
+
await checkPendingInvite(sql, row, row.createdAt);
|
|
328
|
+
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)
|
|
329
|
+
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)]);
|
|
330
|
+
await insertSqlNotificationDelivery(sql, delivery);
|
|
331
|
+
});
|
|
332
|
+
},
|
|
333
|
+
listOpenInvites(orgId, limit, beforeId) {
|
|
334
|
+
return tx(async (sql) => (await rows(sql, `SELECT invite.* FROM invites invite
|
|
335
|
+
WHERE invite.org_id = $1 AND invite.accepted_at IS NULL AND invite.revoked_at IS NULL
|
|
336
|
+
AND ($3::text IS NULL OR (invite.created_at, invite.id COLLATE "C") <
|
|
337
|
+
(SELECT cursor.created_at, cursor.id COLLATE "C" FROM invites cursor WHERE cursor.org_id = $1 AND cursor.id = $3))
|
|
338
|
+
ORDER BY invite.created_at DESC, invite.id COLLATE "C" DESC LIMIT $2`, [orgId, limit, beforeId ?? null])).map(inviteOf));
|
|
339
|
+
},
|
|
340
|
+
getOrgInvite(orgId, inviteId) {
|
|
341
|
+
return tx((sql) => first(sql, "SELECT * FROM invites WHERE org_id = $1 AND id = $2", [orgId, inviteId], inviteOf));
|
|
342
|
+
},
|
|
343
|
+
rotateInvite(input) {
|
|
164
344
|
return tx(async (sql) => {
|
|
165
|
-
await sql.query(
|
|
166
|
-
|
|
345
|
+
await sql.query("SELECT id FROM orgs WHERE id = $1 FOR NO KEY UPDATE", [input.orgId]);
|
|
346
|
+
const row = await first(sql, `SELECT * FROM invites WHERE org_id = $1 AND id = $2 AND accepted_at IS NULL
|
|
347
|
+
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);
|
|
348
|
+
if (!row)
|
|
349
|
+
return null;
|
|
350
|
+
await checkPendingInvite(sql, row, input.at);
|
|
351
|
+
const rotated = await first(sql, `UPDATE invites SET token_hash = $2, expires_at = $3::timestamptz,
|
|
352
|
+
last_mail_requested_at = $4::timestamptz WHERE id = $1 RETURNING *`, [row.id, input.tokenHash, asTime(input.expiresAt), asTime(input.at)], inviteOf);
|
|
353
|
+
if (rotated)
|
|
354
|
+
await insertSqlNotificationDelivery(sql, input.delivery);
|
|
355
|
+
return rotated;
|
|
167
356
|
});
|
|
168
357
|
},
|
|
358
|
+
revokeInvite(orgId, inviteId, at) {
|
|
359
|
+
return tx(async (sql) => (await rows(sql, `UPDATE invites SET revoked_at = $3::timestamptz WHERE org_id = $1 AND id = $2
|
|
360
|
+
AND accepted_at IS NULL AND revoked_at IS NULL RETURNING id`, [orgId, inviteId, asTime(at)])).length > 0);
|
|
361
|
+
},
|
|
169
362
|
acceptInvite(input) {
|
|
170
363
|
return tx(async (sql) => {
|
|
171
364
|
const at = asTime(input.at);
|
|
172
365
|
await sql.query("SELECT id FROM users WHERE id = $1 FOR UPDATE", [input.userId]);
|
|
173
366
|
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))
|
|
367
|
+
if (!invite || invite.acceptedAt || invite.revokedAt || isExpired(invite.expiresAt, at))
|
|
175
368
|
throw new StoreError("invite_invalid", "Invite is no longer valid.");
|
|
176
369
|
const account = await first(sql, "SELECT * FROM users WHERE id = $1", [input.userId], userOf);
|
|
177
370
|
if (!account)
|
|
@@ -394,20 +587,21 @@ export function createSqlStore(database) {
|
|
|
394
587
|
getTrust: (id) => tx((sql) => first(sql, "SELECT * FROM workload_trusts WHERE id = $1", [id], trustOf)),
|
|
395
588
|
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
589
|
insertAudit(row) {
|
|
397
|
-
return tx(
|
|
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
|
-
});
|
|
590
|
+
return tx((sql) => writeAudit(sql, row));
|
|
401
591
|
},
|
|
402
592
|
listAudit: (query) => tx(async (sql) => (await rows(sql, `SELECT * FROM audit_events
|
|
403
593
|
WHERE org_id = $1
|
|
404
594
|
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
|
|
595
|
+
AND ($3::text IS NULL OR actor_user_id = $3 OR actor_service_id = $3 OR agent_id = $3 OR target = $3)
|
|
596
|
+
AND ($4::text IS NULL OR detail = $4 OR left(detail, length($4) + 1) = $4 || ' ')
|
|
407
597
|
AND ($5::timestamptz IS NULL OR at >= $5::timestamptz)
|
|
408
598
|
AND ($6::timestamptz IS NULL OR at <= $6::timestamptz)
|
|
409
|
-
|
|
599
|
+
AND ($9::text IS NULL OR actor_user_id = $9)
|
|
600
|
+
AND ($10::text IS NULL OR decision = $10)
|
|
601
|
+
AND ($11::timestamptz IS NULL OR (at, id COLLATE "C") < ($11::timestamptz, $12::text COLLATE "C"))
|
|
602
|
+
ORDER BY at DESC, id COLLATE "C" DESC LIMIT $7 OFFSET $8`, [
|
|
410
603
|
query.orgId, query.action ?? null, query.subject ?? null, query.source ? `source=${query.source}` : null, query.from ?? null, query.to ?? null, query.limit, query.offset,
|
|
604
|
+
query.actorUserId ?? null, query.decision ?? null, query.before?.at ?? null, query.before?.id ?? null,
|
|
411
605
|
])).map(auditOf)),
|
|
412
606
|
getDeniedJti: (id) => tx((sql) => first(sql, "SELECT * FROM denied_jtis WHERE id = $1", [id], deniedOf)),
|
|
413
607
|
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 +611,311 @@ export function createSqlStore(database) {
|
|
|
417
611
|
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
612
|
});
|
|
419
613
|
},
|
|
420
|
-
insertApplication(row)
|
|
614
|
+
insertApplication: (row) => tx((sql) => insertApp(sql, row)),
|
|
615
|
+
registerApplication({ application, environments, creatorAccess, audit }) {
|
|
421
616
|
return tx(async (sql) => {
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
617
|
+
if (!environments.length || environments.some((row) => row.appId !== application.id || row.orgId !== application.orgId)) {
|
|
618
|
+
throw new StoreError("conflict", "Registration needs environments for the new application.");
|
|
619
|
+
}
|
|
620
|
+
if (creatorAccess && !environments.some((row) => row.name === "development" && row.id === creatorAccess.environmentId
|
|
621
|
+
&& row.appId === creatorAccess.appId && row.orgId === creatorAccess.orgId)) {
|
|
622
|
+
throw new StoreError("conflict", "Creator access must target the new development environment.");
|
|
623
|
+
}
|
|
624
|
+
if (audit && audit.orgId !== application.orgId)
|
|
625
|
+
throw new StoreError("conflict", "Application registration audit must match the tenant.");
|
|
626
|
+
await insertApp(sql, application);
|
|
627
|
+
for (const environment of environments)
|
|
628
|
+
await insertAppEnvironment(sql, environment);
|
|
629
|
+
if (creatorAccess)
|
|
630
|
+
await saveStaffAccess(sql, creatorAccess);
|
|
631
|
+
if (audit)
|
|
632
|
+
await writeAudit(sql, audit);
|
|
429
633
|
});
|
|
430
634
|
},
|
|
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)),
|
|
635
|
+
getApplication: (id) => tx((sql) => first(sql, "SELECT * FROM applications WHERE id = $1 AND trashed_at IS NULL", [id], applicationOf)),
|
|
636
|
+
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)),
|
|
637
|
+
listTrashedApplications: (orgId) => tx(async (sql) => (await rows(sql, `SELECT * FROM applications
|
|
638
|
+
WHERE org_id = $1 AND trashed_at IS NOT NULL ORDER BY trashed_at DESC, id DESC`, [orgId])).map(trashedApplicationOf)),
|
|
639
|
+
moveApplication: ({ appId, sourceOrgId, targetOrgId, updatedAt, environmentKeys, audit = [] }) => tx(async (sql) => {
|
|
640
|
+
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);
|
|
641
|
+
if (!app)
|
|
642
|
+
throw new StoreError("not_found", "Application not found.");
|
|
643
|
+
if (sourceOrgId === targetOrgId)
|
|
644
|
+
throw new StoreError("conflict", "Choose a different tenant.");
|
|
645
|
+
const target = await rows(sql, "SELECT id FROM orgs WHERE id = $1 FOR KEY SHARE", [targetOrgId]);
|
|
646
|
+
if (!target.length)
|
|
647
|
+
throw new StoreError("not_found", "Destination tenant not found.");
|
|
648
|
+
if (audit.some((event) => event.orgId !== sourceOrgId && event.orgId !== targetOrgId)) {
|
|
649
|
+
throw new StoreError("conflict", "Application move audit must match the source or destination tenant.");
|
|
650
|
+
}
|
|
651
|
+
const stamp = applicationLifecycleTime(updatedAt, app.updatedAt);
|
|
652
|
+
const environments = (await rows(sql, "SELECT * FROM app_environments WHERE app_id = $1 ORDER BY id FOR UPDATE", [appId])).map(environmentOf);
|
|
653
|
+
const keys = applicationMoveKeys(environments, environmentKeys);
|
|
654
|
+
const path = `/tenants/${sourceOrgId}/apps/${appId}`;
|
|
655
|
+
const destinationPath = `/tenants/${targetOrgId}/apps/${appId}`;
|
|
656
|
+
const collision = await rows(sql, `SELECT 1 FROM audiences AS source JOIN audiences AS destination ON destination.identifier = source.identifier
|
|
657
|
+
WHERE source.app_id = $1 AND destination.org_id = $2 LIMIT 1`, [appId, targetOrgId]);
|
|
658
|
+
if (collision.length)
|
|
659
|
+
throw new StoreError("conflict", "The destination tenant already uses an audience identifier from this application.");
|
|
660
|
+
const mixed = await rows(sql, `SELECT 1 FROM gateway_routes AS route JOIN audiences AS audience ON audience.id = route.audience_id
|
|
661
|
+
WHERE (audience.app_id = $1 OR rtrim(route.resource, '/') = $2)
|
|
662
|
+
AND (audience.app_id IS DISTINCT FROM $1 OR rtrim(route.resource, '/') <> $2 OR route.org_id <> $3) LIMIT 1`, [appId, path, sourceOrgId]);
|
|
663
|
+
if (mixed.length)
|
|
664
|
+
throw new StoreError("conflict", "An application gateway route uses a shared tenant resource or audience. Update its scope before moving the application.");
|
|
665
|
+
await removeApplicationTenantAccess(sql, sourceOrgId, appId, stamp);
|
|
666
|
+
await sql.query("DELETE FROM sso_logins WHERE app_id = $1", [appId]);
|
|
667
|
+
await sql.query("DELETE FROM sso_exchanges WHERE app_id = $1", [appId]);
|
|
668
|
+
await sql.query("DELETE FROM hosted_human_codes WHERE app_id = $1", [appId]);
|
|
669
|
+
await sql.query("UPDATE hosted_human_clients SET revoked_at = $2::timestamptz WHERE app_id = $1 AND revoked_at IS NULL", [appId, stamp]);
|
|
670
|
+
await sql.query("DELETE FROM hosted_sso_profiles WHERE app_id = $1", [appId]);
|
|
671
|
+
await sql.query("DELETE FROM hosted_email_codes WHERE environment_id = ANY($1::text[])", [[...keys.keys()]]);
|
|
672
|
+
for (const key of keys.values()) {
|
|
673
|
+
await sql.query(`UPDATE app_environments SET org_id = $2, updated_at = $3::timestamptz, secret_enc = $4, secret_hash = $5,
|
|
674
|
+
key_version = $6, previous_secret_enc = NULL, previous_secret_hash = NULL, previous_key_version = NULL, previous_key_expires_at = NULL
|
|
675
|
+
WHERE id = $1 AND app_id = $7 AND org_id = $8`, [key.id, targetOrgId, stamp, key.secretEnc, key.secretHash, key.keyVersion, appId, sourceOrgId]);
|
|
676
|
+
}
|
|
677
|
+
await sql.query("UPDATE app_tokens SET org_id = $2, revoked_at = COALESCE(revoked_at, $3::timestamptz) WHERE app_id = $1", [appId, targetOrgId, stamp]);
|
|
678
|
+
await sql.query("UPDATE app_identities SET org_id = $2 WHERE app_id = $1", [appId, targetOrgId]);
|
|
679
|
+
await sql.query("UPDATE app_notification_settings SET org_id = $2 WHERE app_id = $1", [appId, targetOrgId]);
|
|
680
|
+
await sql.query("UPDATE app_notification_webhooks SET org_id = $2, enabled = false, updated_at = $3::timestamptz WHERE app_id = $1", [appId, targetOrgId, stamp]);
|
|
681
|
+
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()]]);
|
|
682
|
+
await sql.query(`UPDATE gateway_routes SET org_id = $2, resource = $3
|
|
683
|
+
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]);
|
|
684
|
+
await sql.query("UPDATE audiences SET org_id = $2 WHERE app_id = $1", [appId, targetOrgId]);
|
|
685
|
+
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);
|
|
686
|
+
if (!moved)
|
|
687
|
+
throw new StoreError("conflict", "Application tenant changed.");
|
|
688
|
+
for (const event of audit)
|
|
689
|
+
await writeAudit(sql, event);
|
|
690
|
+
return moved;
|
|
691
|
+
}),
|
|
692
|
+
trashApplication: ({ appId, orgId, trashedAt, allowProduction = true, audit }) => tx(async (sql) => {
|
|
693
|
+
await lockApplicationTenant(sql, orgId);
|
|
694
|
+
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);
|
|
695
|
+
if (!app)
|
|
696
|
+
throw new StoreError("not_found", "Application not found.");
|
|
697
|
+
if (audit && audit.orgId !== orgId)
|
|
698
|
+
throw new StoreError("conflict", "Application trash audit must match the tenant.");
|
|
699
|
+
if (!allowProduction && (await rows(sql, "SELECT id FROM app_environments WHERE app_id = $1 AND name = 'production'", [appId])).length) {
|
|
700
|
+
throw new StoreError("conflict", "Production access is required to move this application to Trash.");
|
|
701
|
+
}
|
|
702
|
+
const stamp = applicationLifecycleTime(trashedAt, app.updatedAt);
|
|
703
|
+
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);
|
|
704
|
+
if (audit)
|
|
705
|
+
await writeAudit(sql, audit);
|
|
706
|
+
return trashed;
|
|
707
|
+
}),
|
|
708
|
+
restoreApplication: ({ appId, orgId, updatedAt, expectedTrashedAt, audit }) => tx(async (sql) => {
|
|
709
|
+
await lockApplicationTenant(sql, orgId);
|
|
710
|
+
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);
|
|
711
|
+
if (!app)
|
|
712
|
+
throw new StoreError("not_found", "Application not found in Trash.");
|
|
713
|
+
if (expectedTrashedAt && expectedTrashedAt !== app.trashedAt)
|
|
714
|
+
throw new StoreError("conflict", "Trash changed. Review the application before restoring it.");
|
|
715
|
+
if (audit && audit.orgId !== orgId)
|
|
716
|
+
throw new StoreError("conflict", "Application restore audit must match the tenant.");
|
|
717
|
+
const stamp = applicationLifecycleTime(updatedAt, app.trashedAt);
|
|
718
|
+
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);
|
|
719
|
+
if (audit)
|
|
720
|
+
await writeAudit(sql, audit);
|
|
721
|
+
return restored;
|
|
722
|
+
}),
|
|
723
|
+
emptyApplicationTrash: (orgId, confirmed, audit, allowProduction = true) => tx(async (sql) => {
|
|
724
|
+
await lockApplicationTenant(sql, orgId);
|
|
725
|
+
if (audit && audit.orgId !== orgId)
|
|
726
|
+
throw new StoreError("conflict", "Application trash audit must match the tenant.");
|
|
727
|
+
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);
|
|
728
|
+
verifyApplicationTrashSnapshot(entries, confirmed);
|
|
729
|
+
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) {
|
|
730
|
+
throw new StoreError("conflict", "Production access is required to empty this Trash.");
|
|
731
|
+
}
|
|
732
|
+
for (const entry of entries)
|
|
733
|
+
await purgeApplication(sql, entry);
|
|
734
|
+
if (audit)
|
|
735
|
+
await writeAudit(sql, audit);
|
|
736
|
+
return entries.length;
|
|
737
|
+
}),
|
|
738
|
+
listPurgedApplicationLogos: () => tx(async (sql) => (await rows(sql, "SELECT app_id FROM application_logo_purge ORDER BY app_id")).map((row) => String(row.app_id))),
|
|
739
|
+
clearPurgedApplicationLogo: (appId) => tx(async (sql) => { await sql.query("DELETE FROM application_logo_purge WHERE app_id = $1", [appId]); }),
|
|
433
740
|
updateApplication(row) {
|
|
434
741
|
return tx(async (sql) => {
|
|
742
|
+
let repair = { organizations: 0, workspaces: 0 };
|
|
743
|
+
if (row.directoryModel !== undefined) {
|
|
744
|
+
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);
|
|
745
|
+
if (current === null)
|
|
746
|
+
throw new StoreError("not_found", "Application not found.");
|
|
747
|
+
if (current !== row.directoryModel && row.directoryModel === "people-only") {
|
|
748
|
+
const existing = await rows(sql, `WITH environments AS (SELECT id FROM app_environments WHERE app_id = $1)
|
|
749
|
+
SELECT 1 WHERE EXISTS (SELECT 1 FROM app_identities WHERE app_id = $1 AND kind = 'organization')
|
|
750
|
+
OR EXISTS (SELECT 1 FROM app_workspaces WHERE app_id = $1)
|
|
751
|
+
OR EXISTS (SELECT 1 FROM app_identity_memberships WHERE environment_id IN (SELECT id FROM environments))
|
|
752
|
+
OR EXISTS (SELECT 1 FROM app_workspace_memberships WHERE environment_id IN (SELECT id FROM environments))
|
|
753
|
+
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))
|
|
754
|
+
OR EXISTS (SELECT 1 FROM app_feature_assignments WHERE environment_id IN (SELECT id FROM environments) AND target_type = 'organization')`, [row.id]);
|
|
755
|
+
if (existing.length)
|
|
756
|
+
throw new StoreError("conflict", "Existing organizations, workspaces, memberships, or organization access rules prevent using people only.");
|
|
757
|
+
}
|
|
758
|
+
else if (current !== row.directoryModel && (row.directoryModel === "organizations" || row.directoryModel === "workspaces")) {
|
|
759
|
+
const conflicting = await rows(sql, `SELECT id FROM app_workspaces WHERE app_id = $1 AND
|
|
760
|
+
(($2 = 'organizations' AND status = 'active') OR ($2 = 'workspaces' AND organization_id IS NOT NULL))
|
|
761
|
+
LIMIT 1`, [row.id, row.directoryModel]);
|
|
762
|
+
if (conflicting.length)
|
|
763
|
+
throw new StoreError("conflict", "Existing workspaces are incompatible with this directory model.");
|
|
764
|
+
}
|
|
765
|
+
if (current !== row.directoryModel && row.directoryModel !== "people-only") {
|
|
766
|
+
repair = await repairDirectoryStructure(sql, row.id, row.orgId, row.directoryModel, row.updatedAt);
|
|
767
|
+
}
|
|
768
|
+
}
|
|
435
769
|
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
|
-
|
|
770
|
+
title = $2, description = $3, status = $4, allowed_scopes = $5::text[], allowed_features = $6::text[], updated_at = GREATEST(updated_at, $7::timestamptz),
|
|
771
|
+
product_name = $8, logo_url = $9, accent_color = $10, signup_mode = $11, allow_without_personal_org = $12,
|
|
772
|
+
waitlist_questions = COALESCE($13::text[], waitlist_questions), signup_audience = $14, signup_sso_providers = $15::text[], signup_organization = $16,
|
|
773
|
+
managed_sign_in = COALESCE($17::boolean, managed_sign_in), email_code_sign_in = COALESCE($18::boolean, email_code_sign_in),
|
|
774
|
+
auth_copy = COALESCE($19::jsonb, auth_copy), directory_model = COALESCE($20, directory_model),
|
|
775
|
+
directory_labels = COALESCE($21::jsonb, directory_labels), onboarding = onboarding || $22::jsonb,
|
|
776
|
+
waitlist_question_definitions = CASE WHEN $23::boolean THEN $24::jsonb ELSE waitlist_question_definitions END,
|
|
777
|
+
waitlist_question_layout = COALESCE($25, waitlist_question_layout)
|
|
778
|
+
WHERE id = $1 AND org_id = $26 AND trashed_at IS NULL RETURNING id`, [
|
|
439
779
|
row.id, row.title, row.description, row.status, row.allowedScopes, row.allowedFeatures, asTime(row.updatedAt),
|
|
440
780
|
row.productName || row.title, row.logoUrl ?? null, row.accentColor ?? null, row.signupMode ?? "open", row.allowRegistrationWithoutPersonalOrg === true,
|
|
781
|
+
row.waitlistQuestionDefinitions?.map(({ prompt }) => prompt) ?? row.waitlistQuestions ?? null,
|
|
782
|
+
row.signupAudience ?? "any-email", row.signupSsoProviders ?? [], row.signupOrganization ?? "required",
|
|
783
|
+
row.managedSignIn ?? null, row.emailCodeSignIn ?? null, row.authCopy === undefined ? null : JSON.stringify(row.authCopy),
|
|
784
|
+
row.directoryModel ?? null, row.directoryLabels === undefined ? null : JSON.stringify(row.directoryLabels), JSON.stringify(row.onboarding ?? {}),
|
|
785
|
+
row.waitlistQuestionDefinitions !== undefined || row.waitlistQuestions !== undefined,
|
|
786
|
+
row.waitlistQuestionDefinitions == null ? null : JSON.stringify(row.waitlistQuestionDefinitions), row.waitlistQuestionLayout ?? null, row.orgId,
|
|
441
787
|
]);
|
|
442
788
|
if (!updated.length)
|
|
443
789
|
throw new StoreError("not_found", "Application not found.");
|
|
790
|
+
return repair;
|
|
444
791
|
});
|
|
445
792
|
},
|
|
446
|
-
insertEnvironment(row)
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
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
|
-
]);
|
|
457
|
-
});
|
|
458
|
-
},
|
|
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)),
|
|
793
|
+
insertEnvironment: (row) => tx((sql) => insertAppEnvironment(sql, row)),
|
|
794
|
+
getEnvironment: (id) => tx((sql) => first(sql, `SELECT env.* FROM app_environments env JOIN applications app ON app.id = env.app_id
|
|
795
|
+
WHERE env.id = $1 AND app.trashed_at IS NULL`, [id], environmentOf)),
|
|
796
|
+
listEnvironments: (appId, options) => tx(async (sql) => (await rows(sql, `SELECT env.* FROM app_environments env JOIN applications app ON app.id = env.app_id
|
|
797
|
+
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)),
|
|
461
798
|
updateEnvironment(row) {
|
|
462
799
|
return tx(async (sql) => {
|
|
800
|
+
await assertApplicationScope(sql, row.appId, row.orgId);
|
|
463
801
|
const updated = await rows(sql, `UPDATE app_environments SET
|
|
464
802
|
title = $2, status = $3, secret_enc = $4, secret_hash = $5, key_version = $6,
|
|
465
803
|
previous_secret_enc = $7, previous_secret_hash = $8, previous_key_version = $9,
|
|
466
804
|
previous_key_expires_at = $10::timestamptz, updated_at = $11::timestamptz
|
|
467
|
-
WHERE id = $1
|
|
805
|
+
WHERE id = $1 AND app_id = $12 AND org_id = $13 AND name = $14
|
|
806
|
+
AND ((key_version = $6 AND secret_hash = $5) OR (key_version = $6 - 1 AND secret_hash = $8)) RETURNING id`, [
|
|
468
807
|
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),
|
|
808
|
+
row.previousSecretEnc, row.previousSecretHash, row.previousKeyVersion, asTimeOrNull(row.previousKeyExpiresAt), asTime(row.updatedAt), row.appId, row.orgId, row.name,
|
|
470
809
|
]);
|
|
471
810
|
if (!updated.length)
|
|
472
811
|
throw new StoreError("not_found", "Environment not found.");
|
|
473
812
|
});
|
|
474
813
|
},
|
|
814
|
+
getNotificationSettings: (environmentId) => tx((sql) => first(sql, "SELECT * FROM app_notification_settings WHERE environment_id = $1", [environmentId], notificationSettingsOf)),
|
|
815
|
+
saveNotificationSettings(row, expectedUpdatedAt, audit) {
|
|
816
|
+
return tx(async (sql) => {
|
|
817
|
+
if (row.delivery !== "keyrox" && row.delivery !== "both" && row.delivery !== "webhook")
|
|
818
|
+
throw new StoreError("conflict", "Invalid notification delivery.");
|
|
819
|
+
await assertApplicationScope(sql, row.appId, row.orgId);
|
|
820
|
+
const environment = await first(sql, "SELECT * FROM app_environments WHERE id = $1 FOR UPDATE", [row.environmentId], environmentOf);
|
|
821
|
+
if (!environment || environment.appId !== row.appId || environment.orgId !== row.orgId)
|
|
822
|
+
throw new StoreError("conflict", "Notification settings must match the environment.");
|
|
823
|
+
const existing = await first(sql, "SELECT * FROM app_notification_settings WHERE environment_id = $1", [row.environmentId], notificationSettingsOf);
|
|
824
|
+
if (expectedUpdatedAt !== undefined && (existing?.updatedAt ?? null) !== expectedUpdatedAt)
|
|
825
|
+
return false;
|
|
826
|
+
if (row.delivery === "webhook" && !(await rows(sql, "SELECT id FROM app_notification_webhooks WHERE environment_id = $1 AND enabled LIMIT 1", [row.environmentId])).length) {
|
|
827
|
+
throw new StoreError("conflict", "webhook_required");
|
|
828
|
+
}
|
|
829
|
+
const saved = await rows(sql, `INSERT INTO app_notification_settings (environment_id, app_id, org_id, delivery, templates, updated_at)
|
|
830
|
+
VALUES ($1, $2, $3, $4, $5::jsonb, $6::timestamptz)
|
|
831
|
+
ON CONFLICT (environment_id) DO UPDATE SET delivery = EXCLUDED.delivery, templates = EXCLUDED.templates, updated_at = EXCLUDED.updated_at
|
|
832
|
+
WHERE app_notification_settings.app_id = EXCLUDED.app_id AND app_notification_settings.org_id = EXCLUDED.org_id
|
|
833
|
+
RETURNING environment_id`, [row.environmentId, row.appId, row.orgId, row.delivery, JSON.stringify(row.templates), asTime(row.updatedAt)]);
|
|
834
|
+
if (!saved.length)
|
|
835
|
+
throw new StoreError("conflict", "Notification settings must match the environment.");
|
|
836
|
+
if (audit) {
|
|
837
|
+
if (audit.orgId !== row.orgId)
|
|
838
|
+
throw new StoreError("conflict", "Notification audit must match the tenant.");
|
|
839
|
+
await writeAudit(sql, audit);
|
|
840
|
+
}
|
|
841
|
+
return true;
|
|
842
|
+
});
|
|
843
|
+
},
|
|
844
|
+
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)),
|
|
845
|
+
insertNotificationWebhook(row) {
|
|
846
|
+
return tx(async (sql) => {
|
|
847
|
+
await assertApplicationScope(sql, row.appId, row.orgId);
|
|
848
|
+
const environment = await first(sql, "SELECT * FROM app_environments WHERE id = $1 FOR UPDATE", [row.environmentId], environmentOf);
|
|
849
|
+
if (!environment || environment.appId !== row.appId || environment.orgId !== row.orgId)
|
|
850
|
+
throw new StoreError("conflict", "A webhook must match the environment.");
|
|
851
|
+
const count = Number((await rows(sql, "SELECT count(*)::int AS count FROM app_notification_webhooks WHERE environment_id = $1", [row.environmentId]))[0]?.count ?? 0);
|
|
852
|
+
if (count >= 5)
|
|
853
|
+
throw new StoreError("conflict", "webhook_limit");
|
|
854
|
+
await sql.query(`INSERT INTO app_notification_webhooks (
|
|
855
|
+
id, environment_id, app_id, org_id, url, secret_enc, enabled, created_at, updated_at
|
|
856
|
+
) VALUES ($1, $2, $3, $4, $5, $6, $7, $8::timestamptz, $9::timestamptz)`, [
|
|
857
|
+
row.id, row.environmentId, row.appId, row.orgId, row.url, row.secretEnc, row.enabled, asTime(row.createdAt), asTime(row.updatedAt),
|
|
858
|
+
]);
|
|
859
|
+
});
|
|
860
|
+
},
|
|
861
|
+
updateNotificationWebhook(row) {
|
|
862
|
+
return tx(async (sql) => {
|
|
863
|
+
await assertApplicationScope(sql, row.appId, row.orgId);
|
|
864
|
+
await rows(sql, "SELECT id FROM app_environments WHERE id = $1 FOR UPDATE", [row.environmentId]);
|
|
865
|
+
if (!row.enabled)
|
|
866
|
+
await ensureAnotherNotificationWebhook(sql, row.environmentId, row.id);
|
|
867
|
+
const updated = await rows(sql, `UPDATE app_notification_webhooks SET
|
|
868
|
+
url = $3, secret_enc = $4, enabled = $5, updated_at = $6::timestamptz
|
|
869
|
+
WHERE id = $1 AND environment_id = $2 AND app_id = $7 AND org_id = $8
|
|
870
|
+
RETURNING id`, [row.id, row.environmentId, row.url, row.secretEnc, row.enabled, asTime(row.updatedAt), row.appId, row.orgId]);
|
|
871
|
+
if (!updated.length)
|
|
872
|
+
throw new StoreError("not_found", "Webhook not found.");
|
|
873
|
+
});
|
|
874
|
+
},
|
|
875
|
+
deleteNotificationWebhook(environmentId, id, orgId) {
|
|
876
|
+
return tx(async (sql) => {
|
|
877
|
+
const scope = await rows(sql, `SELECT app.id FROM app_environments env JOIN applications app ON app.id = env.app_id
|
|
878
|
+
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]);
|
|
879
|
+
if (!scope.length)
|
|
880
|
+
return false;
|
|
881
|
+
await rows(sql, "SELECT id FROM app_environments WHERE id = $1 FOR UPDATE", [environmentId]);
|
|
882
|
+
await ensureAnotherNotificationWebhook(sql, environmentId, id);
|
|
883
|
+
const deleted = await rows(sql, `DELETE FROM app_notification_webhooks WHERE environment_id = $1 AND id = $2
|
|
884
|
+
AND ($3::text IS NULL OR org_id = $3) RETURNING id`, [environmentId, id, orgId ?? null]);
|
|
885
|
+
return deleted.length > 0;
|
|
886
|
+
});
|
|
887
|
+
},
|
|
888
|
+
listApplicationStaffAccess: (orgId, userId) => tx(async (sql) => (await rows(sql, `SELECT staff.* FROM app_staff_access staff
|
|
889
|
+
JOIN applications app ON app.id = staff.app_id WHERE staff.org_id = $1 AND app.trashed_at IS NULL
|
|
890
|
+
AND ($2::text IS NULL OR staff.user_id = $2) ORDER BY staff.created_at, staff.id`, [orgId, userId ?? null])).map(applicationStaffAccessOf)),
|
|
891
|
+
saveApplicationStaffAccess(row, audit) {
|
|
892
|
+
return tx(async (sql) => {
|
|
893
|
+
if (audit && audit.orgId !== row.orgId)
|
|
894
|
+
throw new StoreError("conflict", "Application staff audit must match the tenant.");
|
|
895
|
+
const saved = await saveStaffAccess(sql, row);
|
|
896
|
+
if (audit)
|
|
897
|
+
await writeAudit(sql, audit);
|
|
898
|
+
return saved;
|
|
899
|
+
});
|
|
900
|
+
},
|
|
901
|
+
deleteApplicationStaffAccess(orgId, appId, environmentId, userId, audit) {
|
|
902
|
+
return tx(async (sql) => {
|
|
903
|
+
if (audit && audit.orgId !== orgId)
|
|
904
|
+
throw new StoreError("conflict", "Application staff audit must match the tenant.");
|
|
905
|
+
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]);
|
|
906
|
+
if (!removed.length)
|
|
907
|
+
return false;
|
|
908
|
+
if (audit)
|
|
909
|
+
await writeAudit(sql, audit);
|
|
910
|
+
return true;
|
|
911
|
+
});
|
|
912
|
+
},
|
|
475
913
|
insertAppToken(row) {
|
|
476
914
|
return tx(async (sql) => {
|
|
915
|
+
await assertApplicationScope(sql, row.appId, row.orgId);
|
|
916
|
+
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]);
|
|
917
|
+
if (!environment.length)
|
|
918
|
+
throw new StoreError("conflict", "The environment or its key changed during token issuance.");
|
|
477
919
|
await sql.query(`INSERT INTO app_tokens (
|
|
478
920
|
id, app_id, environment_id, org_id, owner_identity_id, identity_type, payload, encrypted, revoked_at, expires_at, created_at
|
|
479
921
|
) VALUES ($1, $2, $3, $4, $5, $6, $7::jsonb, $8, $9::timestamptz, $10::timestamptz, $11::timestamptz)`, [
|
|
@@ -482,58 +924,298 @@ export function createSqlStore(database) {
|
|
|
482
924
|
]);
|
|
483
925
|
});
|
|
484
926
|
},
|
|
485
|
-
getAppToken: (id) => tx((sql) => first(sql,
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
927
|
+
getAppToken: (id) => tx((sql) => first(sql, `SELECT token.* FROM app_tokens token JOIN applications app ON app.id = token.app_id
|
|
928
|
+
WHERE token.id = $1 AND app.trashed_at IS NULL`, [id], appTokenOf)),
|
|
929
|
+
listAppTokens: (filter) => tx(async (sql) => (await rows(sql, `SELECT token.* FROM app_tokens token
|
|
930
|
+
JOIN applications app ON app.id = token.app_id WHERE app.trashed_at IS NULL
|
|
931
|
+
AND ($1::text IS NULL OR token.app_id = $1) AND ($2::text IS NULL OR token.environment_id = $2)
|
|
932
|
+
AND ($3::text IS NULL OR token.owner_identity_id = $3) AND ($4::text IS NULL OR token.org_id = $4)
|
|
933
|
+
ORDER BY token.created_at DESC, token.id DESC`, [filter.appId ?? null, filter.environmentId ?? null, filter.identityId ?? null, filter.orgId ?? null])).map(appTokenOf)),
|
|
489
934
|
revokeAppToken: (id, at) => tx(async (sql) => {
|
|
490
|
-
await sql.query(
|
|
491
|
-
|
|
935
|
+
await sql.query(`UPDATE app_tokens SET revoked_at = $2::timestamptz WHERE id = $1 AND revoked_at IS NULL
|
|
936
|
+
AND EXISTS (SELECT 1 FROM applications app WHERE app.id = app_tokens.app_id AND app.trashed_at IS NULL)`, [id, asTime(at)]);
|
|
937
|
+
return first(sql, `SELECT token.* FROM app_tokens token JOIN applications app ON app.id = token.app_id
|
|
938
|
+
WHERE token.id = $1 AND app.trashed_at IS NULL`, [id], appTokenOf);
|
|
492
939
|
}),
|
|
493
940
|
revokeAppTokens: (filter, at) => tx(async (sql) => {
|
|
494
941
|
const updated = await rows(sql, `UPDATE app_tokens SET revoked_at = $5::timestamptz
|
|
495
942
|
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)
|
|
943
|
+
AND EXISTS (SELECT 1 FROM applications app WHERE app.id = app_tokens.app_id AND app.trashed_at IS NULL)
|
|
496
944
|
RETURNING id`, [filter.appId ?? null, filter.environmentId ?? null, filter.identityId ?? null, filter.orgId ?? null, asTime(at)]);
|
|
497
945
|
return updated.length;
|
|
498
946
|
}),
|
|
947
|
+
savePlatformSignIn: (row) => tx(async (sql) => {
|
|
948
|
+
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)
|
|
949
|
+
VALUES ($1, $2, $3, $4, $5, $6, $7::timestamptz,
|
|
950
|
+
($2 <> 'oidc' AND ($2 <> 'microsoft' OR $5 IS NOT DISTINCT FROM 'common')) AND COALESCE($8::boolean, false))
|
|
951
|
+
ON CONFLICT (provider) DO UPDATE SET client_id = EXCLUDED.client_id, client_secret_enc = EXCLUDED.client_secret_enc,
|
|
952
|
+
directory_id = EXCLUDED.directory_id, issuer = EXCLUDED.issuer, managed_for_apps =
|
|
953
|
+
(EXCLUDED.provider <> 'oidc' AND (EXCLUDED.provider <> 'microsoft' OR EXCLUDED.directory_id IS NOT DISTINCT FROM 'common'))
|
|
954
|
+
AND COALESCE($8::boolean, platform_sign_in.managed_for_apps)
|
|
955
|
+
RETURNING *`, [row.id, row.provider, row.clientId, row.clientSecretEnc, row.directoryId, row.issuer, asTime(row.createdAt), row.managedForApps ?? null], platformSignInOf);
|
|
956
|
+
return saved;
|
|
957
|
+
}),
|
|
958
|
+
setPlatformSignInManaged: (provider, managedForApps) => tx((sql) => first(sql, `UPDATE platform_sign_in SET managed_for_apps = $2
|
|
959
|
+
WHERE provider = $1 AND (NOT $2::boolean OR (provider <> 'oidc' AND (provider <> 'microsoft' OR directory_id IS NOT DISTINCT FROM 'common')))
|
|
960
|
+
RETURNING *`, [provider, managedForApps], platformSignInOf)),
|
|
961
|
+
listPlatformSignIn: () => tx(async (sql) => (await rows(sql, "SELECT * FROM platform_sign_in ORDER BY provider", [])).map(platformSignInOf)),
|
|
962
|
+
deletePlatformSignIn: (provider) => tx(async (sql) => { await sql.query("DELETE FROM platform_sign_in WHERE provider = $1", [provider]); }),
|
|
963
|
+
findAccountIdentity: (provider, subject) => tx((sql) => first(sql, "SELECT * FROM account_identities WHERE provider = $1 AND subject = $2", [provider, subject], accountIdentityOf)),
|
|
964
|
+
findUserAccountIdentity: (userId, provider) => tx((sql) => first(sql, "SELECT * FROM account_identities WHERE user_id = $1 AND provider = $2", [userId, provider], accountIdentityOf)),
|
|
965
|
+
saveAccountIdentity: (row) => tx((sql) => insertAccountIdentity(sql, row)),
|
|
966
|
+
insertAccountSsoLogin: (row) => tx(async (sql) => {
|
|
967
|
+
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)]);
|
|
968
|
+
}),
|
|
969
|
+
takeAccountSsoLogin: (stateHash, at) => tx(async (sql) => {
|
|
970
|
+
const found = await first(sql, "DELETE FROM account_sso_logins WHERE state_hash = $1 RETURNING *", [stateHash], accountSsoLoginOf);
|
|
971
|
+
if (!found || Date.parse(found.expiresAt) <= Date.parse(asTime(at)))
|
|
972
|
+
return null;
|
|
973
|
+
return found;
|
|
974
|
+
}),
|
|
975
|
+
insertAccountSsoProfile: (row) => tx(async (sql) => {
|
|
976
|
+
const createdAt = asTime(row.createdAt);
|
|
977
|
+
await sql.query("DELETE FROM account_sso_profiles WHERE expires_at <= $1::timestamptz", [createdAt]);
|
|
978
|
+
await sql.query(`INSERT INTO account_sso_profiles (id, code_hash, browser_hash, provider, connection_fingerprint, subject, email, next_path, expires_at, created_at)
|
|
979
|
+
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]);
|
|
980
|
+
}),
|
|
981
|
+
takeAccountSsoProfile: (codeHash, browserHash, at) => tx(async (sql) => {
|
|
982
|
+
const found = await first(sql, "DELETE FROM account_sso_profiles WHERE code_hash = $1 AND browser_hash = $2 RETURNING *", [codeHash, browserHash], accountSsoProfileOf);
|
|
983
|
+
return found && !isExpired(found.expiresAt, asTime(at)) ? found : null;
|
|
984
|
+
}),
|
|
985
|
+
insertAccountHandoff: (row) => tx(async (sql) => {
|
|
986
|
+
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)]);
|
|
987
|
+
}),
|
|
988
|
+
takeAccountHandoff: (codeHash, at) => tx(async (sql) => {
|
|
989
|
+
const found = await first(sql, "DELETE FROM account_handoffs WHERE code_hash = $1 RETURNING *", [codeHash], accountHandoffOf);
|
|
990
|
+
if (!found || Date.parse(found.expiresAt) <= Date.parse(asTime(at)))
|
|
991
|
+
return null;
|
|
992
|
+
return found;
|
|
993
|
+
}),
|
|
994
|
+
insertCliLoginCode: (row) => tx(async (sql) => {
|
|
995
|
+
const createdAt = asTime(row.createdAt);
|
|
996
|
+
await sql.query("DELETE FROM cli_login_codes WHERE expires_at <= $1::timestamptz", [createdAt]);
|
|
997
|
+
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)
|
|
998
|
+
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,
|
|
999
|
+
asTime(row.expiresAt), createdAt, asTimeOrNull(row.consumedAt)]);
|
|
1000
|
+
}),
|
|
1001
|
+
takeCliLoginCode: (codeHash, codeChallenge, redirectUri, at) => tx((sql) => first(sql, `UPDATE cli_login_codes SET consumed_at = $4::timestamptz
|
|
1002
|
+
WHERE code_hash = $1 AND code_challenge = $2 AND redirect_uri = $3 AND consumed_at IS NULL AND expires_at > $4::timestamptz
|
|
1003
|
+
RETURNING *`, [codeHash, codeChallenge, redirectUri, asTime(at)], cliLoginCodeOf)),
|
|
499
1004
|
saveSignInConnection: (row) => tx(async (sql) => {
|
|
500
|
-
await sql
|
|
501
|
-
|
|
502
|
-
|
|
1005
|
+
await assertApplicationScope(sql, row.appId, row.orgId, "conflict");
|
|
1006
|
+
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)
|
|
1007
|
+
SELECT $1, app.id, $4, $5, $6, $7, $8, $9::timestamptz FROM applications app WHERE app.id = $2 AND app.org_id = $3
|
|
1008
|
+
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
|
|
1009
|
+
RETURNING id`, [row.id, row.appId, row.orgId, row.provider, row.clientId, row.clientSecretEnc, row.directoryId, row.issuer, asTime(row.createdAt)]);
|
|
1010
|
+
if (!saved.length)
|
|
1011
|
+
throw new StoreError("conflict", "The sign-in connection must belong to the application tenant.");
|
|
1012
|
+
await retireLegacyAppSignIn(sql, row.appId, row.provider);
|
|
1013
|
+
}),
|
|
1014
|
+
listSignInConnections: (appId) => tx(async (sql) => (await rows(sql, `SELECT connection.*, app.org_id FROM app_sign_in_connections connection
|
|
1015
|
+
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)),
|
|
1016
|
+
listOrgSignInConnections: (orgId) => tx(async (sql) => (await rows(sql, `SELECT connection.*, app.org_id FROM app_sign_in_connections connection
|
|
1017
|
+
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)),
|
|
1018
|
+
deleteSignInConnection: (appId, provider, orgId) => tx(async (sql) => {
|
|
1019
|
+
const scope = await rows(sql, `SELECT id FROM applications WHERE id = $1 AND trashed_at IS NULL
|
|
1020
|
+
AND ($2::text IS NULL OR org_id = $2) FOR SHARE`, [appId, orgId ?? null]);
|
|
1021
|
+
if (!scope.length)
|
|
1022
|
+
throw new StoreError("not_found", "Application not found.");
|
|
1023
|
+
await sql.query("DELETE FROM app_sign_in_connections WHERE app_id = $1 AND provider = $2", [appId, provider]);
|
|
1024
|
+
await retireLegacyAppSignIn(sql, appId, provider);
|
|
503
1025
|
}),
|
|
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
1026
|
saveAppSignIn: (appId, providers) => tx(async (sql) => {
|
|
507
1027
|
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
1028
|
}),
|
|
509
1029
|
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) => {
|
|
1030
|
+
saveRedirects: (environmentId, uris, orgId) => tx(async (sql) => {
|
|
1031
|
+
const scope = await rows(sql, `SELECT app.id FROM app_environments env JOIN applications app ON app.id = env.app_id
|
|
1032
|
+
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]);
|
|
1033
|
+
if (!scope.length)
|
|
1034
|
+
throw new StoreError("not_found", "Application environment not found.");
|
|
511
1035
|
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
1036
|
}),
|
|
513
1037
|
getRedirects: (environmentId) => tx(async (sql) => textsOf(await first(sql, "SELECT uris FROM environment_redirects WHERE environment_id = $1", [environmentId], (row) => row))),
|
|
1038
|
+
insertHostedHumanClient: (row) => tx(async (sql) => {
|
|
1039
|
+
await assertApplicationScope(sql, row.appId, row.orgId);
|
|
1040
|
+
const inserted = await rows(sql, `INSERT INTO hosted_human_clients
|
|
1041
|
+
(id, app_id, environment_id, org_id, name, redirect_uri, audience, secret_hash, created_at, revoked_at)
|
|
1042
|
+
SELECT $1, env.app_id, env.id, env.org_id, $5, $6, $7, $8, $9::timestamptz, $10::timestamptz
|
|
1043
|
+
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,
|
|
1044
|
+
asTime(row.createdAt), asTimeOrNull(row.revokedAt)]);
|
|
1045
|
+
if (!inserted.length)
|
|
1046
|
+
throw new StoreError("not_found", "Application environment not found.");
|
|
1047
|
+
}),
|
|
1048
|
+
getHostedHumanClient: (clientId) => tx((sql) => first(sql, "SELECT * FROM hosted_human_clients WHERE id = $1", [clientId], hostedHumanClientOf)),
|
|
1049
|
+
listHostedHumanClients: (appId, environmentId) => tx(async (sql) => (await rows(sql, `SELECT client.* FROM hosted_human_clients client
|
|
1050
|
+
JOIN applications app ON app.id = client.app_id AND app.org_id = client.org_id
|
|
1051
|
+
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)),
|
|
1052
|
+
revokeHostedHumanClient: (appId, environmentId, clientId, at) => tx(async (sql) => {
|
|
1053
|
+
const revoked = await rows(sql, `UPDATE hosted_human_clients client
|
|
1054
|
+
SET revoked_at = COALESCE(client.revoked_at, $4::timestamptz) FROM applications app
|
|
1055
|
+
WHERE client.app_id = $1 AND client.environment_id = $2 AND client.id = $3
|
|
1056
|
+
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)]);
|
|
1057
|
+
if (!revoked.length)
|
|
1058
|
+
return false;
|
|
1059
|
+
await sql.query("DELETE FROM hosted_human_codes WHERE client_id = $1", [clientId]);
|
|
1060
|
+
return true;
|
|
1061
|
+
}),
|
|
1062
|
+
insertHostedHumanCode: (row) => tx(async (sql) => (await rows(sql, `INSERT INTO hosted_human_codes
|
|
1063
|
+
(code_hash, client_id, app_id, environment_id, org_id, redirect_uri, code_challenge, identity_id, provider, created_at, expires_at)
|
|
1064
|
+
SELECT $1, client.id, client.app_id, client.environment_id, client.org_id, client.redirect_uri, $7, identity.id, $9, $10::timestamptz, $11::timestamptz
|
|
1065
|
+
FROM hosted_human_clients client
|
|
1066
|
+
JOIN applications app ON app.id = client.app_id AND app.org_id = client.org_id
|
|
1067
|
+
JOIN app_environments env ON env.id = client.environment_id AND env.app_id = client.app_id AND env.org_id = client.org_id
|
|
1068
|
+
JOIN environment_redirects redirects ON redirects.environment_id = env.id AND client.redirect_uri = ANY(redirects.uris)
|
|
1069
|
+
JOIN app_identities identity ON identity.id = $8 AND identity.app_id = client.app_id
|
|
1070
|
+
AND identity.environment_id = client.environment_id AND identity.org_id = client.org_id
|
|
1071
|
+
WHERE client.id = $2 AND client.app_id = $3 AND client.environment_id = $4 AND client.org_id = $5 AND client.redirect_uri = $6
|
|
1072
|
+
AND client.revoked_at IS NULL AND app.trashed_at IS NULL AND app.status = 'active' AND app.signup_mode = 'waiting-list'
|
|
1073
|
+
AND env.status = 'active' AND identity.kind = 'user' AND identity.status = 'active'
|
|
1074
|
+
AND identity.email IS NOT NULL AND identity.email_verified_at IS NOT NULL AND identity.email_proof_at IS NOT NULL
|
|
1075
|
+
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,
|
|
1076
|
+
row.identityId, row.provider, asTime(row.createdAt), asTime(row.expiresAt)])).length === 1),
|
|
1077
|
+
takeHostedHumanCode: (input) => tx(async (sql) => {
|
|
1078
|
+
const found = await first(sql, `SELECT code.* FROM hosted_human_codes code
|
|
1079
|
+
JOIN hosted_human_clients client ON client.id = code.client_id AND client.app_id = code.app_id
|
|
1080
|
+
AND client.environment_id = code.environment_id AND client.org_id = code.org_id AND client.redirect_uri = code.redirect_uri
|
|
1081
|
+
JOIN applications app ON app.id = code.app_id AND app.org_id = code.org_id
|
|
1082
|
+
JOIN app_environments env ON env.id = code.environment_id AND env.app_id = code.app_id AND env.org_id = code.org_id
|
|
1083
|
+
JOIN environment_redirects redirects ON redirects.environment_id = env.id AND code.redirect_uri = ANY(redirects.uris)
|
|
1084
|
+
JOIN app_identities identity ON identity.id = code.identity_id AND identity.app_id = code.app_id
|
|
1085
|
+
AND identity.environment_id = code.environment_id AND identity.org_id = code.org_id
|
|
1086
|
+
WHERE code.code_hash = $1 AND code.client_id = $2 AND code.app_id = $3 AND code.environment_id = $4
|
|
1087
|
+
AND code.redirect_uri = $5 AND code.code_challenge = $6 AND client.secret_hash = $7 AND code.expires_at > $8::timestamptz
|
|
1088
|
+
AND client.revoked_at IS NULL AND app.trashed_at IS NULL AND app.status = 'active' AND app.signup_mode = 'waiting-list'
|
|
1089
|
+
AND env.status = 'active' AND identity.kind = 'user' AND identity.status = 'active'
|
|
1090
|
+
AND identity.email IS NOT NULL AND identity.email_verified_at IS NOT NULL AND identity.email_proof_at IS NOT NULL
|
|
1091
|
+
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);
|
|
1092
|
+
return found ? first(sql, "DELETE FROM hosted_human_codes WHERE code_hash = $1 RETURNING *", [found.codeHash], hostedHumanCodeOf) : null;
|
|
1093
|
+
}),
|
|
514
1094
|
insertSsoLogin: (row) => tx(async (sql) => {
|
|
515
|
-
await sql
|
|
516
|
-
|
|
517
|
-
|
|
1095
|
+
await assertApplicationScope(sql, row.appId, row.orgId);
|
|
1096
|
+
await sql.query(`INSERT INTO sso_logins (id, state_hash, nonce, verifier, app_id, environment_id, org_id, provider, redirect_uri, app_state,
|
|
1097
|
+
expires_at, created_at, connection_authority, waitlist_in_app, human_binding, invitation_token_hash)
|
|
1098
|
+
VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11::timestamptz,$12::timestamptz,$13,$14,$15::jsonb,$16)`, [
|
|
1099
|
+
row.id, row.stateHash, row.nonce, row.verifier, row.appId, row.environmentId, row.orgId, row.provider, row.redirectUri, row.appState,
|
|
1100
|
+
asTime(row.expiresAt), asTime(row.createdAt), row.connectionAuthority ?? null, row.waitlistInApp === true,
|
|
1101
|
+
row.humanBinding ? JSON.stringify(row.humanBinding) : null, row.invitationTokenHash ?? null,
|
|
518
1102
|
]);
|
|
519
1103
|
}),
|
|
520
1104
|
takeSsoLogin: (stateHash, at) => tx(async (sql) => {
|
|
1105
|
+
const scope = await rows(sql, `SELECT app.id FROM sso_logins login JOIN applications app ON app.id = login.app_id
|
|
1106
|
+
WHERE login.state_hash = $1 AND app.org_id = login.org_id AND app.trashed_at IS NULL FOR SHARE OF app`, [stateHash]);
|
|
1107
|
+
if (!scope.length)
|
|
1108
|
+
return null;
|
|
521
1109
|
const found = await first(sql, "DELETE FROM sso_logins WHERE state_hash = $1 RETURNING *", [stateHash], ssoLoginOf);
|
|
522
1110
|
if (!found || Date.parse(found.expiresAt) <= Date.parse(asTime(at)))
|
|
523
1111
|
return null;
|
|
524
1112
|
return found;
|
|
525
1113
|
}),
|
|
1114
|
+
putHostedEmailCode: (row) => tx(async (sql) => {
|
|
1115
|
+
const createdAt = asTime(row.createdAt);
|
|
1116
|
+
const expiresAt = asTime(row.expiresAt);
|
|
1117
|
+
if (isExpired(expiresAt, createdAt))
|
|
1118
|
+
throw new StoreError("conflict", "Email code expiry must follow issuance.");
|
|
1119
|
+
const now = Date.parse(createdAt);
|
|
1120
|
+
const windowStart = new Date(now - hostedEmailCodePolicy.sendWindowMs).toISOString();
|
|
1121
|
+
const cooldownEnd = new Date(now - hostedEmailCodePolicy.resendDelayMs).toISOString();
|
|
1122
|
+
const inserted = await rows(sql, `INSERT INTO hosted_email_codes AS current_code
|
|
1123
|
+
(environment_id, email, id, challenge_hash, code_hash, created_at, expires_at, attempts_remaining, send_history)
|
|
1124
|
+
SELECT env.id, $3, $4, $5, $6, $7::timestamptz, $8::timestamptz, $9, ARRAY[$7::timestamptz]
|
|
1125
|
+
FROM app_environments env JOIN applications app ON app.id = env.app_id
|
|
1126
|
+
WHERE app.id = $1 AND env.id = $2 AND app.trashed_at IS NULL AND app.status = 'active' AND env.status = 'active'
|
|
1127
|
+
FOR SHARE OF app
|
|
1128
|
+
ON CONFLICT (environment_id, email) DO UPDATE SET id = EXCLUDED.id, challenge_hash = EXCLUDED.challenge_hash,
|
|
1129
|
+
code_hash = EXCLUDED.code_hash, created_at = EXCLUDED.created_at, expires_at = EXCLUDED.expires_at,
|
|
1130
|
+
attempts_remaining = EXCLUDED.attempts_remaining, consumed_at = NULL,
|
|
1131
|
+
send_history = ARRAY(SELECT sent_at FROM unnest(current_code.send_history) AS sent(sent_at)
|
|
1132
|
+
WHERE sent_at > $10::timestamptz) || EXCLUDED.send_history
|
|
1133
|
+
WHERE current_code.challenge_hash <> EXCLUDED.challenge_hash
|
|
1134
|
+
AND current_code.created_at <= $11::timestamptz
|
|
1135
|
+
AND (SELECT count(*) FROM unnest(current_code.send_history) AS sent(sent_at) WHERE sent_at > $10::timestamptz) < $12
|
|
1136
|
+
RETURNING id`, [
|
|
1137
|
+
row.appId, row.environmentId, row.email.trim().toLowerCase(), row.id, row.challengeHash, row.codeHash,
|
|
1138
|
+
createdAt, expiresAt, hostedEmailCodePolicy.maxAttempts, windowStart, cooldownEnd, hostedEmailCodePolicy.maxSends,
|
|
1139
|
+
]);
|
|
1140
|
+
return inserted.length ? "sent" : "cooldown";
|
|
1141
|
+
}),
|
|
1142
|
+
verifyHostedEmailCode: (appId, environmentId, challengeHash, codeHash, at) => tx((sql) => first(sql, `UPDATE hosted_email_codes AS code SET
|
|
1143
|
+
attempts_remaining = code.attempts_remaining - 1,
|
|
1144
|
+
consumed_at = CASE WHEN code.code_hash = $4 THEN $5::timestamptz ELSE NULL END
|
|
1145
|
+
FROM app_environments env JOIN applications app ON app.id = env.app_id
|
|
1146
|
+
WHERE code.environment_id = env.id AND app.id = $1 AND env.id = $2 AND code.challenge_hash = $3
|
|
1147
|
+
AND app.trashed_at IS NULL AND app.status = 'active' AND env.status = 'active'
|
|
1148
|
+
AND code.consumed_at IS NULL AND code.attempts_remaining > 0 AND code.expires_at > $5::timestamptz
|
|
1149
|
+
RETURNING code.*, app.id AS app_id`, [appId, environmentId, challengeHash, codeHash, asTime(at)], (row) => row.consumed_at ? hostedEmailCodeOf(row) : null)),
|
|
1150
|
+
insertHostedSsoProfile: (row) => tx(async (sql) => {
|
|
1151
|
+
await assertApplicationScope(sql, row.appId, row.orgId);
|
|
1152
|
+
const inserted = await rows(sql, `INSERT INTO hosted_sso_profiles
|
|
1153
|
+
(id, challenge_hash, browser_hash, app_id, environment_id, org_id, provider, authority, subject, email, redirect_uri, app_state,
|
|
1154
|
+
expires_at, created_at, display_name, connection_fingerprint, waitlist_in_app, human_binding)
|
|
1155
|
+
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
|
|
1156
|
+
FROM app_environments env JOIN applications app ON app.id = env.app_id
|
|
1157
|
+
WHERE app.id = $4 AND env.id = $5 AND app.org_id = $6 RETURNING id`, [
|
|
1158
|
+
row.id, row.challengeHash, row.browserHash, row.appId, row.environmentId, row.orgId, row.provider,
|
|
1159
|
+
row.authority, row.subject, row.email, row.redirectUri, row.appState, asTime(row.expiresAt), asTime(row.createdAt),
|
|
1160
|
+
row.displayName ?? null, row.connectionFingerprint ?? null, row.waitlistInApp === true,
|
|
1161
|
+
row.humanBinding ? JSON.stringify(row.humanBinding) : null,
|
|
1162
|
+
]);
|
|
1163
|
+
if (!inserted.length)
|
|
1164
|
+
throw new StoreError("conflict", "Hosted sign-in environment is missing.");
|
|
1165
|
+
}),
|
|
1166
|
+
getHostedSsoProfile: (challengeHash, browserHash, at) => tx((sql) => first(sql, `SELECT profile.* FROM hosted_sso_profiles profile
|
|
1167
|
+
JOIN applications app ON app.id = profile.app_id AND app.org_id = profile.org_id
|
|
1168
|
+
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)),
|
|
1169
|
+
takeHostedSsoProfile: (challengeHash, browserHash, at) => tx(async (sql) => {
|
|
1170
|
+
if (!await lockHostedSsoApplication(sql, challengeHash, browserHash))
|
|
1171
|
+
return null;
|
|
1172
|
+
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);
|
|
1173
|
+
}),
|
|
1174
|
+
beginHostedSsoEmail: (challengeHash, browserHash, proof) => tx(async (sql) => {
|
|
1175
|
+
const createdAt = asTime(proof.createdAt);
|
|
1176
|
+
const expiresAt = asTime(proof.expiresAt);
|
|
1177
|
+
if (proof.purpose !== "hosted-sso-email" || proof.usedAt !== null || isExpired(expiresAt, createdAt))
|
|
1178
|
+
return false;
|
|
1179
|
+
const profile = await lockHostedSsoEmailProfile(sql, challengeHash, browserHash, createdAt);
|
|
1180
|
+
if (!profile || profile.id !== proof.identityId || profile.environmentId !== proof.environmentId)
|
|
1181
|
+
return false;
|
|
1182
|
+
const inserted = await rows(sql, `INSERT INTO hosted_sso_email_proofs (profile_id, token_hash, email, created_at, expires_at)
|
|
1183
|
+
VALUES ($1, $2, $3, $4::timestamptz, $5::timestamptz)
|
|
1184
|
+
ON CONFLICT (profile_id) DO UPDATE SET token_hash = EXCLUDED.token_hash, email = EXCLUDED.email,
|
|
1185
|
+
created_at = EXCLUDED.created_at, expires_at = EXCLUDED.expires_at
|
|
1186
|
+
WHERE hosted_sso_email_proofs.created_at <= EXCLUDED.created_at - INTERVAL '60 seconds'
|
|
1187
|
+
RETURNING profile_id`, [profile.id, proof.tokenHash, proof.email, createdAt, expiresAt]);
|
|
1188
|
+
return inserted.length > 0;
|
|
1189
|
+
}),
|
|
1190
|
+
takeHostedSsoEmail: (challengeHash, browserHash, tokenHash, at) => tx(async (sql) => {
|
|
1191
|
+
const stamp = asTime(at);
|
|
1192
|
+
const profile = await lockHostedSsoEmailProfile(sql, challengeHash, browserHash, stamp);
|
|
1193
|
+
if (!profile)
|
|
1194
|
+
return null;
|
|
1195
|
+
const proof = await first(sql, `SELECT email FROM hosted_sso_email_proofs
|
|
1196
|
+
WHERE profile_id = $1 AND token_hash = $2 AND expires_at > $3::timestamptz`, [profile.id, tokenHash, stamp], (row) => String(row.email));
|
|
1197
|
+
if (proof === null)
|
|
1198
|
+
return null;
|
|
1199
|
+
await sql.query("DELETE FROM hosted_sso_profiles WHERE id = $1", [profile.id]);
|
|
1200
|
+
return { ...profile, email: proof };
|
|
1201
|
+
}),
|
|
526
1202
|
insertSsoExchange: (row) => tx(async (sql) => {
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
|
|
1203
|
+
const token = await rows(sql, `SELECT token.id FROM app_tokens token JOIN applications app ON app.id = token.app_id
|
|
1204
|
+
WHERE token.id = $1 AND token.app_id = $2 AND token.environment_id = $3 AND token.org_id = app.org_id
|
|
1205
|
+
AND app.trashed_at IS NULL AND token.revoked_at IS NULL FOR SHARE OF app, token`, [row.tokenId, row.appId, row.environmentId]);
|
|
1206
|
+
if (!token.length)
|
|
1207
|
+
throw new StoreError("conflict", "The sign-in token is unavailable.");
|
|
1208
|
+
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)
|
|
1209
|
+
VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9::timestamptz,$10::timestamptz,$11)`, [
|
|
1210
|
+
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
1211
|
]);
|
|
531
1212
|
}),
|
|
1213
|
+
getSsoExchange: (codeHash, at) => tx((sql) => first(sql, ssoExchangeQuery, [codeHash, asTime(at)], ssoExchangeOf)),
|
|
532
1214
|
takeSsoExchange: (codeHash, at) => tx(async (sql) => {
|
|
533
|
-
const
|
|
534
|
-
if (!
|
|
1215
|
+
const exchange = await first(sql, `${ssoExchangeQuery} FOR SHARE OF app, token`, [codeHash, asTime(at)], ssoExchangeOf);
|
|
1216
|
+
if (!exchange)
|
|
535
1217
|
return null;
|
|
536
|
-
return
|
|
1218
|
+
return first(sql, "DELETE FROM sso_exchanges WHERE id = $1 RETURNING *", [exchange.id], ssoExchangeOf);
|
|
537
1219
|
}),
|
|
538
1220
|
insertServiceCredential: (row) => tx(async (sql) => {
|
|
539
1221
|
await sql.query(`INSERT INTO service_credentials (id, org_id, name, secret_hash, app_ids, permissions, revoked_at, created_at)
|
|
@@ -555,19 +1237,50 @@ export function createSqlStore(database) {
|
|
|
555
1237
|
}),
|
|
556
1238
|
listWorkloadCredentials: (principalId) => tx(async (sql) => (await rows(sql, "SELECT * FROM workload_credentials WHERE principal_id = $1", [principalId])).map(workloadCredentialOf)),
|
|
557
1239
|
insertAudience: (row) => tx(async (sql) => {
|
|
1240
|
+
if (row.appId)
|
|
1241
|
+
await assertApplicationScope(sql, row.appId, row.orgId, "conflict");
|
|
558
1242
|
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)]);
|
|
559
1243
|
}),
|
|
560
|
-
listAudiences: (orgId) => tx(async (sql) => (await rows(sql,
|
|
561
|
-
|
|
1244
|
+
listAudiences: (orgId) => tx(async (sql) => (await rows(sql, `SELECT audience.* FROM audiences audience
|
|
1245
|
+
WHERE audience.org_id = $1 AND (audience.app_id IS NULL OR EXISTS (SELECT 1 FROM applications app
|
|
1246
|
+
WHERE app.id = audience.app_id AND app.org_id = $1 AND app.trashed_at IS NULL))`, [orgId])).map(audienceOf)),
|
|
1247
|
+
findAudience: (orgId, identifier) => tx((sql) => first(sql, `SELECT audience.* FROM audiences audience
|
|
1248
|
+
WHERE audience.org_id = $1 AND audience.identifier = $2 AND (audience.app_id IS NULL OR EXISTS (SELECT 1 FROM applications app
|
|
1249
|
+
WHERE app.id = audience.app_id AND app.org_id = $1 AND app.trashed_at IS NULL))`, [orgId, identifier], audienceOf)),
|
|
562
1250
|
insertRole: (row) => tx(async (sql) => {
|
|
563
1251
|
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
1252
|
}),
|
|
565
1253
|
listRoles: (orgId) => tx(async (sql) => (await rows(sql, "SELECT * FROM role_definitions WHERE org_id = $1", [orgId])).map(roleOf)),
|
|
566
1254
|
insertAssignment: (row) => tx(async (sql) => {
|
|
1255
|
+
// Serialize grants to the same identity so concurrent requests cannot create duplicates.
|
|
1256
|
+
const [principal] = await rows(sql, "SELECT enabled FROM workload_principals WHERE id = $1 AND org_id = $2 FOR UPDATE", [row.principalId, row.orgId]);
|
|
1257
|
+
const role = await rows(sql, "SELECT id FROM role_definitions WHERE id = $1 AND org_id = $2", [row.roleId, row.orgId]);
|
|
1258
|
+
if (!principal || !role.length)
|
|
1259
|
+
throw new StoreError("conflict", "Choose an app identity and role from this tenant.");
|
|
1260
|
+
if (!principal.enabled)
|
|
1261
|
+
throw new StoreError("conflict", "This app identity is disabled.");
|
|
1262
|
+
const duplicate = await rows(sql, `SELECT id FROM role_assignments
|
|
1263
|
+
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]);
|
|
1264
|
+
if (duplicate.length)
|
|
1265
|
+
throw new StoreError("duplicate", "Role assignment already exists.");
|
|
567
1266
|
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
1267
|
}),
|
|
569
1268
|
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)),
|
|
1269
|
+
deleteAssignment: (id, orgId, audit) => tx(async (sql) => {
|
|
1270
|
+
const removed = await rows(sql, "DELETE FROM role_assignments WHERE id = $1 AND org_id = $2 RETURNING id", [id, orgId]);
|
|
1271
|
+
if (!removed.length)
|
|
1272
|
+
return false;
|
|
1273
|
+
await writeAudit(sql, audit);
|
|
1274
|
+
return true;
|
|
1275
|
+
}),
|
|
570
1276
|
insertGatewayRoute: (row) => tx(async (sql) => {
|
|
1277
|
+
const audience = await first(sql, "SELECT * FROM audiences WHERE id = $1 AND org_id = $2", [row.audienceId, row.orgId], audienceOf);
|
|
1278
|
+
if (!audience)
|
|
1279
|
+
throw new StoreError("conflict", "Choose an audience from this tenant.");
|
|
1280
|
+
const applicationIds = new Set([audience.appId, appIdFromTenantResource(row.orgId, row.resource)].sort());
|
|
1281
|
+
for (const appId of applicationIds)
|
|
1282
|
+
if (appId)
|
|
1283
|
+
await assertApplicationScope(sql, appId, row.orgId, "conflict");
|
|
571
1284
|
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
1285
|
}),
|
|
573
1286
|
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 +1290,21 @@ export function createSqlStore(database) {
|
|
|
577
1290
|
throw new StoreError("not_found", "Route not found.");
|
|
578
1291
|
}),
|
|
579
1292
|
...createSqlDirectory(tx),
|
|
1293
|
+
...createSqlNotificationWebhookJobs(tx),
|
|
580
1294
|
ping: () => tx(async (sql) => { await sql.query("SELECT 1"); }),
|
|
581
1295
|
purgeExpired(at) {
|
|
582
1296
|
return tx(async (sql) => {
|
|
583
1297
|
const stamp = asTime(at);
|
|
584
1298
|
const seconds = Math.floor(Date.parse(stamp) / 1000);
|
|
585
1299
|
await sql.query("DELETE FROM sessions WHERE expires_at <= $1::timestamptz", [stamp]);
|
|
1300
|
+
await pruneSqlHostedHumanCredentials(sql, stamp);
|
|
1301
|
+
await sql.query("DELETE FROM cli_login_codes WHERE expires_at <= $1::timestamptz", [stamp]);
|
|
586
1302
|
await sql.query("DELETE FROM email_challenges WHERE expires_at <= $1::timestamptz", [stamp]);
|
|
587
1303
|
await sql.query("DELETE FROM authorization_requests WHERE expires_at <= $1::timestamptz", [stamp]);
|
|
588
1304
|
await sql.query("DELETE FROM denied_jtis WHERE exp <= $1", [seconds]);
|
|
589
1305
|
await sql.query("DELETE FROM sso_logins WHERE expires_at <= $1::timestamptz", [stamp]);
|
|
1306
|
+
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()]);
|
|
1307
|
+
await sql.query("DELETE FROM hosted_sso_profiles WHERE expires_at <= $1::timestamptz", [stamp]);
|
|
590
1308
|
await sql.query("DELETE FROM sso_exchanges WHERE expires_at <= $1::timestamptz", [stamp]);
|
|
591
1309
|
});
|
|
592
1310
|
},
|