@x12i/keyrox-store-pg 0.0.0-stage → 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 +10 -0
- package/dist/database.d.ts.map +1 -0
- package/dist/database.js +28 -0
- package/dist/database.js.map +1 -0
- 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 +8 -0
- package/dist/directory-sql.d.ts.map +1 -0
- package/dist/directory-sql.js +1052 -0
- package/dist/directory-sql.js.map +1 -0
- 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/index.d.ts +21 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +59 -0
- package/dist/index.js.map +1 -0
- package/dist/migrate.d.ts +4 -0
- package/dist/migrate.d.ts.map +1 -0
- package/dist/migrate.js +51 -0
- package/dist/migrate.js.map +1 -0
- 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 +54 -0
- package/dist/rows.d.ts.map +1 -0
- package/dist/rows.js +426 -0
- package/dist/rows.js.map +1 -0
- package/dist/sql-store.d.ts +4 -0
- package/dist/sql-store.d.ts.map +1 -0
- package/dist/sql-store.js +1350 -0
- package/dist/sql-store.js.map +1 -0
- package/migrations/001_init.sql +260 -0
- package/migrations/002_apps.sql +36 -0
- package/migrations/003_environments.sql +46 -0
- package/migrations/004_sso.sql +62 -0
- package/migrations/005_workloads.sql +64 -0
- package/migrations/006_directory.sql +155 -0
- 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 +36 -4
- package/README.md +0 -3
|
@@ -0,0 +1,1350 @@
|
|
|
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";
|
|
7
|
+
async function rows(sql, text, values = []) {
|
|
8
|
+
const result = await sql.query(text, values);
|
|
9
|
+
return result.rows;
|
|
10
|
+
}
|
|
11
|
+
async function first(sql, text, values, map) {
|
|
12
|
+
const found = await rows(sql, text, values);
|
|
13
|
+
return found[0] ? map(found[0]) : null;
|
|
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
|
+
}
|
|
41
|
+
async function revokeGrant(sql, id, at) {
|
|
42
|
+
const grant = await first(sql, "SELECT * FROM delegation_grants WHERE id = $1 FOR UPDATE", [id], grantOf);
|
|
43
|
+
if (!grant)
|
|
44
|
+
return null;
|
|
45
|
+
const changed = grant.revokedAt === null;
|
|
46
|
+
if (changed) {
|
|
47
|
+
grant.revokedAt = at;
|
|
48
|
+
await sql.query("UPDATE delegation_grants SET revoked_at = $2::timestamptz WHERE id = $1", [id, at]);
|
|
49
|
+
}
|
|
50
|
+
await sql.query("UPDATE long_lived_tokens SET revoked_at = $2::timestamptz WHERE grant_id = $1 AND revoked_at IS NULL", [id, grant.revokedAt]);
|
|
51
|
+
await sql.query("UPDATE refresh_tokens SET revoked_at = $2::timestamptz WHERE grant_id = $1 AND revoked_at IS NULL", [id, grant.revokedAt]);
|
|
52
|
+
return { grant, changed };
|
|
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
|
+
}
|
|
144
|
+
export function createSqlStore(database) {
|
|
145
|
+
const tx = (run) => database.transaction(run);
|
|
146
|
+
const store = {
|
|
147
|
+
...createSqlNotificationDeliveries(database),
|
|
148
|
+
...createSqlHostedHumanSessions(database),
|
|
149
|
+
signup(input) {
|
|
150
|
+
return tx(async (sql) => {
|
|
151
|
+
const user = { ...input.user, emailVerifiedAt: asTimeOrNull(input.user.emailVerifiedAt), disabledAt: asTimeOrNull(input.user.disabledAt), createdAt: asTime(input.user.createdAt) };
|
|
152
|
+
const org = { ...input.org, createdAt: asTime(input.org.createdAt) };
|
|
153
|
+
const membership = { ...input.membership, createdAt: asTime(input.membership.createdAt) };
|
|
154
|
+
if (membership.userId !== user.id || membership.orgId !== org.id || membership.role !== "owner") {
|
|
155
|
+
throw new StoreError("conflict", "Signup requires the new organization and its owner membership.");
|
|
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
|
+
}
|
|
168
|
+
const email = await rows(sql, "SELECT id FROM users WHERE lower(email) = lower($1)", [user.email]);
|
|
169
|
+
if (email.length)
|
|
170
|
+
throw new StoreError("duplicate_email", "Email already exists.");
|
|
171
|
+
const slug = await rows(sql, "SELECT id FROM orgs WHERE slug = $1", [org.slug]);
|
|
172
|
+
if (slug.length)
|
|
173
|
+
throw new StoreError("duplicate_slug", "Slug already exists.");
|
|
174
|
+
await sql.query(`INSERT INTO users (id, email, password_hash, display_name, email_verified_at, disabled_at, created_at, last_org_id)
|
|
175
|
+
VALUES ($1, $2, $3, $4, $5::timestamptz, $6::timestamptz, $7::timestamptz, $8)`, [user.id, user.email, user.passwordHash, user.displayName, user.emailVerifiedAt, user.disabledAt, user.createdAt, user.lastOrgId ?? null]);
|
|
176
|
+
await sql.query(`INSERT INTO orgs (id, slug, name, personal, allow_never_expire, allow_device_flow, grant_max_days, policy_version, created_at)
|
|
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]);
|
|
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
|
+
}
|
|
191
|
+
});
|
|
192
|
+
},
|
|
193
|
+
createOrg(input) {
|
|
194
|
+
return tx(async (sql) => {
|
|
195
|
+
const org = { ...input.org, createdAt: asTime(input.org.createdAt) };
|
|
196
|
+
const membership = { ...input.membership, createdAt: asTime(input.membership.createdAt) };
|
|
197
|
+
if (membership.orgId !== org.id || membership.role !== "owner")
|
|
198
|
+
throw new StoreError("conflict", "A new organization needs an owner membership.");
|
|
199
|
+
await sql.query("SELECT id FROM users WHERE id = $1 FOR UPDATE", [membership.userId]);
|
|
200
|
+
const owner = await rows(sql, "SELECT id FROM users WHERE id = $1", [membership.userId]);
|
|
201
|
+
if (!owner.length)
|
|
202
|
+
throw new StoreError("conflict", "User is missing.");
|
|
203
|
+
const slug = await rows(sql, "SELECT id FROM orgs WHERE slug = $1", [org.slug]);
|
|
204
|
+
if (slug.length)
|
|
205
|
+
throw new StoreError("duplicate_slug", "Slug already exists.");
|
|
206
|
+
await sql.query(`INSERT INTO orgs (id, slug, name, personal, allow_never_expire, allow_device_flow, grant_max_days, policy_version, created_at)
|
|
207
|
+
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]);
|
|
208
|
+
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, membership.role === "owner" || membership.productionAccess === true]);
|
|
209
|
+
});
|
|
210
|
+
},
|
|
211
|
+
getUser: (id) => tx((sql) => first(sql, "SELECT * FROM users WHERE id = $1", [id], userOf)),
|
|
212
|
+
findUserByEmail: (email) => tx((sql) => first(sql, "SELECT * FROM users WHERE lower(email) = lower($1)", [email], userOf)),
|
|
213
|
+
updateUser(user) {
|
|
214
|
+
return tx(async (sql) => {
|
|
215
|
+
const next = { ...user, emailVerifiedAt: asTimeOrNull(user.emailVerifiedAt), disabledAt: asTimeOrNull(user.disabledAt), createdAt: asTime(user.createdAt) };
|
|
216
|
+
const updated = await rows(sql, `UPDATE users SET email = $2, password_hash = $3, display_name = $4, email_verified_at = $5::timestamptz,
|
|
217
|
+
disabled_at = $6::timestamptz, created_at = $7::timestamptz, last_org_id = $8 WHERE id = $1 RETURNING id`, [next.id, next.email, next.passwordHash, next.displayName, next.emailVerifiedAt, next.disabledAt, next.createdAt, next.lastOrgId ?? null]);
|
|
218
|
+
if (!updated.length)
|
|
219
|
+
throw new StoreError("not_found", "User not found.");
|
|
220
|
+
});
|
|
221
|
+
},
|
|
222
|
+
getOrg: (id) => tx((sql) => first(sql, "SELECT * FROM orgs WHERE id = $1", [id], orgOf)),
|
|
223
|
+
findOrgBySlug: (slug) => tx((sql) => first(sql, "SELECT * FROM orgs WHERE slug = $1", [slug], orgOf)),
|
|
224
|
+
updateOrg(org) {
|
|
225
|
+
return tx(async (sql) => {
|
|
226
|
+
const next = { ...org, createdAt: asTime(org.createdAt) };
|
|
227
|
+
const updated = await rows(sql, `UPDATE orgs SET slug = $2, name = $3, personal = $4, allow_never_expire = $5, allow_device_flow = $6,
|
|
228
|
+
grant_max_days = $7, policy_version = $8, created_at = $9::timestamptz, logo_url = $10 WHERE id = $1 RETURNING id`, [next.id, next.slug, next.name, next.personal, next.policy.allowNeverExpire, next.policy.allowDeviceFlow, next.policy.grantMaxDays, next.policy.version, next.createdAt, next.logoUrl ?? null]);
|
|
229
|
+
if (!updated.length)
|
|
230
|
+
throw new StoreError("not_found", "Organization not found.");
|
|
231
|
+
});
|
|
232
|
+
},
|
|
233
|
+
findMembership: (userId, orgId) => tx((sql) => first(sql, "SELECT * FROM memberships WHERE user_id = $1 AND org_id = $2", [userId, orgId], membershipOf)),
|
|
234
|
+
listMembershipsByUser: (userId) => tx(async (sql) => (await rows(sql, "SELECT * FROM memberships WHERE user_id = $1 ORDER BY created_at, id", [userId])).map(membershipOf)),
|
|
235
|
+
listMembershipsByOrg: (orgId) => tx(async (sql) => (await rows(sql, "SELECT * FROM memberships WHERE org_id = $1 ORDER BY created_at, id", [orgId])).map(membershipOf)),
|
|
236
|
+
saveMembership(membership) {
|
|
237
|
+
return tx(async (sql) => {
|
|
238
|
+
const next = { ...membership, createdAt: asTime(membership.createdAt) };
|
|
239
|
+
const locked = await rows(sql, "SELECT * FROM memberships WHERE org_id = $1 ORDER BY id FOR UPDATE", [next.orgId]);
|
|
240
|
+
const existing = locked.map(membershipOf).find((row) => row.id === next.id && row.userId === next.userId);
|
|
241
|
+
if (!existing)
|
|
242
|
+
throw new StoreError("not_found", "Member not found.");
|
|
243
|
+
if (existing.role === "owner" && next.role !== "owner" && locked.map(membershipOf).filter((row) => row.role === "owner").length < 2) {
|
|
244
|
+
throw new StoreError("last_owner", "An organization must keep an owner.");
|
|
245
|
+
}
|
|
246
|
+
await sql.query("UPDATE memberships SET role = $2, actions = $3::text[], production_access = $4 WHERE id = $1", [next.id, next.role, next.actions, next.role === "owner" || next.productionAccess === true]);
|
|
247
|
+
});
|
|
248
|
+
},
|
|
249
|
+
removeMembership(input) {
|
|
250
|
+
return tx(async (sql) => {
|
|
251
|
+
const at = asTime(input.at);
|
|
252
|
+
const account = await rows(sql, "SELECT id FROM users WHERE id = $1 FOR UPDATE", [input.userId]);
|
|
253
|
+
if (!account.length)
|
|
254
|
+
throw new StoreError("not_found", "Member not found.");
|
|
255
|
+
const owned = (await rows(sql, "SELECT * FROM memberships WHERE user_id = $1 OR org_id = $2 ORDER BY id FOR UPDATE", [input.userId, input.orgId])).map(membershipOf);
|
|
256
|
+
const existing = owned.find((row) => row.userId === input.userId && row.orgId === input.orgId);
|
|
257
|
+
if (!existing)
|
|
258
|
+
throw new StoreError("not_found", "Member not found.");
|
|
259
|
+
if (owned.filter((row) => row.userId === input.userId).length < 2)
|
|
260
|
+
throw new StoreError("last_membership", "An account must belong to at least one organization.");
|
|
261
|
+
if (existing.role === "owner" && owned.filter((row) => row.orgId === input.orgId && row.role === "owner").length < 2) {
|
|
262
|
+
throw new StoreError("last_owner", "An organization must keep an owner.");
|
|
263
|
+
}
|
|
264
|
+
await sql.query("DELETE FROM memberships WHERE id = $1", [existing.id]);
|
|
265
|
+
const grants = await rows(sql, "SELECT id FROM delegation_grants WHERE user_id = $1 AND org_id = $2", [input.userId, input.orgId]);
|
|
266
|
+
for (const grant of grants)
|
|
267
|
+
await revokeGrant(sql, String(grant.id), at);
|
|
268
|
+
await sql.query("UPDATE long_lived_tokens SET revoked_at = $3::timestamptz WHERE user_id = $1 AND org_id = $2 AND revoked_at IS NULL", [input.userId, input.orgId, at]);
|
|
269
|
+
});
|
|
270
|
+
},
|
|
271
|
+
insertChallenge(row) {
|
|
272
|
+
return tx((sql) => writeEmailChallenge(sql, row));
|
|
273
|
+
},
|
|
274
|
+
reserveAccountChallenge(row, cooldownSince, delivery) {
|
|
275
|
+
return tx(async (sql) => {
|
|
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;
|
|
286
|
+
});
|
|
287
|
+
},
|
|
288
|
+
verifyEmail(tokenHash, at) {
|
|
289
|
+
return tx(async (sql) => {
|
|
290
|
+
const stamp = asTime(at);
|
|
291
|
+
const candidate = await first(sql, "SELECT * FROM email_challenges WHERE token_hash = $1 AND purpose = 'verify'", [tokenHash], challengeOf);
|
|
292
|
+
if (!candidate)
|
|
293
|
+
throw new StoreError("challenge_invalid", "Verification link is no longer valid.");
|
|
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))
|
|
299
|
+
throw new StoreError("challenge_invalid", "Verification link is no longer valid.");
|
|
300
|
+
await sql.query("UPDATE users SET email_verified_at = $2::timestamptz WHERE id = $1", [account.id, stamp]);
|
|
301
|
+
await sql.query("UPDATE email_challenges SET used_at = $2::timestamptz WHERE id = $1", [mapped.id, stamp]);
|
|
302
|
+
return { ...account, emailVerifiedAt: stamp };
|
|
303
|
+
});
|
|
304
|
+
},
|
|
305
|
+
resetPassword(input) {
|
|
306
|
+
return tx(async (sql) => {
|
|
307
|
+
const stamp = asTime(input.at);
|
|
308
|
+
const candidate = await first(sql, "SELECT * FROM email_challenges WHERE token_hash = $1 AND purpose = 'reset'", [input.tokenHash], challengeOf);
|
|
309
|
+
if (!candidate)
|
|
310
|
+
throw new StoreError("challenge_invalid", "Reset link is no longer valid.");
|
|
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))
|
|
316
|
+
throw new StoreError("challenge_invalid", "Reset link is no longer valid.");
|
|
317
|
+
const verified = account.emailVerifiedAt ?? stamp;
|
|
318
|
+
await sql.query("UPDATE users SET password_hash = $2, email_verified_at = $3::timestamptz WHERE id = $1", [account.id, input.passwordHash, verified]);
|
|
319
|
+
await sql.query("UPDATE email_challenges SET used_at = $2::timestamptz WHERE user_id = $1 AND purpose = 'reset' AND used_at IS NULL", [account.id, stamp]);
|
|
320
|
+
await sql.query("DELETE FROM sessions WHERE user_id = $1", [account.id]);
|
|
321
|
+
return { ...account, passwordHash: input.passwordHash, emailVerifiedAt: verified };
|
|
322
|
+
});
|
|
323
|
+
},
|
|
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) {
|
|
344
|
+
return tx(async (sql) => {
|
|
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;
|
|
356
|
+
});
|
|
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
|
+
},
|
|
362
|
+
acceptInvite(input) {
|
|
363
|
+
return tx(async (sql) => {
|
|
364
|
+
const at = asTime(input.at);
|
|
365
|
+
await sql.query("SELECT id FROM users WHERE id = $1 FOR UPDATE", [input.userId]);
|
|
366
|
+
const invite = await first(sql, "SELECT * FROM invites WHERE token_hash = $1 FOR UPDATE", [input.tokenHash], inviteOf);
|
|
367
|
+
if (!invite || invite.acceptedAt || invite.revokedAt || isExpired(invite.expiresAt, at))
|
|
368
|
+
throw new StoreError("invite_invalid", "Invite is no longer valid.");
|
|
369
|
+
const account = await first(sql, "SELECT * FROM users WHERE id = $1", [input.userId], userOf);
|
|
370
|
+
if (!account)
|
|
371
|
+
throw new StoreError("not_found", "User not found.");
|
|
372
|
+
if (invite.email.toLowerCase() !== input.email.toLowerCase() || invite.email.toLowerCase() !== account.email.toLowerCase()) {
|
|
373
|
+
throw new StoreError("invite_email", "Invite email does not match the account.");
|
|
374
|
+
}
|
|
375
|
+
const existing = await rows(sql, "SELECT id FROM memberships WHERE user_id = $1 AND org_id = $2", [account.id, invite.orgId]);
|
|
376
|
+
if (!existing.length) {
|
|
377
|
+
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)`, [input.membershipId, invite.orgId, account.id, invite.role, invite.actions, at, invite.role === "owner" || invite.productionAccess === true]);
|
|
378
|
+
}
|
|
379
|
+
await sql.query("UPDATE invites SET accepted_at = $2::timestamptz WHERE id = $1", [invite.id, at]);
|
|
380
|
+
return { ...invite, acceptedAt: at };
|
|
381
|
+
});
|
|
382
|
+
},
|
|
383
|
+
insertSession(row) {
|
|
384
|
+
return tx(async (sql) => {
|
|
385
|
+
await sql.query(`INSERT INTO sessions (id, user_id, org_id, secret_hash, csrf, expires_at, created_at)
|
|
386
|
+
VALUES ($1, $2, $3, $4, $5, $6::timestamptz, $7::timestamptz)`, [row.id, row.userId, row.orgId, row.secretHash, row.csrf, asTime(row.expiresAt), asTime(row.createdAt)]);
|
|
387
|
+
});
|
|
388
|
+
},
|
|
389
|
+
findSessionByHash: (secretHash) => tx((sql) => first(sql, "SELECT * FROM sessions WHERE secret_hash = $1", [secretHash], sessionOf)),
|
|
390
|
+
updateSession(session) {
|
|
391
|
+
return tx(async (sql) => {
|
|
392
|
+
const updated = await rows(sql, `UPDATE sessions SET user_id = $2, org_id = $3, secret_hash = $4, csrf = $5, expires_at = $6::timestamptz, created_at = $7::timestamptz
|
|
393
|
+
WHERE id = $1 RETURNING id`, [session.id, session.userId, session.orgId, session.secretHash, session.csrf, asTime(session.expiresAt), asTime(session.createdAt)]);
|
|
394
|
+
if (!updated.length)
|
|
395
|
+
throw new StoreError("not_found", "Session not found.");
|
|
396
|
+
});
|
|
397
|
+
},
|
|
398
|
+
deleteSession: (id) => tx(async (sql) => { await sql.query("DELETE FROM sessions WHERE id = $1", [id]); }),
|
|
399
|
+
insertClient(row) {
|
|
400
|
+
return tx(async (sql) => {
|
|
401
|
+
await sql.query(`INSERT INTO clients (id, name, auth_method, secret_hash, redirect_uris, created_at) VALUES ($1, $2, $3, $4, $5::text[], $6::timestamptz)`, [row.id, row.name, row.authMethod, row.secretHash, row.redirectUris, asTime(row.createdAt)]);
|
|
402
|
+
});
|
|
403
|
+
},
|
|
404
|
+
getClient: (id) => tx((sql) => first(sql, "SELECT * FROM clients WHERE id = $1", [id], clientOf)),
|
|
405
|
+
insertAgent(row) {
|
|
406
|
+
return tx(async (sql) => {
|
|
407
|
+
await sql.query(`INSERT INTO agents (id, name, client_id, owner_user_id, org_id, suspended_at, created_at)
|
|
408
|
+
VALUES ($1, $2, $3, $4, $5, $6::timestamptz, $7::timestamptz)`, [row.id, row.name, row.clientId, row.ownerUserId, row.orgId, asTimeOrNull(row.suspendedAt), asTime(row.createdAt)]);
|
|
409
|
+
});
|
|
410
|
+
},
|
|
411
|
+
getAgent: (id) => tx((sql) => first(sql, "SELECT * FROM agents WHERE id = $1", [id], agentOf)),
|
|
412
|
+
findAgentByClientOwner: (clientId, ownerUserId, orgId) => tx((sql) => first(sql, "SELECT * FROM agents WHERE client_id = $1 AND owner_user_id = $2 AND org_id = $3", [clientId, ownerUserId, orgId], agentOf)),
|
|
413
|
+
listAgentsByOrg: (orgId) => tx(async (sql) => (await rows(sql, "SELECT * FROM agents WHERE org_id = $1 ORDER BY created_at, id", [orgId])).map(agentOf)),
|
|
414
|
+
suspendAgent(id, at) {
|
|
415
|
+
return tx(async (sql) => {
|
|
416
|
+
const stamp = asTime(at);
|
|
417
|
+
const agent = await first(sql, "SELECT * FROM agents WHERE id = $1 FOR UPDATE", [id], agentOf);
|
|
418
|
+
if (!agent)
|
|
419
|
+
return null;
|
|
420
|
+
await sql.query("UPDATE agents SET suspended_at = $2::timestamptz WHERE id = $1", [id, stamp]);
|
|
421
|
+
const grants = await rows(sql, "SELECT id FROM delegation_grants WHERE agent_id = $1", [id]);
|
|
422
|
+
const revoked = [];
|
|
423
|
+
for (const grant of grants) {
|
|
424
|
+
const result = await revokeGrant(sql, String(grant.id), stamp);
|
|
425
|
+
if (result?.changed)
|
|
426
|
+
revoked.push(result.grant);
|
|
427
|
+
}
|
|
428
|
+
return { agent: { ...agent, suspendedAt: stamp }, revoked };
|
|
429
|
+
});
|
|
430
|
+
},
|
|
431
|
+
insertAuthorization(row) { return tx((sql) => insertAuthorization(sql, row)); },
|
|
432
|
+
getAuthorization: (id) => tx((sql) => first(sql, "SELECT * FROM authorization_requests WHERE id = $1", [id], authorizationOf)),
|
|
433
|
+
findAuthorization(filter) {
|
|
434
|
+
return tx((sql) => first(sql, `SELECT * FROM authorization_requests
|
|
435
|
+
WHERE ($1::text IS NULL OR code_hash = $1) AND ($2::text IS NULL OR device_code_hash = $2) AND ($3::text IS NULL OR user_code_hash = $3)
|
|
436
|
+
ORDER BY created_at, id LIMIT 1`, [filter.codeHash ?? null, filter.deviceCodeHash ?? null, filter.userCodeHash ?? null], authorizationOf));
|
|
437
|
+
},
|
|
438
|
+
updateAuthorization(row) {
|
|
439
|
+
return tx(async (sql) => {
|
|
440
|
+
const updated = await rows(sql, `UPDATE authorization_requests SET kind = $2, client_id = $3, redirect_uri = $4, code_challenge = $5, audience = $6,
|
|
441
|
+
actions = $7::text[], resources = $8::text[], state = $9, org_id = $10, user_id = $11, status = $12, code_hash = $13, device_code_hash = $14,
|
|
442
|
+
user_code_hash = $15, grant_id = $16, agent_id = $17, interval_seconds = $18, last_poll_at = $19::timestamptz, expires_at = $20::timestamptz, created_at = $21::timestamptz
|
|
443
|
+
WHERE id = $1 RETURNING id`, [
|
|
444
|
+
row.id, row.kind, row.clientId, row.redirectUri, row.codeChallenge, row.audience, row.actions, row.resources, row.state, row.orgId, row.userId,
|
|
445
|
+
row.status, row.codeHash, row.deviceCodeHash, row.userCodeHash, row.grantId, row.agentId, row.intervalSeconds, asTimeOrNull(row.lastPollAt),
|
|
446
|
+
asTime(row.expiresAt), asTime(row.createdAt),
|
|
447
|
+
]);
|
|
448
|
+
if (!updated.length)
|
|
449
|
+
throw new StoreError("not_found", "Authorization not found.");
|
|
450
|
+
});
|
|
451
|
+
},
|
|
452
|
+
listAuthorizationsByStatus: (status) => tx(async (sql) => (await rows(sql, "SELECT * FROM authorization_requests WHERE status = $1 ORDER BY created_at, id", [status])).map(authorizationOf)),
|
|
453
|
+
insertGrant(row) {
|
|
454
|
+
return tx(async (sql) => {
|
|
455
|
+
await sql.query(`INSERT INTO delegation_grants (id, user_id, org_id, client_id, agent_id, audience, actions, resources, jkt, approval_request_id, policy_version, created_at, expires_at, revoked_at)
|
|
456
|
+
VALUES ($1, $2, $3, $4, $5, $6, $7::text[], $8::text[], $9, $10, $11, $12::timestamptz, $13::timestamptz, $14::timestamptz)`, [row.id, row.userId, row.orgId, row.clientId, row.agentId, row.audience, row.actions, row.resources, row.jkt, row.approvalRequestId, row.policyVersion,
|
|
457
|
+
asTime(row.createdAt), asTime(row.expiresAt), asTimeOrNull(row.revokedAt)]);
|
|
458
|
+
});
|
|
459
|
+
},
|
|
460
|
+
getGrant: (id) => tx((sql) => first(sql, "SELECT * FROM delegation_grants WHERE id = $1", [id], grantOf)),
|
|
461
|
+
updateGrant(row) {
|
|
462
|
+
return tx(async (sql) => {
|
|
463
|
+
const updated = await rows(sql, `UPDATE delegation_grants SET user_id = $2, org_id = $3, client_id = $4, agent_id = $5, audience = $6, actions = $7::text[],
|
|
464
|
+
resources = $8::text[], jkt = $9, approval_request_id = $10, policy_version = $11, created_at = $12::timestamptz, expires_at = $13::timestamptz, revoked_at = $14::timestamptz
|
|
465
|
+
WHERE id = $1 RETURNING id`, [row.id, row.userId, row.orgId, row.clientId, row.agentId, row.audience, row.actions, row.resources, row.jkt, row.approvalRequestId, row.policyVersion,
|
|
466
|
+
asTime(row.createdAt), asTime(row.expiresAt), asTimeOrNull(row.revokedAt)]);
|
|
467
|
+
if (!updated.length)
|
|
468
|
+
throw new StoreError("not_found", "Grant not found.");
|
|
469
|
+
});
|
|
470
|
+
},
|
|
471
|
+
listGrants: (filter) => tx(async (sql) => (await rows(sql, `SELECT * FROM delegation_grants
|
|
472
|
+
WHERE ($1::text IS NULL OR org_id = $1) AND ($2::text IS NULL OR user_id = $2) AND ($3::text IS NULL OR agent_id = $3)
|
|
473
|
+
ORDER BY created_at, id`, [filter.orgId ?? null, filter.userId ?? null, filter.agentId ?? null])).map(grantOf)),
|
|
474
|
+
revokeGrant: (id, at) => tx((sql) => revokeGrant(sql, id, asTime(at))),
|
|
475
|
+
insertLongToken(row) { return tx((sql) => insertLongToken(sql, row)); },
|
|
476
|
+
getLongToken: (id) => tx((sql) => first(sql, "SELECT * FROM long_lived_tokens WHERE id = $1", [id], longTokenOf)),
|
|
477
|
+
findLongTokenByHash: (hash) => tx((sql) => first(sql, "SELECT * FROM long_lived_tokens WHERE hash = $1", [hash], longTokenOf)),
|
|
478
|
+
updateLongToken(row) {
|
|
479
|
+
return tx(async (sql) => {
|
|
480
|
+
const updated = await rows(sql, `UPDATE long_lived_tokens SET prefix = $2, hash = $3, kind = $4, name = $5, user_id = $6, org_id = $7, audience = $8,
|
|
481
|
+
actions = $9::text[], resources = $10::text[], grant_id = $11, agent_id = $12, expires_at = $13::timestamptz, revoked_at = $14::timestamptz,
|
|
482
|
+
created_at = $15::timestamptz, last_used_at = $16::timestamptz WHERE id = $1 RETURNING id`, [row.id, row.prefix, row.hash, row.kind, row.name, row.userId, row.orgId, row.audience, row.actions, row.resources, row.grantId, row.agentId,
|
|
483
|
+
asTimeOrNull(row.expiresAt), asTimeOrNull(row.revokedAt), asTime(row.createdAt), asTimeOrNull(row.lastUsedAt)]);
|
|
484
|
+
if (!updated.length)
|
|
485
|
+
throw new StoreError("not_found", "Token not found.");
|
|
486
|
+
});
|
|
487
|
+
},
|
|
488
|
+
listLongTokens: (filter) => tx(async (sql) => (await rows(sql, `SELECT * FROM long_lived_tokens
|
|
489
|
+
WHERE ($1::text IS NULL OR org_id = $1) AND ($2::text IS NULL OR user_id = $2) AND ($3::text IS NULL OR grant_id = $3)
|
|
490
|
+
ORDER BY created_at, id`, [filter.orgId ?? null, filter.userId ?? null, filter.grantId ?? null])).map(longTokenOf)),
|
|
491
|
+
revokeLongToken(id, at) {
|
|
492
|
+
return tx(async (sql) => {
|
|
493
|
+
const stamp = asTime(at);
|
|
494
|
+
const token = await first(sql, "SELECT * FROM long_lived_tokens WHERE id = $1 FOR UPDATE", [id], longTokenOf);
|
|
495
|
+
if (!token)
|
|
496
|
+
return null;
|
|
497
|
+
const already = token.revokedAt !== null;
|
|
498
|
+
if (!already) {
|
|
499
|
+
token.revokedAt = stamp;
|
|
500
|
+
await sql.query("UPDATE long_lived_tokens SET revoked_at = $2::timestamptz WHERE id = $1", [id, stamp]);
|
|
501
|
+
}
|
|
502
|
+
const revocation = token.grantId && !already ? await revokeGrant(sql, token.grantId, stamp) : null;
|
|
503
|
+
return { token, grant: revocation?.grant ?? null, grantChanged: revocation?.changed ?? false };
|
|
504
|
+
});
|
|
505
|
+
},
|
|
506
|
+
longLivedAccess(hash, at) {
|
|
507
|
+
return tx(async (sql) => {
|
|
508
|
+
const stamp = asTime(at);
|
|
509
|
+
const token = await first(sql, "SELECT * FROM long_lived_tokens WHERE hash = $1", [hash], longTokenOf);
|
|
510
|
+
const user = token ? await first(sql, "SELECT * FROM users WHERE id = $1", [token.userId], userOf) : null;
|
|
511
|
+
const membership = token ? await first(sql, "SELECT * FROM memberships WHERE user_id = $1 AND org_id = $2", [token.userId, token.orgId], membershipOf) : null;
|
|
512
|
+
const grant = token?.grantId ? await first(sql, "SELECT * FROM delegation_grants WHERE id = $1", [token.grantId], grantOf) : null;
|
|
513
|
+
const agent = token?.agentId ? await first(sql, "SELECT * FROM agents WHERE id = $1", [token.agentId], agentOf) : null;
|
|
514
|
+
return decideLongLived({ token, user, membership, grant, agent, at: stamp });
|
|
515
|
+
});
|
|
516
|
+
},
|
|
517
|
+
insertRefresh(row) { return tx((sql) => insertRefresh(sql, row)); },
|
|
518
|
+
findRefreshByHash: (hash) => tx((sql) => first(sql, "SELECT * FROM refresh_tokens WHERE hash = $1", [hash], refreshOf)),
|
|
519
|
+
rotateRefresh(input) {
|
|
520
|
+
return tx(async (sql) => {
|
|
521
|
+
const at = asTime(input.at);
|
|
522
|
+
const current = await first(sql, "SELECT * FROM refresh_tokens WHERE hash = $1 FOR UPDATE", [input.hash], refreshOf);
|
|
523
|
+
if (!current || current.clientId !== input.clientId)
|
|
524
|
+
return { status: "missing" };
|
|
525
|
+
if (current.rotatedAt || current.revokedAt) {
|
|
526
|
+
await sql.query("UPDATE refresh_tokens SET revoked_at = $2::timestamptz WHERE family_id = $1 AND revoked_at IS NULL", [current.familyId, at]);
|
|
527
|
+
const revocation = current.grantId ? await revokeGrant(sql, current.grantId, at) : null;
|
|
528
|
+
return { status: "reuse", grant: revocation?.grant ?? null, grantChanged: revocation?.changed ?? false };
|
|
529
|
+
}
|
|
530
|
+
if (isExpired(current.expiresAt, at))
|
|
531
|
+
return { status: "expired" };
|
|
532
|
+
const account = await first(sql, "SELECT * FROM users WHERE id = $1", [current.userId], userOf);
|
|
533
|
+
if (!account || account.disabledAt)
|
|
534
|
+
return { status: "inactive", reason: "user" };
|
|
535
|
+
const membership = await first(sql, "SELECT * FROM memberships WHERE user_id = $1 AND org_id = $2", [current.userId, current.orgId], membershipOf);
|
|
536
|
+
if (!membership)
|
|
537
|
+
return { status: "inactive", reason: "membership" };
|
|
538
|
+
const grant = current.grantId ? await first(sql, "SELECT * FROM delegation_grants WHERE id = $1", [current.grantId], grantOf) : null;
|
|
539
|
+
if (current.grantId && (!grant || grant.revokedAt || isExpired(grant.expiresAt, at)))
|
|
540
|
+
return { status: "inactive", reason: "grant" };
|
|
541
|
+
const actions = effectiveActions(membership, current.actions, grant);
|
|
542
|
+
if (!actions.length)
|
|
543
|
+
return { status: "inactive", reason: "actions" };
|
|
544
|
+
await sql.query("UPDATE refresh_tokens SET rotated_at = $2::timestamptz WHERE id = $1", [current.id, at]);
|
|
545
|
+
const next = {
|
|
546
|
+
id: input.next.id, hash: input.next.hash, familyId: current.familyId, grantId: current.grantId, clientId: current.clientId,
|
|
547
|
+
userId: current.userId, orgId: current.orgId, audience: current.audience, actions, resources: current.resources, agentId: current.agentId,
|
|
548
|
+
expiresAt: asTime(input.next.expiresAt), rotatedAt: null, revokedAt: null, createdAt: asTime(input.next.createdAt),
|
|
549
|
+
};
|
|
550
|
+
await insertRefresh(sql, next);
|
|
551
|
+
return { status: "rotated", token: next, actions, grant };
|
|
552
|
+
});
|
|
553
|
+
},
|
|
554
|
+
revokeRefreshFamily(hash, at) {
|
|
555
|
+
return tx(async (sql) => {
|
|
556
|
+
const stamp = asTime(at);
|
|
557
|
+
const current = await first(sql, "SELECT family_id FROM refresh_tokens WHERE hash = $1 FOR UPDATE", [hash], (row) => String(row.family_id));
|
|
558
|
+
if (!current)
|
|
559
|
+
return;
|
|
560
|
+
await sql.query("UPDATE refresh_tokens SET revoked_at = $2::timestamptz WHERE family_id = $1 AND revoked_at IS NULL", [current, stamp]);
|
|
561
|
+
});
|
|
562
|
+
},
|
|
563
|
+
insertInstance(row) {
|
|
564
|
+
return tx(async (sql) => {
|
|
565
|
+
await sql.query(`INSERT INTO agent_instances (id, agent_id, grant_id, jkt, created_at, last_seen_at) VALUES ($1, $2, $3, $4, $5::timestamptz, $6::timestamptz)`, [row.id, row.agentId, row.grantId, row.jkt, asTime(row.createdAt), asTime(row.lastSeenAt)]);
|
|
566
|
+
});
|
|
567
|
+
},
|
|
568
|
+
insertExecution(row) {
|
|
569
|
+
return tx(async (sql) => {
|
|
570
|
+
await sql.query(`INSERT INTO agent_executions (id, agent_id, instance_id, grant_id, trace, created_at) VALUES ($1, $2, $3, $4, $5, $6::timestamptz)`, [row.id, row.agentId, row.instanceId, row.grantId, row.trace, asTime(row.createdAt)]);
|
|
571
|
+
});
|
|
572
|
+
},
|
|
573
|
+
insertProvider(row) {
|
|
574
|
+
return tx(async (sql) => {
|
|
575
|
+
await sql.query(`INSERT INTO provider_connections (id, user_id, org_id, provider, account_label, scopes, access_token_enc, refresh_token_enc, base_url, revoked_at, created_at)
|
|
576
|
+
VALUES ($1, $2, $3, $4, $5, $6::text[], $7, $8, $9, $10::timestamptz, $11::timestamptz)`, [row.id, row.userId, row.orgId, row.provider, row.accountLabel, row.scopes, row.accessTokenEnc, row.refreshTokenEnc, row.baseUrl, asTimeOrNull(row.revokedAt), asTime(row.createdAt)]);
|
|
577
|
+
});
|
|
578
|
+
},
|
|
579
|
+
getProvider: (id) => tx((sql) => first(sql, "SELECT * FROM provider_connections WHERE id = $1", [id], providerOf)),
|
|
580
|
+
listProviders: (orgId, userId) => tx(async (sql) => (await rows(sql, "SELECT * FROM provider_connections WHERE org_id = $1 AND user_id = $2 ORDER BY created_at, id", [orgId, userId])).map(providerOf)),
|
|
581
|
+
insertTrust(row) {
|
|
582
|
+
return tx(async (sql) => {
|
|
583
|
+
await sql.query(`INSERT INTO workload_trusts (id, name, issuer, audience, tenant, org_id, actions, jwks, disabled_at, created_at)
|
|
584
|
+
VALUES ($1, $2, $3, $4, $5, $6, $7::text[], $8::jsonb, $9::timestamptz, $10::timestamptz)`, [row.id, row.name, row.issuer, row.audience, row.tenant, row.orgId, row.actions, JSON.stringify(row.jwks), asTimeOrNull(row.disabledAt), asTime(row.createdAt)]);
|
|
585
|
+
});
|
|
586
|
+
},
|
|
587
|
+
getTrust: (id) => tx((sql) => first(sql, "SELECT * FROM workload_trusts WHERE id = $1", [id], trustOf)),
|
|
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)),
|
|
589
|
+
insertAudit(row) {
|
|
590
|
+
return tx((sql) => writeAudit(sql, row));
|
|
591
|
+
},
|
|
592
|
+
listAudit: (query) => tx(async (sql) => (await rows(sql, `SELECT * FROM audit_events
|
|
593
|
+
WHERE org_id = $1
|
|
594
|
+
AND ($2::text IS NULL OR action = $2)
|
|
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 || ' ')
|
|
597
|
+
AND ($5::timestamptz IS NULL OR at >= $5::timestamptz)
|
|
598
|
+
AND ($6::timestamptz IS NULL OR at <= $6::timestamptz)
|
|
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`, [
|
|
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,
|
|
605
|
+
])).map(auditOf)),
|
|
606
|
+
getDeniedJti: (id) => tx((sql) => first(sql, "SELECT * FROM denied_jtis WHERE id = $1", [id], deniedOf)),
|
|
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]); }),
|
|
608
|
+
getIdempotency: (id) => tx((sql) => first(sql, "SELECT * FROM idempotency_records WHERE id = $1", [id], idempotencyOf)),
|
|
609
|
+
insertIdempotency(row) {
|
|
610
|
+
return tx(async (sql) => {
|
|
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)]);
|
|
612
|
+
});
|
|
613
|
+
},
|
|
614
|
+
insertApplication: (row) => tx((sql) => insertApp(sql, row)),
|
|
615
|
+
registerApplication({ application, environments, creatorAccess, audit }) {
|
|
616
|
+
return tx(async (sql) => {
|
|
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);
|
|
633
|
+
});
|
|
634
|
+
},
|
|
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]); }),
|
|
740
|
+
updateApplication(row) {
|
|
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
|
+
}
|
|
769
|
+
const updated = await rows(sql, `UPDATE applications SET
|
|
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`, [
|
|
779
|
+
row.id, row.title, row.description, row.status, row.allowedScopes, row.allowedFeatures, asTime(row.updatedAt),
|
|
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,
|
|
787
|
+
]);
|
|
788
|
+
if (!updated.length)
|
|
789
|
+
throw new StoreError("not_found", "Application not found.");
|
|
790
|
+
return repair;
|
|
791
|
+
});
|
|
792
|
+
},
|
|
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)),
|
|
798
|
+
updateEnvironment(row) {
|
|
799
|
+
return tx(async (sql) => {
|
|
800
|
+
await assertApplicationScope(sql, row.appId, row.orgId);
|
|
801
|
+
const updated = await rows(sql, `UPDATE app_environments SET
|
|
802
|
+
title = $2, status = $3, secret_enc = $4, secret_hash = $5, key_version = $6,
|
|
803
|
+
previous_secret_enc = $7, previous_secret_hash = $8, previous_key_version = $9,
|
|
804
|
+
previous_key_expires_at = $10::timestamptz, updated_at = $11::timestamptz
|
|
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`, [
|
|
807
|
+
row.id, row.title, row.status, row.secretEnc, row.secretHash, row.keyVersion,
|
|
808
|
+
row.previousSecretEnc, row.previousSecretHash, row.previousKeyVersion, asTimeOrNull(row.previousKeyExpiresAt), asTime(row.updatedAt), row.appId, row.orgId, row.name,
|
|
809
|
+
]);
|
|
810
|
+
if (!updated.length)
|
|
811
|
+
throw new StoreError("not_found", "Environment not found.");
|
|
812
|
+
});
|
|
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
|
+
},
|
|
913
|
+
insertAppToken(row) {
|
|
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.");
|
|
919
|
+
await sql.query(`INSERT INTO app_tokens (
|
|
920
|
+
id, app_id, environment_id, org_id, owner_identity_id, identity_type, payload, encrypted, revoked_at, expires_at, created_at
|
|
921
|
+
) VALUES ($1, $2, $3, $4, $5, $6, $7::jsonb, $8, $9::timestamptz, $10::timestamptz, $11::timestamptz)`, [
|
|
922
|
+
row.id, row.appId, row.environmentId, row.orgId, row.ownerIdentityId, row.identityType, JSON.stringify(row.payload), row.encrypted,
|
|
923
|
+
asTimeOrNull(row.revokedAt), asTimeOrNull(row.expiresAt), asTime(row.createdAt),
|
|
924
|
+
]);
|
|
925
|
+
});
|
|
926
|
+
},
|
|
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)),
|
|
934
|
+
revokeAppToken: (id, at) => tx(async (sql) => {
|
|
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);
|
|
939
|
+
}),
|
|
940
|
+
revokeAppTokens: (filter, at) => tx(async (sql) => {
|
|
941
|
+
const updated = await rows(sql, `UPDATE app_tokens SET revoked_at = $5::timestamptz
|
|
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)
|
|
944
|
+
RETURNING id`, [filter.appId ?? null, filter.environmentId ?? null, filter.identityId ?? null, filter.orgId ?? null, asTime(at)]);
|
|
945
|
+
return updated.length;
|
|
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)),
|
|
1004
|
+
saveSignInConnection: (row) => tx(async (sql) => {
|
|
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);
|
|
1025
|
+
}),
|
|
1026
|
+
saveAppSignIn: (appId, providers) => tx(async (sql) => {
|
|
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]);
|
|
1028
|
+
}),
|
|
1029
|
+
getAppSignIn: (appId) => tx(async (sql) => textsOf(await first(sql, "SELECT providers FROM app_sign_in WHERE app_id = $1", [appId], (row) => row))),
|
|
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.");
|
|
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]);
|
|
1036
|
+
}),
|
|
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
|
+
}),
|
|
1094
|
+
insertSsoLogin: (row) => tx(async (sql) => {
|
|
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,
|
|
1102
|
+
]);
|
|
1103
|
+
}),
|
|
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;
|
|
1109
|
+
const found = await first(sql, "DELETE FROM sso_logins WHERE state_hash = $1 RETURNING *", [stateHash], ssoLoginOf);
|
|
1110
|
+
if (!found || Date.parse(found.expiresAt) <= Date.parse(asTime(at)))
|
|
1111
|
+
return null;
|
|
1112
|
+
return found;
|
|
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
|
+
}),
|
|
1202
|
+
insertSsoExchange: (row) => tx(async (sql) => {
|
|
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,
|
|
1211
|
+
]);
|
|
1212
|
+
}),
|
|
1213
|
+
getSsoExchange: (codeHash, at) => tx((sql) => first(sql, ssoExchangeQuery, [codeHash, asTime(at)], ssoExchangeOf)),
|
|
1214
|
+
takeSsoExchange: (codeHash, at) => tx(async (sql) => {
|
|
1215
|
+
const exchange = await first(sql, `${ssoExchangeQuery} FOR SHARE OF app, token`, [codeHash, asTime(at)], ssoExchangeOf);
|
|
1216
|
+
if (!exchange)
|
|
1217
|
+
return null;
|
|
1218
|
+
return first(sql, "DELETE FROM sso_exchanges WHERE id = $1 RETURNING *", [exchange.id], ssoExchangeOf);
|
|
1219
|
+
}),
|
|
1220
|
+
insertServiceCredential: (row) => tx(async (sql) => {
|
|
1221
|
+
await sql.query(`INSERT INTO service_credentials (id, org_id, name, secret_hash, app_ids, permissions, revoked_at, created_at)
|
|
1222
|
+
VALUES ($1,$2,$3,$4,$5,$6,$7::timestamptz,$8::timestamptz)`, [row.id, row.orgId, row.name, row.secretHash, row.appIds, row.permissions, asTimeOrNull(row.revokedAt), asTime(row.createdAt)]);
|
|
1223
|
+
}),
|
|
1224
|
+
listServiceCredentials: (orgId) => tx(async (sql) => (await rows(sql, "SELECT * FROM service_credentials WHERE org_id = $1 ORDER BY created_at DESC", [orgId])).map(serviceCredentialOf)),
|
|
1225
|
+
findServiceCredentialByHash: (hash) => tx((sql) => first(sql, "SELECT * FROM service_credentials WHERE secret_hash = $1", [hash], serviceCredentialOf)),
|
|
1226
|
+
revokeServiceCredential: (id, at) => tx(async (sql) => {
|
|
1227
|
+
await sql.query("UPDATE service_credentials SET revoked_at = $2::timestamptz WHERE id = $1 AND revoked_at IS NULL", [id, asTime(at)]);
|
|
1228
|
+
return first(sql, "SELECT * FROM service_credentials WHERE id = $1", [id], serviceCredentialOf);
|
|
1229
|
+
}),
|
|
1230
|
+
insertPrincipal: (row) => tx(async (sql) => {
|
|
1231
|
+
await sql.query(`INSERT INTO workload_principals (id, org_id, name, client_id, enabled, created_at) VALUES ($1,$2,$3,$4,$5,$6::timestamptz)`, [row.id, row.orgId, row.name, row.clientId, row.enabled, asTime(row.createdAt)]);
|
|
1232
|
+
}),
|
|
1233
|
+
listPrincipals: (orgId) => tx(async (sql) => (await rows(sql, "SELECT * FROM workload_principals WHERE org_id = $1 ORDER BY created_at DESC", [orgId])).map(principalOf)),
|
|
1234
|
+
findPrincipalByClientId: (clientId) => tx((sql) => first(sql, "SELECT * FROM workload_principals WHERE client_id = $1", [clientId], principalOf)),
|
|
1235
|
+
insertWorkloadCredential: (row) => tx(async (sql) => {
|
|
1236
|
+
await sql.query(`INSERT INTO workload_credentials (id, principal_id, org_id, kind, secret_hash, jwks, created_at) VALUES ($1,$2,$3,$4,$5,$6::jsonb,$7::timestamptz)`, [row.id, row.principalId, row.orgId, row.kind, row.secretHash, JSON.stringify(row.jwks), asTime(row.createdAt)]);
|
|
1237
|
+
}),
|
|
1238
|
+
listWorkloadCredentials: (principalId) => tx(async (sql) => (await rows(sql, "SELECT * FROM workload_credentials WHERE principal_id = $1", [principalId])).map(workloadCredentialOf)),
|
|
1239
|
+
insertAudience: (row) => tx(async (sql) => {
|
|
1240
|
+
if (row.appId)
|
|
1241
|
+
await assertApplicationScope(sql, row.appId, row.orgId, "conflict");
|
|
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)]);
|
|
1243
|
+
}),
|
|
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)),
|
|
1250
|
+
insertRole: (row) => tx(async (sql) => {
|
|
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)]);
|
|
1252
|
+
}),
|
|
1253
|
+
listRoles: (orgId) => tx(async (sql) => (await rows(sql, "SELECT * FROM role_definitions WHERE org_id = $1", [orgId])).map(roleOf)),
|
|
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.");
|
|
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)]);
|
|
1267
|
+
}),
|
|
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
|
+
}),
|
|
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");
|
|
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)]);
|
|
1285
|
+
}),
|
|
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)),
|
|
1287
|
+
deleteGatewayRoute: (id, orgId) => tx(async (sql) => {
|
|
1288
|
+
const removed = await rows(sql, "DELETE FROM gateway_routes WHERE id = $1 AND org_id = $2 RETURNING id", [id, orgId]);
|
|
1289
|
+
if (!removed.length)
|
|
1290
|
+
throw new StoreError("not_found", "Route not found.");
|
|
1291
|
+
}),
|
|
1292
|
+
...createSqlDirectory(tx),
|
|
1293
|
+
...createSqlNotificationWebhookJobs(tx),
|
|
1294
|
+
ping: () => tx(async (sql) => { await sql.query("SELECT 1"); }),
|
|
1295
|
+
purgeExpired(at) {
|
|
1296
|
+
return tx(async (sql) => {
|
|
1297
|
+
const stamp = asTime(at);
|
|
1298
|
+
const seconds = Math.floor(Date.parse(stamp) / 1000);
|
|
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]);
|
|
1302
|
+
await sql.query("DELETE FROM email_challenges WHERE expires_at <= $1::timestamptz", [stamp]);
|
|
1303
|
+
await sql.query("DELETE FROM authorization_requests WHERE expires_at <= $1::timestamptz", [stamp]);
|
|
1304
|
+
await sql.query("DELETE FROM denied_jtis WHERE exp <= $1", [seconds]);
|
|
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]);
|
|
1308
|
+
await sql.query("DELETE FROM sso_exchanges WHERE expires_at <= $1::timestamptz", [stamp]);
|
|
1309
|
+
});
|
|
1310
|
+
},
|
|
1311
|
+
};
|
|
1312
|
+
return store;
|
|
1313
|
+
}
|
|
1314
|
+
function textsOf(row) {
|
|
1315
|
+
const value = row?.uris ?? row?.providers;
|
|
1316
|
+
return Array.isArray(value) ? value.map(String) : [];
|
|
1317
|
+
}
|
|
1318
|
+
function insertAuthorization(sql, row) {
|
|
1319
|
+
return sql.query(`INSERT INTO authorization_requests (
|
|
1320
|
+
id, kind, client_id, redirect_uri, code_challenge, audience, actions, resources, state, org_id, user_id, status, code_hash,
|
|
1321
|
+
device_code_hash, user_code_hash, grant_id, agent_id, interval_seconds, last_poll_at, expires_at, created_at
|
|
1322
|
+
) VALUES (
|
|
1323
|
+
$1, $2, $3, $4, $5, $6, $7::text[], $8::text[], $9, $10, $11, $12, $13, $14, $15, $16, $17, $18, $19::timestamptz, $20::timestamptz, $21::timestamptz
|
|
1324
|
+
)`, [
|
|
1325
|
+
row.id, row.kind, row.clientId, row.redirectUri, row.codeChallenge, row.audience, row.actions, row.resources, row.state, row.orgId, row.userId,
|
|
1326
|
+
row.status, row.codeHash, row.deviceCodeHash, row.userCodeHash, row.grantId, row.agentId, row.intervalSeconds, asTimeOrNull(row.lastPollAt),
|
|
1327
|
+
asTime(row.expiresAt), asTime(row.createdAt),
|
|
1328
|
+
]).then(() => undefined);
|
|
1329
|
+
}
|
|
1330
|
+
function insertLongToken(sql, row) {
|
|
1331
|
+
return sql.query(`INSERT INTO long_lived_tokens (
|
|
1332
|
+
id, prefix, hash, kind, name, user_id, org_id, audience, actions, resources, grant_id, agent_id, expires_at, revoked_at, created_at, last_used_at
|
|
1333
|
+
) VALUES (
|
|
1334
|
+
$1, $2, $3, $4, $5, $6, $7, $8, $9::text[], $10::text[], $11, $12, $13::timestamptz, $14::timestamptz, $15::timestamptz, $16::timestamptz
|
|
1335
|
+
)`, [
|
|
1336
|
+
row.id, row.prefix, row.hash, row.kind, row.name, row.userId, row.orgId, row.audience, row.actions, row.resources, row.grantId, row.agentId,
|
|
1337
|
+
asTimeOrNull(row.expiresAt), asTimeOrNull(row.revokedAt), asTime(row.createdAt), asTimeOrNull(row.lastUsedAt),
|
|
1338
|
+
]).then(() => undefined);
|
|
1339
|
+
}
|
|
1340
|
+
function insertRefresh(sql, row) {
|
|
1341
|
+
return sql.query(`INSERT INTO refresh_tokens (
|
|
1342
|
+
id, hash, family_id, grant_id, client_id, user_id, org_id, audience, actions, resources, agent_id, expires_at, rotated_at, revoked_at, created_at
|
|
1343
|
+
) VALUES (
|
|
1344
|
+
$1, $2, $3, $4, $5, $6, $7, $8, $9::text[], $10::text[], $11, $12::timestamptz, $13::timestamptz, $14::timestamptz, $15::timestamptz
|
|
1345
|
+
)`, [
|
|
1346
|
+
row.id, row.hash, row.familyId, row.grantId, row.clientId, row.userId, row.orgId, row.audience, row.actions, row.resources, row.agentId,
|
|
1347
|
+
asTime(row.expiresAt), asTimeOrNull(row.rotatedAt), asTimeOrNull(row.revokedAt), asTime(row.createdAt),
|
|
1348
|
+
]).then(() => undefined);
|
|
1349
|
+
}
|
|
1350
|
+
//# sourceMappingURL=sql-store.js.map
|