@x12i/keyrox-store-pg 0.1.4 → 0.1.6
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/delegation-sql.d.ts +10 -0
- package/dist/delegation-sql.d.ts.map +1 -0
- package/dist/delegation-sql.js +160 -0
- package/dist/delegation-sql.js.map +1 -0
- package/dist/directory-access-sql.d.ts.map +1 -1
- package/dist/directory-access-sql.js +6 -0
- package/dist/directory-access-sql.js.map +1 -1
- package/dist/directory-sql.d.ts +1 -1
- package/dist/directory-sql.d.ts.map +1 -1
- package/dist/directory-sql.js +50 -1
- package/dist/directory-sql.js.map +1 -1
- package/dist/rows.d.ts +6 -0
- package/dist/rows.d.ts.map +1 -1
- package/dist/rows.js +44 -0
- package/dist/rows.js.map +1 -1
- package/dist/sql-store.d.ts.map +1 -1
- package/dist/sql-store.js +184 -7
- package/dist/sql-store.js.map +1 -1
- package/migrations/051_suite_account.sql +5 -0
- package/migrations/052_super_admin.sql +1 -0
- package/migrations/053_stations.sql +48 -0
- package/migrations/054_safe_share.sql +44 -0
- package/migrations/055_customer_access.sql +60 -0
- package/migrations/056_customer_access_portal.sql +13 -0
- package/package.json +38 -38
package/dist/sql-store.js
CHANGED
|
@@ -1,9 +1,10 @@
|
|
|
1
|
-
import { appIdFromTenantResource, applicationLifecycleTime, applicationMoveKeys, asTime, asTimeOrNull, decideLongLived, effectiveActions, hostedEmailCodePolicy, isExpired, StoreError, verifyApplicationTrashSnapshot, } from "@x12i/keyrox-store";
|
|
1
|
+
import { appIdFromTenantResource, applicationLifecycleTime, applicationMoveKeys, asTime, asTimeOrNull, decideLongLived, effectiveActions, hostedEmailCodePolicy, isExpired, planSafeSharePush, planStationRegistration, safeShareDocumentProblem, StoreError, verifyApplicationTrashSnapshot, } from "@x12i/keyrox-store";
|
|
2
|
+
import { createSqlDelegation } from "./delegation-sql.js";
|
|
2
3
|
import { createSqlDirectory, repairDirectoryStructure } from "./directory-sql.js";
|
|
3
4
|
import { createSqlHostedHumanSessions, pruneSqlHostedHumanCredentials } from "./hosted-human-sessions.js";
|
|
4
5
|
import { createSqlNotificationWebhookJobs } from "./notification-webhook-sql.js";
|
|
5
6
|
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
|
+
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, safeShareDocumentOf, safeShareOf, safeShareSummaryOf, serviceCredentialOf, sessionOf, stationOf, stationRegistrationOf, accountHandoffOf, accountIdentityOf, accountSsoLoginOf, accountSsoProfileOf, cliLoginCodeOf, platformSignInOf, signInOf, hostedEmailCodeOf, hostedHumanClientOf, hostedHumanCodeOf, hostedSsoProfileOf, ssoExchangeOf, ssoLoginOf, trustOf, userOf, workloadCredentialOf, audienceOf, assignmentOf, } from "./rows.js";
|
|
7
8
|
async function rows(sql, text, values = []) {
|
|
8
9
|
const result = await sql.query(text, values);
|
|
9
10
|
return result.rows;
|
|
@@ -67,6 +68,15 @@ async function assertApplicationScope(sql, appId, orgId, code = "not_found") {
|
|
|
67
68
|
if (!app.length)
|
|
68
69
|
throw new StoreError(code, "Application not found in this tenant.");
|
|
69
70
|
}
|
|
71
|
+
/** Whether the application is active (not in the Trash) in this Team. It holds the application row against a move or a purge until the transaction ends. */
|
|
72
|
+
async function activeApplicationIn(sql, appId, orgId) {
|
|
73
|
+
return (await rows(sql, "SELECT id FROM applications WHERE id = $1 AND org_id = $2 AND trashed_at IS NULL FOR SHARE", [appId, orgId])).length > 0;
|
|
74
|
+
}
|
|
75
|
+
/** An application's safe-share and its documents. They go with the application, and they do not move with it. */
|
|
76
|
+
async function deleteSafeShare(sql, appId) {
|
|
77
|
+
await sql.query("DELETE FROM safe_share_documents WHERE app_id = $1", [appId]);
|
|
78
|
+
await sql.query("DELETE FROM app_safe_shares WHERE app_id = $1", [appId]);
|
|
79
|
+
}
|
|
70
80
|
async function ensureAnotherNotificationWebhook(sql, environmentId, webhookId) {
|
|
71
81
|
const last = await rows(sql, `SELECT hook.id FROM app_notification_webhooks hook
|
|
72
82
|
JOIN app_notification_settings settings ON settings.environment_id = hook.environment_id
|
|
@@ -92,6 +102,7 @@ async function purgeApplication(sql, app) {
|
|
|
92
102
|
await sql.query("DELETE FROM sso_exchanges WHERE app_id = $1", [app.id]);
|
|
93
103
|
await sql.query("DELETE FROM app_waitlist WHERE app_id = $1", [app.id]);
|
|
94
104
|
await sql.query("DELETE FROM directory_challenges WHERE environment_id IN (SELECT id FROM app_environments WHERE app_id = $1)", [app.id]);
|
|
105
|
+
await deleteSafeShare(sql, app.id);
|
|
95
106
|
await sql.query("DELETE FROM applications WHERE id = $1 AND org_id = $2 AND trashed_at IS NOT NULL", [app.id, app.orgId]);
|
|
96
107
|
}
|
|
97
108
|
async function insertApp(sql, row) {
|
|
@@ -171,8 +182,8 @@ export function createSqlStore(database) {
|
|
|
171
182
|
const slug = await rows(sql, "SELECT id FROM orgs WHERE slug = $1", [org.slug]);
|
|
172
183
|
if (slug.length)
|
|
173
184
|
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, password_change_required)
|
|
175
|
-
VALUES ($1, $2, $3, $4, $5::timestamptz, $6::timestamptz, $7::timestamptz, $8, $9)`, [user.id, user.email, user.passwordHash, user.displayName, user.emailVerifiedAt, user.disabledAt, user.createdAt, user.lastOrgId ?? null, user.passwordChangeRequired === true]);
|
|
185
|
+
await sql.query(`INSERT INTO users (id, email, password_hash, display_name, email_verified_at, disabled_at, created_at, last_org_id, password_change_required, super_admin)
|
|
186
|
+
VALUES ($1, $2, $3, $4, $5::timestamptz, $6::timestamptz, $7::timestamptz, $8, $9, $10)`, [user.id, user.email, user.passwordHash, user.displayName, user.emailVerifiedAt, user.disabledAt, user.createdAt, user.lastOrgId ?? null, user.passwordChangeRequired === true, user.superAdmin === true]);
|
|
176
187
|
await sql.query(`INSERT INTO orgs (id, slug, name, personal, allow_never_expire, allow_device_flow, grant_max_days, policy_version, created_at)
|
|
177
188
|
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
189
|
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]);
|
|
@@ -210,22 +221,26 @@ export function createSqlStore(database) {
|
|
|
210
221
|
},
|
|
211
222
|
getUser: (id) => tx((sql) => first(sql, "SELECT * FROM users WHERE id = $1", [id], userOf)),
|
|
212
223
|
findUserByEmail: (email) => tx((sql) => first(sql, "SELECT * FROM users WHERE lower(email) = lower($1)", [email], userOf)),
|
|
224
|
+
listUsers: () => tx(async (sql) => (await rows(sql, "SELECT * FROM users ORDER BY lower(email), id")).map(userOf)),
|
|
213
225
|
updateUser(user) {
|
|
214
226
|
return tx(async (sql) => {
|
|
215
227
|
const next = { ...user, emailVerifiedAt: asTimeOrNull(user.emailVerifiedAt), disabledAt: asTimeOrNull(user.disabledAt), createdAt: asTime(user.createdAt) };
|
|
216
228
|
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, password_change_required = $9 WHERE id = $1 RETURNING id`, [next.id, next.email, next.passwordHash, next.displayName, next.emailVerifiedAt, next.disabledAt, next.createdAt, next.lastOrgId ?? null, next.passwordChangeRequired === true]);
|
|
229
|
+
disabled_at = $6::timestamptz, created_at = $7::timestamptz, last_org_id = $8, password_change_required = $9, super_admin = $10 WHERE id = $1 RETURNING id`, [next.id, next.email, next.passwordHash, next.displayName, next.emailVerifiedAt, next.disabledAt, next.createdAt, next.lastOrgId ?? null, next.passwordChangeRequired === true, next.superAdmin === true]);
|
|
218
230
|
if (!updated.length)
|
|
219
231
|
throw new StoreError("not_found", "User not found.");
|
|
220
232
|
});
|
|
221
233
|
},
|
|
222
234
|
getOrg: (id) => tx((sql) => first(sql, "SELECT * FROM orgs WHERE id = $1", [id], orgOf)),
|
|
235
|
+
listOrgs: () => tx(async (sql) => (await rows(sql, "SELECT * FROM orgs ORDER BY lower(name), id")).map(orgOf)),
|
|
223
236
|
findOrgBySlug: (slug) => tx((sql) => first(sql, "SELECT * FROM orgs WHERE slug = $1", [slug], orgOf)),
|
|
237
|
+
findOrgBySuiteAccountId: (suiteAccountId) => tx((sql) => first(sql, "SELECT * FROM orgs WHERE suite_account_id = $1", [suiteAccountId], orgOf)),
|
|
224
238
|
updateOrg(org) {
|
|
225
239
|
return tx(async (sql) => {
|
|
226
240
|
const next = { ...org, createdAt: asTime(org.createdAt) };
|
|
227
241
|
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
|
|
242
|
+
grant_max_days = $7, policy_version = $8, created_at = $9::timestamptz, logo_url = $10,
|
|
243
|
+
suite_account_id = $11, suite_account_version = $12 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, next.suiteAccountId ?? null, next.suiteAccountVersion ?? 0]);
|
|
229
244
|
if (!updated.length)
|
|
230
245
|
throw new StoreError("not_found", "Organization not found.");
|
|
231
246
|
});
|
|
@@ -271,6 +286,17 @@ export function createSqlStore(database) {
|
|
|
271
286
|
insertChallenge(row) {
|
|
272
287
|
return tx((sql) => writeEmailChallenge(sql, row));
|
|
273
288
|
},
|
|
289
|
+
replaceAccountResetChallenge(row) {
|
|
290
|
+
return tx(async (sql) => {
|
|
291
|
+
if (row.purpose !== "reset")
|
|
292
|
+
throw new StoreError("conflict", "Reset challenge is required.");
|
|
293
|
+
const account = await first(sql, "SELECT * FROM users WHERE id = $1 FOR UPDATE", [row.userId], userOf);
|
|
294
|
+
if (!account || account.disabledAt)
|
|
295
|
+
throw new StoreError("not_found", "User not found.");
|
|
296
|
+
await sql.query("UPDATE email_challenges SET used_at = $2::timestamptz WHERE user_id = $1 AND purpose = 'reset' AND used_at IS NULL", [row.userId, asTime(row.createdAt)]);
|
|
297
|
+
await writeEmailChallenge(sql, row);
|
|
298
|
+
});
|
|
299
|
+
},
|
|
274
300
|
reserveAccountChallenge(row, cooldownSince, delivery) {
|
|
275
301
|
return tx(async (sql) => {
|
|
276
302
|
const account = await first(sql, "SELECT * FROM users WHERE id = $1 FOR UPDATE", [row.userId], userOf);
|
|
@@ -285,6 +311,11 @@ export function createSqlStore(database) {
|
|
|
285
311
|
return true;
|
|
286
312
|
});
|
|
287
313
|
},
|
|
314
|
+
releaseAccountChallenge(id) {
|
|
315
|
+
return tx(async (sql) => {
|
|
316
|
+
await sql.query("DELETE FROM email_challenges WHERE id = $1 AND used_at IS NULL", [id]);
|
|
317
|
+
});
|
|
318
|
+
},
|
|
288
319
|
verifyEmail(tokenHash, at) {
|
|
289
320
|
return tx(async (sql) => {
|
|
290
321
|
const stamp = asTime(at);
|
|
@@ -371,7 +402,7 @@ export function createSqlStore(database) {
|
|
|
371
402
|
return null;
|
|
372
403
|
await checkPendingInvite(sql, row, input.at);
|
|
373
404
|
const rotated = await first(sql, `UPDATE invites SET token_hash = $2, expires_at = $3::timestamptz,
|
|
374
|
-
last_mail_requested_at = $4::timestamptz WHERE id = $1 RETURNING *`, [row.id, input.tokenHash, asTime(input.expiresAt), asTime(input.at)], inviteOf);
|
|
405
|
+
last_mail_requested_at = COALESCE($4::timestamptz, last_mail_requested_at) WHERE id = $1 RETURNING *`, [row.id, input.tokenHash, asTime(input.expiresAt), input.delivery || input.mailRequested ? asTime(input.at) : null], inviteOf);
|
|
375
406
|
if (rotated)
|
|
376
407
|
await insertSqlNotificationDelivery(sql, input.delivery);
|
|
377
408
|
return rotated;
|
|
@@ -381,6 +412,7 @@ export function createSqlStore(database) {
|
|
|
381
412
|
return tx(async (sql) => (await rows(sql, `UPDATE invites SET revoked_at = $3::timestamptz WHERE org_id = $1 AND id = $2
|
|
382
413
|
AND accepted_at IS NULL AND revoked_at IS NULL RETURNING id`, [orgId, inviteId, asTime(at)])).length > 0);
|
|
383
414
|
},
|
|
415
|
+
findInviteByToken: (tokenHash) => tx((sql) => first(sql, "SELECT * FROM invites WHERE token_hash = $1", [tokenHash], inviteOf)),
|
|
384
416
|
acceptInvite(input) {
|
|
385
417
|
return tx(async (sql) => {
|
|
386
418
|
const at = asTime(input.at);
|
|
@@ -685,6 +717,12 @@ export function createSqlStore(database) {
|
|
|
685
717
|
if (mixed.length)
|
|
686
718
|
throw new StoreError("conflict", "An application gateway route uses a shared tenant resource or audience. Update its scope before moving the application.");
|
|
687
719
|
await removeApplicationTenantAccess(sql, sourceOrgId, appId, stamp);
|
|
720
|
+
await deleteSafeShare(sql, appId);
|
|
721
|
+
// Customer access does not move with the application: the new Team opts in again, and no session of the old one goes on. The
|
|
722
|
+
// portal address and the allowed origins name hosts of the old Team, and a link is built on the first of them, so neither stays.
|
|
723
|
+
await sql.query(`UPDATE customer_access SET enabled = false, portal_url = NULL, allowed_origins = '{}', updated_at = $2::timestamptz
|
|
724
|
+
WHERE (enabled OR portal_url IS NOT NULL OR cardinality(allowed_origins) > 0) AND environment_id IN (SELECT id FROM app_environments WHERE app_id = $1)`, [appId, stamp]);
|
|
725
|
+
await sql.query("UPDATE delegations SET ended_at = $2::timestamptz WHERE app_id = $1 AND ended_at IS NULL", [appId, stamp]);
|
|
688
726
|
await sql.query("DELETE FROM sso_logins WHERE app_id = $1", [appId]);
|
|
689
727
|
await sql.query("DELETE FROM sso_exchanges WHERE app_id = $1", [appId]);
|
|
690
728
|
await sql.query("DELETE FROM hosted_human_codes WHERE app_id = $1", [appId]);
|
|
@@ -793,6 +831,7 @@ export function createSqlStore(database) {
|
|
|
793
831
|
product_name = $8, logo_url = $9, accent_color = $10, signup_mode = $11, allow_without_personal_org = $12,
|
|
794
832
|
waitlist_questions = COALESCE($13::text[], waitlist_questions), signup_audience = $14, signup_sso_providers = $15::text[], signup_organization = $16,
|
|
795
833
|
managed_sign_in = COALESCE($17::boolean, managed_sign_in), email_code_sign_in = COALESCE($18::boolean, email_code_sign_in),
|
|
834
|
+
authix_mode = COALESCE($27::boolean, authix_mode),
|
|
796
835
|
auth_copy = COALESCE($19::jsonb, auth_copy), directory_model = COALESCE($20, directory_model),
|
|
797
836
|
directory_labels = COALESCE($21::jsonb, directory_labels), onboarding = onboarding || $22::jsonb,
|
|
798
837
|
waitlist_question_definitions = CASE WHEN $23::boolean THEN $24::jsonb ELSE waitlist_question_definitions END,
|
|
@@ -806,6 +845,7 @@ export function createSqlStore(database) {
|
|
|
806
845
|
row.directoryModel ?? null, row.directoryLabels === undefined ? null : JSON.stringify(row.directoryLabels), JSON.stringify(row.onboarding ?? {}),
|
|
807
846
|
row.waitlistQuestionDefinitions !== undefined || row.waitlistQuestions !== undefined,
|
|
808
847
|
row.waitlistQuestionDefinitions == null ? null : JSON.stringify(row.waitlistQuestionDefinitions), row.waitlistQuestionLayout ?? null, row.orgId,
|
|
848
|
+
row.authixMode ?? null,
|
|
809
849
|
]);
|
|
810
850
|
if (!updated.length)
|
|
811
851
|
throw new StoreError("not_found", "Application not found.");
|
|
@@ -1258,6 +1298,141 @@ export function createSqlStore(database) {
|
|
|
1258
1298
|
await sql.query("UPDATE service_credentials SET revoked_at = $2::timestamptz WHERE id = $1 AND revoked_at IS NULL", [id, asTime(at)]);
|
|
1259
1299
|
return first(sql, "SELECT * FROM service_credentials WHERE id = $1", [id], serviceCredentialOf);
|
|
1260
1300
|
}),
|
|
1301
|
+
getStationRegistration: (orgId) => tx((sql) => first(sql, "SELECT * FROM station_registration WHERE org_id = $1", [orgId], stationRegistrationOf)),
|
|
1302
|
+
saveStationRegistration: (change) => tx(async (sql) => {
|
|
1303
|
+
const next = change.registration;
|
|
1304
|
+
if (!Number.isInteger(next.generation) || next.generation < 0)
|
|
1305
|
+
throw new StoreError("conflict", "Invalid station registration.");
|
|
1306
|
+
// The Team's row is the lock: a first change has no settings row to lock yet, and two of them must not both win.
|
|
1307
|
+
await sql.query("SELECT id FROM orgs WHERE id = $1 FOR NO KEY UPDATE", [next.orgId]);
|
|
1308
|
+
const current = await first(sql, "SELECT * FROM station_registration WHERE org_id = $1", [next.orgId], stationRegistrationOf);
|
|
1309
|
+
if ((current?.enabled ?? false) !== change.expected.enabled || (current?.generation ?? 0) !== change.expected.generation)
|
|
1310
|
+
return { saved: false, removed: 0 };
|
|
1311
|
+
await sql.query(`INSERT INTO station_registration (org_id, enabled, enabled_at, secret_enc, secret_hash, generation, updated_at)
|
|
1312
|
+
VALUES ($1, $2, $3::timestamptz, $4, $5, $6, $7::timestamptz)
|
|
1313
|
+
ON CONFLICT (org_id) DO UPDATE SET enabled = EXCLUDED.enabled, enabled_at = EXCLUDED.enabled_at, secret_enc = EXCLUDED.secret_enc,
|
|
1314
|
+
secret_hash = EXCLUDED.secret_hash, generation = EXCLUDED.generation, updated_at = EXCLUDED.updated_at`, [next.orgId, next.enabled, asTimeOrNull(next.enabledAt), next.secretEnc, next.secretHash, next.generation, asTime(next.updatedAt)]);
|
|
1315
|
+
let removed = 0;
|
|
1316
|
+
if (change.removeOlder) {
|
|
1317
|
+
removed = (await rows(sql, `UPDATE stations SET removed_at = $2::timestamptz, removed_by = $3, removed_reason = 'secret-regenerated'
|
|
1318
|
+
WHERE org_id = $1 AND removed_at IS NULL AND generation < $4 RETURNING id`, [next.orgId, asTime(change.removeOlder.at), change.removeOlder.removedBy, next.generation])).length;
|
|
1319
|
+
}
|
|
1320
|
+
return { saved: true, removed };
|
|
1321
|
+
}),
|
|
1322
|
+
listStations: (orgId) => tx(async (sql) => (await rows(sql, "SELECT * FROM stations WHERE org_id = $1 AND removed_at IS NULL ORDER BY registered_at DESC, id DESC", [orgId])).map(stationOf)),
|
|
1323
|
+
getStation: (orgId, id) => tx((sql) => first(sql, "SELECT * FROM stations WHERE org_id = $1 AND id = $2", [orgId, id], stationOf)),
|
|
1324
|
+
findStationByFingerprint: (orgId, fingerprint) => tx((sql) => first(sql, "SELECT * FROM stations WHERE org_id = $1 AND fingerprint = $2", [orgId, fingerprint], stationOf)),
|
|
1325
|
+
registerStation: (input) => tx(async (sql) => {
|
|
1326
|
+
const wanted = input.station;
|
|
1327
|
+
if (wanted.keyType !== "ssh-ed25519" || wanted.name !== wanted.name.toLowerCase())
|
|
1328
|
+
throw new StoreError("conflict", "Invalid station.");
|
|
1329
|
+
const stamp = asTime(input.at);
|
|
1330
|
+
// One registration at a time per Team, so two requests cannot both pass the name rule or the limit.
|
|
1331
|
+
if (!(await rows(sql, "SELECT id FROM orgs WHERE id = $1 FOR NO KEY UPDATE", [wanted.orgId])).length)
|
|
1332
|
+
throw new StoreError("conflict", "Organization is missing.");
|
|
1333
|
+
// The settings are read again under that lock, the lock a regenerate or a turn-off also takes: a secret that was
|
|
1334
|
+
// replaced or switched off after the caller checked it must not register anyone, and nothing has been written yet.
|
|
1335
|
+
const settings = await first(sql, "SELECT * FROM station_registration WHERE org_id = $1", [wanted.orgId], stationRegistrationOf);
|
|
1336
|
+
if (!settings?.enabled || settings.generation !== input.expected.generation) {
|
|
1337
|
+
return { status: "registration_changed", enabled: settings?.enabled === true };
|
|
1338
|
+
}
|
|
1339
|
+
await sql.query("DELETE FROM request_nonces WHERE expires_at <= $1::timestamptz", [stamp]);
|
|
1340
|
+
const replayed = await rows(sql, "SELECT nonce FROM request_nonces WHERE fingerprint = $1 AND nonce = $2", [input.nonce.fingerprint, input.nonce.nonce]);
|
|
1341
|
+
if (replayed.length)
|
|
1342
|
+
return { status: "replayed" };
|
|
1343
|
+
const existing = await first(sql, "SELECT * FROM stations WHERE org_id = $1 AND fingerprint = $2 FOR UPDATE", [wanted.orgId, wanted.fingerprint], stationOf);
|
|
1344
|
+
const [counted] = await rows(sql, "SELECT count(*)::int AS n FROM stations WHERE org_id = $1 AND removed_at IS NULL", [wanted.orgId]);
|
|
1345
|
+
const taken = await rows(sql, "SELECT id FROM stations WHERE org_id = $1 AND name = $2 AND removed_at IS NULL AND id <> $3", [wanted.orgId, wanted.name, existing?.id ?? ""]);
|
|
1346
|
+
const plan = planStationRegistration({ existing, nameTaken: taken.length > 0, activeCount: Number(counted?.n ?? 0), maxActive: input.maxActive });
|
|
1347
|
+
if (plan.action === "key_removed" || plan.action === "name_taken" || plan.action === "limit")
|
|
1348
|
+
return { status: plan.action };
|
|
1349
|
+
await sql.query("INSERT INTO request_nonces (fingerprint, nonce, expires_at) VALUES ($1, $2, $3::timestamptz)", [input.nonce.fingerprint, input.nonce.nonce, asTime(input.nonce.expiresAt)]);
|
|
1350
|
+
if (plan.action === "create") {
|
|
1351
|
+
const created = await first(sql, `INSERT INTO stations (id, org_id, name, key_type, public_key, fingerprint, generation, registered_at, last_seen_at)
|
|
1352
|
+
VALUES ($1, $2, $3, $4, $5, $6, $7, $8::timestamptz, $9::timestamptz) RETURNING *`, [wanted.id, wanted.orgId, wanted.name, wanted.keyType, wanted.publicKey, wanted.fingerprint, wanted.generation, asTime(wanted.registeredAt), asTime(wanted.lastSeenAt)], stationOf);
|
|
1353
|
+
return { status: "created", station: created };
|
|
1354
|
+
}
|
|
1355
|
+
const row = existing;
|
|
1356
|
+
const saved = await first(sql, plan.action === "update"
|
|
1357
|
+
? "UPDATE stations SET name = $2, generation = $3, last_seen_at = $4::timestamptz WHERE id = $1 RETURNING *"
|
|
1358
|
+
: `UPDATE stations SET name = $2, generation = $3, last_seen_at = $4::timestamptz, registered_at = $5::timestamptz,
|
|
1359
|
+
removed_at = NULL, removed_by = NULL, removed_reason = NULL WHERE id = $1 RETURNING *`, plan.action === "update" ? [row.id, wanted.name, wanted.generation, stamp] : [row.id, wanted.name, wanted.generation, stamp, asTime(wanted.registeredAt)], stationOf);
|
|
1360
|
+
return { status: plan.action === "update" ? "updated" : "created", station: saved };
|
|
1361
|
+
}),
|
|
1362
|
+
removeStation: (input) => tx((sql) => first(sql, `UPDATE stations SET removed_at = $3::timestamptz, removed_by = $4, removed_reason = 'removed'
|
|
1363
|
+
WHERE org_id = $1 AND id = $2 AND removed_at IS NULL RETURNING *`, [input.orgId, input.id, asTime(input.at), input.removedBy], stationOf)),
|
|
1364
|
+
touchStation: (orgId, id, at, minIntervalMs) => tx(async (sql) => {
|
|
1365
|
+
await sql.query(`UPDATE stations SET last_seen_at = $3::timestamptz WHERE org_id = $1 AND id = $2 AND removed_at IS NULL
|
|
1366
|
+
AND last_seen_at <= $3::timestamptz - ($4::int * interval '1 millisecond')`, [orgId, id, asTime(at), Math.max(0, Math.floor(minIntervalMs))]);
|
|
1367
|
+
}),
|
|
1368
|
+
takeRequestNonce: (nonce, at) => tx(async (sql) => {
|
|
1369
|
+
await sql.query("DELETE FROM request_nonces WHERE expires_at <= $1::timestamptz", [asTime(at)]);
|
|
1370
|
+
const stored = await rows(sql, "INSERT INTO request_nonces (fingerprint, nonce, expires_at) VALUES ($1, $2, $3::timestamptz) ON CONFLICT DO NOTHING RETURNING nonce", [nonce.fingerprint, nonce.nonce, asTime(nonce.expiresAt)]);
|
|
1371
|
+
return stored.length === 1;
|
|
1372
|
+
}),
|
|
1373
|
+
listStationsByIds: (orgId, ids) => tx(async (sql) => (await rows(sql, "SELECT * FROM stations WHERE org_id = $1 AND id = ANY($2::text[])", [orgId, ids])).map(stationOf)),
|
|
1374
|
+
getSafeShare: (appId) => tx((sql) => first(sql, "SELECT * FROM app_safe_shares WHERE app_id = $1", [appId], safeShareOf)),
|
|
1375
|
+
defineSafeShare: (input) => tx(async (sql) => {
|
|
1376
|
+
if (!(await activeApplicationIn(sql, input.appId, input.orgId)))
|
|
1377
|
+
return { status: "not_found" };
|
|
1378
|
+
// A new row, or a removed one switched back on. A row that is already on is left exactly as it is.
|
|
1379
|
+
const written = await first(sql, `INSERT INTO app_safe_shares (app_id, org_id, defined_at, defined_by, active)
|
|
1380
|
+
VALUES ($1, $2, $3::timestamptz, $4, true)
|
|
1381
|
+
ON CONFLICT (app_id) DO UPDATE SET active = true, defined_at = EXCLUDED.defined_at, defined_by = EXCLUDED.defined_by
|
|
1382
|
+
WHERE app_safe_shares.active = false
|
|
1383
|
+
RETURNING *`, [input.appId, input.orgId, asTime(input.at), input.definedBy], safeShareOf);
|
|
1384
|
+
if (!written) {
|
|
1385
|
+
const current = await first(sql, "SELECT * FROM app_safe_shares WHERE app_id = $1", [input.appId], safeShareOf);
|
|
1386
|
+
return { status: "already", share: current };
|
|
1387
|
+
}
|
|
1388
|
+
const [counted] = await rows(sql, "SELECT count(*)::int AS n FROM safe_share_documents WHERE app_id = $1", [input.appId]);
|
|
1389
|
+
return { status: "defined", share: written, restored: Number(counted?.n ?? 0) };
|
|
1390
|
+
}),
|
|
1391
|
+
removeSafeShare: (input) => tx(async (sql) => {
|
|
1392
|
+
if (!(await activeApplicationIn(sql, input.appId, input.orgId)))
|
|
1393
|
+
return null;
|
|
1394
|
+
return first(sql, "UPDATE app_safe_shares SET active = false WHERE app_id = $1 AND org_id = $2 AND active RETURNING *", [input.appId, input.orgId], safeShareOf);
|
|
1395
|
+
}),
|
|
1396
|
+
listSafeShareDocuments: (appId) => tx(async (sql) => (await rows(sql, `SELECT app_id, name, kind, version, bytes, sha256, pushed_by_kind, pushed_by_id, pushed_by_name,
|
|
1397
|
+
pushed_at, previous_version IS NOT NULL AS has_previous FROM safe_share_documents WHERE app_id = $1 ORDER BY name COLLATE "C"`, [appId])).map(safeShareSummaryOf)),
|
|
1398
|
+
getSafeShareDocuments: (appId, names) => tx(async (sql) => (await rows(sql, 'SELECT * FROM safe_share_documents WHERE app_id = $1 AND name = ANY($2::text[]) ORDER BY name COLLATE "C"', [appId, names])).map(safeShareDocumentOf)),
|
|
1399
|
+
pushSafeShareDocument: (input) => tx(async (sql) => {
|
|
1400
|
+
const problem = safeShareDocumentProblem(input);
|
|
1401
|
+
if (problem)
|
|
1402
|
+
throw new StoreError("conflict", problem);
|
|
1403
|
+
const stamp = asTime(input.pushedAt);
|
|
1404
|
+
await sql.query("DELETE FROM request_nonces WHERE expires_at <= $1::timestamptz", [stamp]);
|
|
1405
|
+
// The share's row is the lock: pushes of one share go one at a time, so two of them cannot both take the last place.
|
|
1406
|
+
const share = (await activeApplicationIn(sql, input.appId, input.orgId))
|
|
1407
|
+
? (await rows(sql, "SELECT active FROM app_safe_shares WHERE app_id = $1 AND org_id = $2 FOR UPDATE", [input.appId, input.orgId]))[0]
|
|
1408
|
+
: undefined;
|
|
1409
|
+
const replayed = input.nonce
|
|
1410
|
+
? (await rows(sql, "SELECT nonce FROM request_nonces WHERE fingerprint = $1 AND nonce = $2", [input.nonce.fingerprint, input.nonce.nonce])).length > 0
|
|
1411
|
+
: false;
|
|
1412
|
+
const existing = await rows(sql, "SELECT name FROM safe_share_documents WHERE app_id = $1 AND name = $2", [input.appId, input.name]);
|
|
1413
|
+
const [counted] = await rows(sql, "SELECT count(*)::int AS n FROM safe_share_documents WHERE app_id = $1", [input.appId]);
|
|
1414
|
+
const plan = planSafeSharePush({
|
|
1415
|
+
active: share?.active === true, replayed, exists: existing.length > 0, documentCount: Number(counted?.n ?? 0), maxDocuments: input.maxDocuments,
|
|
1416
|
+
});
|
|
1417
|
+
if (plan.action !== "write")
|
|
1418
|
+
return { status: plan.action };
|
|
1419
|
+
if (input.nonce) {
|
|
1420
|
+
// Another share can take the same nonce at the same moment: whoever inserts it first wins, before anything is written.
|
|
1421
|
+
const stored = await rows(sql, "INSERT INTO request_nonces (fingerprint, nonce, expires_at) VALUES ($1, $2, $3::timestamptz) ON CONFLICT DO NOTHING RETURNING nonce", [input.nonce.fingerprint, input.nonce.nonce, asTime(input.nonce.expiresAt)]);
|
|
1422
|
+
if (stored.length !== 1)
|
|
1423
|
+
return { status: "replayed" };
|
|
1424
|
+
}
|
|
1425
|
+
const written = await first(sql, `INSERT INTO safe_share_documents (app_id, name, kind, content, bytes, sha256, version, pushed_by_kind, pushed_by_id, pushed_by_name, pushed_at)
|
|
1426
|
+
VALUES ($1, $2, $3, $4, $5, $6, 1, $7, $8, $9, $10::timestamptz)
|
|
1427
|
+
ON CONFLICT (app_id, name) DO UPDATE SET
|
|
1428
|
+
previous_version = safe_share_documents.version, previous_content = safe_share_documents.content, previous_sha256 = safe_share_documents.sha256,
|
|
1429
|
+
previous_pushed_by_kind = safe_share_documents.pushed_by_kind, previous_pushed_by_id = safe_share_documents.pushed_by_id,
|
|
1430
|
+
previous_pushed_by_name = safe_share_documents.pushed_by_name, previous_pushed_at = safe_share_documents.pushed_at,
|
|
1431
|
+
version = safe_share_documents.version + 1, kind = EXCLUDED.kind, content = EXCLUDED.content, bytes = EXCLUDED.bytes, sha256 = EXCLUDED.sha256,
|
|
1432
|
+
pushed_by_kind = EXCLUDED.pushed_by_kind, pushed_by_id = EXCLUDED.pushed_by_id, pushed_by_name = EXCLUDED.pushed_by_name, pushed_at = EXCLUDED.pushed_at
|
|
1433
|
+
RETURNING *`, [input.appId, input.name, input.kind, input.content, input.bytes, input.sha256, input.pushedBy.kind, input.pushedBy.id, input.pushedBy.name, stamp], safeShareDocumentOf);
|
|
1434
|
+
return { status: "pushed", document: written };
|
|
1435
|
+
}),
|
|
1261
1436
|
insertPrincipal: (row) => tx(async (sql) => {
|
|
1262
1437
|
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)]);
|
|
1263
1438
|
}),
|
|
@@ -1346,6 +1521,7 @@ export function createSqlStore(database) {
|
|
|
1346
1521
|
throw new StoreError("not_found", "Route not found.");
|
|
1347
1522
|
}),
|
|
1348
1523
|
...createSqlDirectory(tx),
|
|
1524
|
+
...createSqlDelegation(tx),
|
|
1349
1525
|
...createSqlNotificationWebhookJobs(tx),
|
|
1350
1526
|
ping: () => tx(async (sql) => { await sql.query("SELECT 1"); }),
|
|
1351
1527
|
purgeExpired(at) {
|
|
@@ -1362,6 +1538,7 @@ export function createSqlStore(database) {
|
|
|
1362
1538
|
await sql.query("DELETE FROM hosted_email_codes WHERE expires_at <= $1::timestamptz AND created_at <= $2::timestamptz", [stamp, new Date(Date.parse(stamp) - hostedEmailCodePolicy.sendWindowMs).toISOString()]);
|
|
1363
1539
|
await sql.query("DELETE FROM hosted_sso_profiles WHERE expires_at <= $1::timestamptz", [stamp]);
|
|
1364
1540
|
await sql.query("DELETE FROM sso_exchanges WHERE expires_at <= $1::timestamptz", [stamp]);
|
|
1541
|
+
await sql.query("DELETE FROM request_nonces WHERE expires_at <= $1::timestamptz", [stamp]);
|
|
1365
1542
|
});
|
|
1366
1543
|
},
|
|
1367
1544
|
};
|