@x12i/keyrox-store-pg 0.0.0-stage → 0.1.0
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 +26 -0
- package/dist/database.js.map +1 -0
- package/dist/directory-sql.d.ts +6 -0
- package/dist/directory-sql.d.ts.map +1 -0
- package/dist/directory-sql.js +274 -0
- package/dist/directory-sql.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 +28 -0
- package/dist/migrate.js.map +1 -0
- package/dist/rows.d.ts +36 -0
- package/dist/rows.d.ts.map +1 -0
- package/dist/rows.js +276 -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 +632 -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/package.json +36 -4
- package/README.md +0 -3
|
@@ -0,0 +1,632 @@
|
|
|
1
|
+
import { asTime, asTimeOrNull, decideLongLived, effectiveActions, isExpired, StoreError, } from "@x12i/keyrox-store";
|
|
2
|
+
import { createSqlDirectory } from "./directory-sql.js";
|
|
3
|
+
import { agentOf, applicationOf, appTokenOf, environmentOf, auditOf, authorizationOf, challengeOf, clientOf, deniedOf, grantOf, gatewayRouteOf, idempotencyOf, inviteOf, longTokenOf, membershipOf, orgOf, principalOf, providerOf, refreshOf, roleOf, serviceCredentialOf, sessionOf, signInOf, ssoExchangeOf, ssoLoginOf, trustOf, userOf, workloadCredentialOf, audienceOf, assignmentOf, } from "./rows.js";
|
|
4
|
+
async function rows(sql, text, values = []) {
|
|
5
|
+
const result = await sql.query(text, values);
|
|
6
|
+
return result.rows;
|
|
7
|
+
}
|
|
8
|
+
async function first(sql, text, values, map) {
|
|
9
|
+
const found = await rows(sql, text, values);
|
|
10
|
+
return found[0] ? map(found[0]) : null;
|
|
11
|
+
}
|
|
12
|
+
async function revokeGrant(sql, id, at) {
|
|
13
|
+
const grant = await first(sql, "SELECT * FROM delegation_grants WHERE id = $1 FOR UPDATE", [id], grantOf);
|
|
14
|
+
if (!grant)
|
|
15
|
+
return null;
|
|
16
|
+
const changed = grant.revokedAt === null;
|
|
17
|
+
if (changed) {
|
|
18
|
+
grant.revokedAt = at;
|
|
19
|
+
await sql.query("UPDATE delegation_grants SET revoked_at = $2::timestamptz WHERE id = $1", [id, at]);
|
|
20
|
+
}
|
|
21
|
+
await sql.query("UPDATE long_lived_tokens SET revoked_at = $2::timestamptz WHERE grant_id = $1 AND revoked_at IS NULL", [id, grant.revokedAt]);
|
|
22
|
+
await sql.query("UPDATE refresh_tokens SET revoked_at = $2::timestamptz WHERE grant_id = $1 AND revoked_at IS NULL", [id, grant.revokedAt]);
|
|
23
|
+
return { grant, changed };
|
|
24
|
+
}
|
|
25
|
+
export function createSqlStore(database) {
|
|
26
|
+
const tx = (run) => database.transaction(run);
|
|
27
|
+
const store = {
|
|
28
|
+
signup(input) {
|
|
29
|
+
return tx(async (sql) => {
|
|
30
|
+
const user = { ...input.user, emailVerifiedAt: asTimeOrNull(input.user.emailVerifiedAt), disabledAt: asTimeOrNull(input.user.disabledAt), createdAt: asTime(input.user.createdAt) };
|
|
31
|
+
const org = { ...input.org, createdAt: asTime(input.org.createdAt) };
|
|
32
|
+
const membership = { ...input.membership, createdAt: asTime(input.membership.createdAt) };
|
|
33
|
+
if (membership.userId !== user.id || membership.orgId !== org.id || membership.role !== "owner") {
|
|
34
|
+
throw new StoreError("conflict", "Signup requires the new organization and its owner membership.");
|
|
35
|
+
}
|
|
36
|
+
const email = await rows(sql, "SELECT id FROM users WHERE lower(email) = lower($1)", [user.email]);
|
|
37
|
+
if (email.length)
|
|
38
|
+
throw new StoreError("duplicate_email", "Email already exists.");
|
|
39
|
+
const slug = await rows(sql, "SELECT id FROM orgs WHERE slug = $1", [org.slug]);
|
|
40
|
+
if (slug.length)
|
|
41
|
+
throw new StoreError("duplicate_slug", "Slug already exists.");
|
|
42
|
+
await sql.query(`INSERT INTO users (id, email, password_hash, display_name, email_verified_at, disabled_at, created_at, last_org_id)
|
|
43
|
+
VALUES ($1, $2, $3, $4, $5::timestamptz, $6::timestamptz, $7::timestamptz, $8)`, [user.id, user.email, user.passwordHash, user.displayName, user.emailVerifiedAt, user.disabledAt, user.createdAt, user.lastOrgId ?? null]);
|
|
44
|
+
await sql.query(`INSERT INTO orgs (id, slug, name, personal, allow_never_expire, allow_device_flow, grant_max_days, policy_version, created_at)
|
|
45
|
+
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9::timestamptz)`, [org.id, org.slug, org.name, org.personal, org.policy.allowNeverExpire, org.policy.allowDeviceFlow, org.policy.grantMaxDays, org.policy.version, org.createdAt]);
|
|
46
|
+
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]);
|
|
47
|
+
});
|
|
48
|
+
},
|
|
49
|
+
createOrg(input) {
|
|
50
|
+
return tx(async (sql) => {
|
|
51
|
+
const org = { ...input.org, createdAt: asTime(input.org.createdAt) };
|
|
52
|
+
const membership = { ...input.membership, createdAt: asTime(input.membership.createdAt) };
|
|
53
|
+
if (membership.orgId !== org.id || membership.role !== "owner")
|
|
54
|
+
throw new StoreError("conflict", "A new organization needs an owner membership.");
|
|
55
|
+
await sql.query("SELECT id FROM users WHERE id = $1 FOR UPDATE", [membership.userId]);
|
|
56
|
+
const owner = await rows(sql, "SELECT id FROM users WHERE id = $1", [membership.userId]);
|
|
57
|
+
if (!owner.length)
|
|
58
|
+
throw new StoreError("conflict", "User is missing.");
|
|
59
|
+
const slug = await rows(sql, "SELECT id FROM orgs WHERE slug = $1", [org.slug]);
|
|
60
|
+
if (slug.length)
|
|
61
|
+
throw new StoreError("duplicate_slug", "Slug already exists.");
|
|
62
|
+
await sql.query(`INSERT INTO orgs (id, slug, name, personal, allow_never_expire, allow_device_flow, grant_max_days, policy_version, created_at)
|
|
63
|
+
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]);
|
|
64
|
+
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]);
|
|
65
|
+
});
|
|
66
|
+
},
|
|
67
|
+
getUser: (id) => tx((sql) => first(sql, "SELECT * FROM users WHERE id = $1", [id], userOf)),
|
|
68
|
+
findUserByEmail: (email) => tx((sql) => first(sql, "SELECT * FROM users WHERE lower(email) = lower($1)", [email], userOf)),
|
|
69
|
+
updateUser(user) {
|
|
70
|
+
return tx(async (sql) => {
|
|
71
|
+
const next = { ...user, emailVerifiedAt: asTimeOrNull(user.emailVerifiedAt), disabledAt: asTimeOrNull(user.disabledAt), createdAt: asTime(user.createdAt) };
|
|
72
|
+
const updated = await rows(sql, `UPDATE users SET email = $2, password_hash = $3, display_name = $4, email_verified_at = $5::timestamptz,
|
|
73
|
+
disabled_at = $6::timestamptz, created_at = $7::timestamptz, last_org_id = $8 WHERE id = $1 RETURNING id`, [next.id, next.email, next.passwordHash, next.displayName, next.emailVerifiedAt, next.disabledAt, next.createdAt, next.lastOrgId ?? null]);
|
|
74
|
+
if (!updated.length)
|
|
75
|
+
throw new StoreError("not_found", "User not found.");
|
|
76
|
+
});
|
|
77
|
+
},
|
|
78
|
+
getOrg: (id) => tx((sql) => first(sql, "SELECT * FROM orgs WHERE id = $1", [id], orgOf)),
|
|
79
|
+
findOrgBySlug: (slug) => tx((sql) => first(sql, "SELECT * FROM orgs WHERE slug = $1", [slug], orgOf)),
|
|
80
|
+
updateOrg(org) {
|
|
81
|
+
return tx(async (sql) => {
|
|
82
|
+
const next = { ...org, createdAt: asTime(org.createdAt) };
|
|
83
|
+
const updated = await rows(sql, `UPDATE orgs SET slug = $2, name = $3, personal = $4, allow_never_expire = $5, allow_device_flow = $6,
|
|
84
|
+
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]);
|
|
85
|
+
if (!updated.length)
|
|
86
|
+
throw new StoreError("not_found", "Organization not found.");
|
|
87
|
+
});
|
|
88
|
+
},
|
|
89
|
+
findMembership: (userId, orgId) => tx((sql) => first(sql, "SELECT * FROM memberships WHERE user_id = $1 AND org_id = $2", [userId, orgId], membershipOf)),
|
|
90
|
+
listMembershipsByUser: (userId) => tx(async (sql) => (await rows(sql, "SELECT * FROM memberships WHERE user_id = $1 ORDER BY created_at, id", [userId])).map(membershipOf)),
|
|
91
|
+
listMembershipsByOrg: (orgId) => tx(async (sql) => (await rows(sql, "SELECT * FROM memberships WHERE org_id = $1 ORDER BY created_at, id", [orgId])).map(membershipOf)),
|
|
92
|
+
saveMembership(membership) {
|
|
93
|
+
return tx(async (sql) => {
|
|
94
|
+
const next = { ...membership, createdAt: asTime(membership.createdAt) };
|
|
95
|
+
const locked = await rows(sql, "SELECT * FROM memberships WHERE org_id = $1 ORDER BY id FOR UPDATE", [next.orgId]);
|
|
96
|
+
const existing = locked.map(membershipOf).find((row) => row.id === next.id && row.userId === next.userId);
|
|
97
|
+
if (!existing)
|
|
98
|
+
throw new StoreError("not_found", "Member not found.");
|
|
99
|
+
if (existing.role === "owner" && next.role !== "owner" && locked.map(membershipOf).filter((row) => row.role === "owner").length < 2) {
|
|
100
|
+
throw new StoreError("last_owner", "An organization must keep an owner.");
|
|
101
|
+
}
|
|
102
|
+
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]);
|
|
103
|
+
});
|
|
104
|
+
},
|
|
105
|
+
removeMembership(input) {
|
|
106
|
+
return tx(async (sql) => {
|
|
107
|
+
const at = asTime(input.at);
|
|
108
|
+
const account = await rows(sql, "SELECT id FROM users WHERE id = $1 FOR UPDATE", [input.userId]);
|
|
109
|
+
if (!account.length)
|
|
110
|
+
throw new StoreError("not_found", "Member not found.");
|
|
111
|
+
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);
|
|
112
|
+
const existing = owned.find((row) => row.userId === input.userId && row.orgId === input.orgId);
|
|
113
|
+
if (!existing)
|
|
114
|
+
throw new StoreError("not_found", "Member not found.");
|
|
115
|
+
if (owned.filter((row) => row.userId === input.userId).length < 2)
|
|
116
|
+
throw new StoreError("last_membership", "An account must belong to at least one organization.");
|
|
117
|
+
if (existing.role === "owner" && owned.filter((row) => row.orgId === input.orgId && row.role === "owner").length < 2) {
|
|
118
|
+
throw new StoreError("last_owner", "An organization must keep an owner.");
|
|
119
|
+
}
|
|
120
|
+
await sql.query("DELETE FROM memberships WHERE id = $1", [existing.id]);
|
|
121
|
+
const grants = await rows(sql, "SELECT id FROM delegation_grants WHERE user_id = $1 AND org_id = $2", [input.userId, input.orgId]);
|
|
122
|
+
for (const grant of grants)
|
|
123
|
+
await revokeGrant(sql, String(grant.id), at);
|
|
124
|
+
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]);
|
|
125
|
+
});
|
|
126
|
+
},
|
|
127
|
+
insertChallenge(row) {
|
|
128
|
+
return tx(async (sql) => {
|
|
129
|
+
await sql.query(`INSERT INTO email_challenges (id, user_id, purpose, token_hash, expires_at, used_at, created_at)
|
|
130
|
+
VALUES ($1, $2, $3, $4, $5::timestamptz, $6::timestamptz, $7::timestamptz)`, [row.id, row.userId, row.purpose, row.tokenHash, asTime(row.expiresAt), asTimeOrNull(row.usedAt), asTime(row.createdAt)]);
|
|
131
|
+
});
|
|
132
|
+
},
|
|
133
|
+
verifyEmail(tokenHash, at) {
|
|
134
|
+
return tx(async (sql) => {
|
|
135
|
+
const stamp = asTime(at);
|
|
136
|
+
const mapped = await first(sql, "SELECT * FROM email_challenges WHERE token_hash = $1 AND purpose = 'verify' FOR UPDATE", [tokenHash], challengeOf);
|
|
137
|
+
if (!mapped || mapped.usedAt || isExpired(mapped.expiresAt, stamp))
|
|
138
|
+
throw new StoreError("challenge_invalid", "Verification link is no longer valid.");
|
|
139
|
+
const account = await first(sql, "SELECT * FROM users WHERE id = $1 FOR UPDATE", [mapped.userId], userOf);
|
|
140
|
+
if (!account)
|
|
141
|
+
throw new StoreError("challenge_invalid", "Verification link is no longer valid.");
|
|
142
|
+
await sql.query("UPDATE users SET email_verified_at = $2::timestamptz WHERE id = $1", [account.id, stamp]);
|
|
143
|
+
await sql.query("UPDATE email_challenges SET used_at = $2::timestamptz WHERE id = $1", [mapped.id, stamp]);
|
|
144
|
+
return { ...account, emailVerifiedAt: stamp };
|
|
145
|
+
});
|
|
146
|
+
},
|
|
147
|
+
resetPassword(input) {
|
|
148
|
+
return tx(async (sql) => {
|
|
149
|
+
const stamp = asTime(input.at);
|
|
150
|
+
const mapped = await first(sql, "SELECT * FROM email_challenges WHERE token_hash = $1 AND purpose = 'reset' FOR UPDATE", [input.tokenHash], challengeOf);
|
|
151
|
+
if (!mapped || mapped.usedAt || isExpired(mapped.expiresAt, stamp))
|
|
152
|
+
throw new StoreError("challenge_invalid", "Reset link is no longer valid.");
|
|
153
|
+
const account = await first(sql, "SELECT * FROM users WHERE id = $1 FOR UPDATE", [mapped.userId], userOf);
|
|
154
|
+
if (!account)
|
|
155
|
+
throw new StoreError("challenge_invalid", "Reset link is no longer valid.");
|
|
156
|
+
const verified = account.emailVerifiedAt ?? stamp;
|
|
157
|
+
await sql.query("UPDATE users SET password_hash = $2, email_verified_at = $3::timestamptz WHERE id = $1", [account.id, input.passwordHash, verified]);
|
|
158
|
+
await sql.query("UPDATE email_challenges SET used_at = $2::timestamptz WHERE id = $1", [mapped.id, stamp]);
|
|
159
|
+
await sql.query("DELETE FROM sessions WHERE user_id = $1", [account.id]);
|
|
160
|
+
return { ...account, passwordHash: input.passwordHash, emailVerifiedAt: verified };
|
|
161
|
+
});
|
|
162
|
+
},
|
|
163
|
+
insertInvite(row) {
|
|
164
|
+
return tx(async (sql) => {
|
|
165
|
+
await sql.query(`INSERT INTO invites (id, org_id, email, role, actions, token_hash, invited_by, expires_at, accepted_at, created_at, production_access)
|
|
166
|
+
VALUES ($1, $2, $3, $4, $5::text[], $6, $7, $8::timestamptz, $9::timestamptz, $10::timestamptz, $11)`, [row.id, row.orgId, row.email, row.role, row.actions, row.tokenHash, row.invitedBy, asTime(row.expiresAt), asTimeOrNull(row.acceptedAt), asTime(row.createdAt), row.productionAccess === true]);
|
|
167
|
+
});
|
|
168
|
+
},
|
|
169
|
+
acceptInvite(input) {
|
|
170
|
+
return tx(async (sql) => {
|
|
171
|
+
const at = asTime(input.at);
|
|
172
|
+
await sql.query("SELECT id FROM users WHERE id = $1 FOR UPDATE", [input.userId]);
|
|
173
|
+
const invite = await first(sql, "SELECT * FROM invites WHERE token_hash = $1 FOR UPDATE", [input.tokenHash], inviteOf);
|
|
174
|
+
if (!invite || invite.acceptedAt || isExpired(invite.expiresAt, at))
|
|
175
|
+
throw new StoreError("invite_invalid", "Invite is no longer valid.");
|
|
176
|
+
const account = await first(sql, "SELECT * FROM users WHERE id = $1", [input.userId], userOf);
|
|
177
|
+
if (!account)
|
|
178
|
+
throw new StoreError("not_found", "User not found.");
|
|
179
|
+
if (invite.email.toLowerCase() !== input.email.toLowerCase() || invite.email.toLowerCase() !== account.email.toLowerCase()) {
|
|
180
|
+
throw new StoreError("invite_email", "Invite email does not match the account.");
|
|
181
|
+
}
|
|
182
|
+
const existing = await rows(sql, "SELECT id FROM memberships WHERE user_id = $1 AND org_id = $2", [account.id, invite.orgId]);
|
|
183
|
+
if (!existing.length) {
|
|
184
|
+
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]);
|
|
185
|
+
}
|
|
186
|
+
await sql.query("UPDATE invites SET accepted_at = $2::timestamptz WHERE id = $1", [invite.id, at]);
|
|
187
|
+
return { ...invite, acceptedAt: at };
|
|
188
|
+
});
|
|
189
|
+
},
|
|
190
|
+
insertSession(row) {
|
|
191
|
+
return tx(async (sql) => {
|
|
192
|
+
await sql.query(`INSERT INTO sessions (id, user_id, org_id, secret_hash, csrf, expires_at, created_at)
|
|
193
|
+
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)]);
|
|
194
|
+
});
|
|
195
|
+
},
|
|
196
|
+
findSessionByHash: (secretHash) => tx((sql) => first(sql, "SELECT * FROM sessions WHERE secret_hash = $1", [secretHash], sessionOf)),
|
|
197
|
+
updateSession(session) {
|
|
198
|
+
return tx(async (sql) => {
|
|
199
|
+
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
|
|
200
|
+
WHERE id = $1 RETURNING id`, [session.id, session.userId, session.orgId, session.secretHash, session.csrf, asTime(session.expiresAt), asTime(session.createdAt)]);
|
|
201
|
+
if (!updated.length)
|
|
202
|
+
throw new StoreError("not_found", "Session not found.");
|
|
203
|
+
});
|
|
204
|
+
},
|
|
205
|
+
deleteSession: (id) => tx(async (sql) => { await sql.query("DELETE FROM sessions WHERE id = $1", [id]); }),
|
|
206
|
+
insertClient(row) {
|
|
207
|
+
return tx(async (sql) => {
|
|
208
|
+
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)]);
|
|
209
|
+
});
|
|
210
|
+
},
|
|
211
|
+
getClient: (id) => tx((sql) => first(sql, "SELECT * FROM clients WHERE id = $1", [id], clientOf)),
|
|
212
|
+
insertAgent(row) {
|
|
213
|
+
return tx(async (sql) => {
|
|
214
|
+
await sql.query(`INSERT INTO agents (id, name, client_id, owner_user_id, org_id, suspended_at, created_at)
|
|
215
|
+
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)]);
|
|
216
|
+
});
|
|
217
|
+
},
|
|
218
|
+
getAgent: (id) => tx((sql) => first(sql, "SELECT * FROM agents WHERE id = $1", [id], agentOf)),
|
|
219
|
+
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)),
|
|
220
|
+
listAgentsByOrg: (orgId) => tx(async (sql) => (await rows(sql, "SELECT * FROM agents WHERE org_id = $1 ORDER BY created_at, id", [orgId])).map(agentOf)),
|
|
221
|
+
suspendAgent(id, at) {
|
|
222
|
+
return tx(async (sql) => {
|
|
223
|
+
const stamp = asTime(at);
|
|
224
|
+
const agent = await first(sql, "SELECT * FROM agents WHERE id = $1 FOR UPDATE", [id], agentOf);
|
|
225
|
+
if (!agent)
|
|
226
|
+
return null;
|
|
227
|
+
await sql.query("UPDATE agents SET suspended_at = $2::timestamptz WHERE id = $1", [id, stamp]);
|
|
228
|
+
const grants = await rows(sql, "SELECT id FROM delegation_grants WHERE agent_id = $1", [id]);
|
|
229
|
+
const revoked = [];
|
|
230
|
+
for (const grant of grants) {
|
|
231
|
+
const result = await revokeGrant(sql, String(grant.id), stamp);
|
|
232
|
+
if (result?.changed)
|
|
233
|
+
revoked.push(result.grant);
|
|
234
|
+
}
|
|
235
|
+
return { agent: { ...agent, suspendedAt: stamp }, revoked };
|
|
236
|
+
});
|
|
237
|
+
},
|
|
238
|
+
insertAuthorization(row) { return tx((sql) => insertAuthorization(sql, row)); },
|
|
239
|
+
getAuthorization: (id) => tx((sql) => first(sql, "SELECT * FROM authorization_requests WHERE id = $1", [id], authorizationOf)),
|
|
240
|
+
findAuthorization(filter) {
|
|
241
|
+
return tx((sql) => first(sql, `SELECT * FROM authorization_requests
|
|
242
|
+
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)
|
|
243
|
+
ORDER BY created_at, id LIMIT 1`, [filter.codeHash ?? null, filter.deviceCodeHash ?? null, filter.userCodeHash ?? null], authorizationOf));
|
|
244
|
+
},
|
|
245
|
+
updateAuthorization(row) {
|
|
246
|
+
return tx(async (sql) => {
|
|
247
|
+
const updated = await rows(sql, `UPDATE authorization_requests SET kind = $2, client_id = $3, redirect_uri = $4, code_challenge = $5, audience = $6,
|
|
248
|
+
actions = $7::text[], resources = $8::text[], state = $9, org_id = $10, user_id = $11, status = $12, code_hash = $13, device_code_hash = $14,
|
|
249
|
+
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
|
|
250
|
+
WHERE id = $1 RETURNING id`, [
|
|
251
|
+
row.id, row.kind, row.clientId, row.redirectUri, row.codeChallenge, row.audience, row.actions, row.resources, row.state, row.orgId, row.userId,
|
|
252
|
+
row.status, row.codeHash, row.deviceCodeHash, row.userCodeHash, row.grantId, row.agentId, row.intervalSeconds, asTimeOrNull(row.lastPollAt),
|
|
253
|
+
asTime(row.expiresAt), asTime(row.createdAt),
|
|
254
|
+
]);
|
|
255
|
+
if (!updated.length)
|
|
256
|
+
throw new StoreError("not_found", "Authorization not found.");
|
|
257
|
+
});
|
|
258
|
+
},
|
|
259
|
+
listAuthorizationsByStatus: (status) => tx(async (sql) => (await rows(sql, "SELECT * FROM authorization_requests WHERE status = $1 ORDER BY created_at, id", [status])).map(authorizationOf)),
|
|
260
|
+
insertGrant(row) {
|
|
261
|
+
return tx(async (sql) => {
|
|
262
|
+
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)
|
|
263
|
+
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,
|
|
264
|
+
asTime(row.createdAt), asTime(row.expiresAt), asTimeOrNull(row.revokedAt)]);
|
|
265
|
+
});
|
|
266
|
+
},
|
|
267
|
+
getGrant: (id) => tx((sql) => first(sql, "SELECT * FROM delegation_grants WHERE id = $1", [id], grantOf)),
|
|
268
|
+
updateGrant(row) {
|
|
269
|
+
return tx(async (sql) => {
|
|
270
|
+
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[],
|
|
271
|
+
resources = $8::text[], jkt = $9, approval_request_id = $10, policy_version = $11, created_at = $12::timestamptz, expires_at = $13::timestamptz, revoked_at = $14::timestamptz
|
|
272
|
+
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,
|
|
273
|
+
asTime(row.createdAt), asTime(row.expiresAt), asTimeOrNull(row.revokedAt)]);
|
|
274
|
+
if (!updated.length)
|
|
275
|
+
throw new StoreError("not_found", "Grant not found.");
|
|
276
|
+
});
|
|
277
|
+
},
|
|
278
|
+
listGrants: (filter) => tx(async (sql) => (await rows(sql, `SELECT * FROM delegation_grants
|
|
279
|
+
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)
|
|
280
|
+
ORDER BY created_at, id`, [filter.orgId ?? null, filter.userId ?? null, filter.agentId ?? null])).map(grantOf)),
|
|
281
|
+
revokeGrant: (id, at) => tx((sql) => revokeGrant(sql, id, asTime(at))),
|
|
282
|
+
insertLongToken(row) { return tx((sql) => insertLongToken(sql, row)); },
|
|
283
|
+
getLongToken: (id) => tx((sql) => first(sql, "SELECT * FROM long_lived_tokens WHERE id = $1", [id], longTokenOf)),
|
|
284
|
+
findLongTokenByHash: (hash) => tx((sql) => first(sql, "SELECT * FROM long_lived_tokens WHERE hash = $1", [hash], longTokenOf)),
|
|
285
|
+
updateLongToken(row) {
|
|
286
|
+
return tx(async (sql) => {
|
|
287
|
+
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,
|
|
288
|
+
actions = $9::text[], resources = $10::text[], grant_id = $11, agent_id = $12, expires_at = $13::timestamptz, revoked_at = $14::timestamptz,
|
|
289
|
+
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,
|
|
290
|
+
asTimeOrNull(row.expiresAt), asTimeOrNull(row.revokedAt), asTime(row.createdAt), asTimeOrNull(row.lastUsedAt)]);
|
|
291
|
+
if (!updated.length)
|
|
292
|
+
throw new StoreError("not_found", "Token not found.");
|
|
293
|
+
});
|
|
294
|
+
},
|
|
295
|
+
listLongTokens: (filter) => tx(async (sql) => (await rows(sql, `SELECT * FROM long_lived_tokens
|
|
296
|
+
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)
|
|
297
|
+
ORDER BY created_at, id`, [filter.orgId ?? null, filter.userId ?? null, filter.grantId ?? null])).map(longTokenOf)),
|
|
298
|
+
revokeLongToken(id, at) {
|
|
299
|
+
return tx(async (sql) => {
|
|
300
|
+
const stamp = asTime(at);
|
|
301
|
+
const token = await first(sql, "SELECT * FROM long_lived_tokens WHERE id = $1 FOR UPDATE", [id], longTokenOf);
|
|
302
|
+
if (!token)
|
|
303
|
+
return null;
|
|
304
|
+
const already = token.revokedAt !== null;
|
|
305
|
+
if (!already) {
|
|
306
|
+
token.revokedAt = stamp;
|
|
307
|
+
await sql.query("UPDATE long_lived_tokens SET revoked_at = $2::timestamptz WHERE id = $1", [id, stamp]);
|
|
308
|
+
}
|
|
309
|
+
const revocation = token.grantId && !already ? await revokeGrant(sql, token.grantId, stamp) : null;
|
|
310
|
+
return { token, grant: revocation?.grant ?? null, grantChanged: revocation?.changed ?? false };
|
|
311
|
+
});
|
|
312
|
+
},
|
|
313
|
+
longLivedAccess(hash, at) {
|
|
314
|
+
return tx(async (sql) => {
|
|
315
|
+
const stamp = asTime(at);
|
|
316
|
+
const token = await first(sql, "SELECT * FROM long_lived_tokens WHERE hash = $1", [hash], longTokenOf);
|
|
317
|
+
const user = token ? await first(sql, "SELECT * FROM users WHERE id = $1", [token.userId], userOf) : null;
|
|
318
|
+
const membership = token ? await first(sql, "SELECT * FROM memberships WHERE user_id = $1 AND org_id = $2", [token.userId, token.orgId], membershipOf) : null;
|
|
319
|
+
const grant = token?.grantId ? await first(sql, "SELECT * FROM delegation_grants WHERE id = $1", [token.grantId], grantOf) : null;
|
|
320
|
+
const agent = token?.agentId ? await first(sql, "SELECT * FROM agents WHERE id = $1", [token.agentId], agentOf) : null;
|
|
321
|
+
return decideLongLived({ token, user, membership, grant, agent, at: stamp });
|
|
322
|
+
});
|
|
323
|
+
},
|
|
324
|
+
insertRefresh(row) { return tx((sql) => insertRefresh(sql, row)); },
|
|
325
|
+
findRefreshByHash: (hash) => tx((sql) => first(sql, "SELECT * FROM refresh_tokens WHERE hash = $1", [hash], refreshOf)),
|
|
326
|
+
rotateRefresh(input) {
|
|
327
|
+
return tx(async (sql) => {
|
|
328
|
+
const at = asTime(input.at);
|
|
329
|
+
const current = await first(sql, "SELECT * FROM refresh_tokens WHERE hash = $1 FOR UPDATE", [input.hash], refreshOf);
|
|
330
|
+
if (!current || current.clientId !== input.clientId)
|
|
331
|
+
return { status: "missing" };
|
|
332
|
+
if (current.rotatedAt || current.revokedAt) {
|
|
333
|
+
await sql.query("UPDATE refresh_tokens SET revoked_at = $2::timestamptz WHERE family_id = $1 AND revoked_at IS NULL", [current.familyId, at]);
|
|
334
|
+
const revocation = current.grantId ? await revokeGrant(sql, current.grantId, at) : null;
|
|
335
|
+
return { status: "reuse", grant: revocation?.grant ?? null, grantChanged: revocation?.changed ?? false };
|
|
336
|
+
}
|
|
337
|
+
if (isExpired(current.expiresAt, at))
|
|
338
|
+
return { status: "expired" };
|
|
339
|
+
const account = await first(sql, "SELECT * FROM users WHERE id = $1", [current.userId], userOf);
|
|
340
|
+
if (!account || account.disabledAt)
|
|
341
|
+
return { status: "inactive", reason: "user" };
|
|
342
|
+
const membership = await first(sql, "SELECT * FROM memberships WHERE user_id = $1 AND org_id = $2", [current.userId, current.orgId], membershipOf);
|
|
343
|
+
if (!membership)
|
|
344
|
+
return { status: "inactive", reason: "membership" };
|
|
345
|
+
const grant = current.grantId ? await first(sql, "SELECT * FROM delegation_grants WHERE id = $1", [current.grantId], grantOf) : null;
|
|
346
|
+
if (current.grantId && (!grant || grant.revokedAt || isExpired(grant.expiresAt, at)))
|
|
347
|
+
return { status: "inactive", reason: "grant" };
|
|
348
|
+
const actions = effectiveActions(membership, current.actions, grant);
|
|
349
|
+
if (!actions.length)
|
|
350
|
+
return { status: "inactive", reason: "actions" };
|
|
351
|
+
await sql.query("UPDATE refresh_tokens SET rotated_at = $2::timestamptz WHERE id = $1", [current.id, at]);
|
|
352
|
+
const next = {
|
|
353
|
+
id: input.next.id, hash: input.next.hash, familyId: current.familyId, grantId: current.grantId, clientId: current.clientId,
|
|
354
|
+
userId: current.userId, orgId: current.orgId, audience: current.audience, actions, resources: current.resources, agentId: current.agentId,
|
|
355
|
+
expiresAt: asTime(input.next.expiresAt), rotatedAt: null, revokedAt: null, createdAt: asTime(input.next.createdAt),
|
|
356
|
+
};
|
|
357
|
+
await insertRefresh(sql, next);
|
|
358
|
+
return { status: "rotated", token: next, actions, grant };
|
|
359
|
+
});
|
|
360
|
+
},
|
|
361
|
+
revokeRefreshFamily(hash, at) {
|
|
362
|
+
return tx(async (sql) => {
|
|
363
|
+
const stamp = asTime(at);
|
|
364
|
+
const current = await first(sql, "SELECT family_id FROM refresh_tokens WHERE hash = $1 FOR UPDATE", [hash], (row) => String(row.family_id));
|
|
365
|
+
if (!current)
|
|
366
|
+
return;
|
|
367
|
+
await sql.query("UPDATE refresh_tokens SET revoked_at = $2::timestamptz WHERE family_id = $1 AND revoked_at IS NULL", [current, stamp]);
|
|
368
|
+
});
|
|
369
|
+
},
|
|
370
|
+
insertInstance(row) {
|
|
371
|
+
return tx(async (sql) => {
|
|
372
|
+
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)]);
|
|
373
|
+
});
|
|
374
|
+
},
|
|
375
|
+
insertExecution(row) {
|
|
376
|
+
return tx(async (sql) => {
|
|
377
|
+
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)]);
|
|
378
|
+
});
|
|
379
|
+
},
|
|
380
|
+
insertProvider(row) {
|
|
381
|
+
return tx(async (sql) => {
|
|
382
|
+
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)
|
|
383
|
+
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)]);
|
|
384
|
+
});
|
|
385
|
+
},
|
|
386
|
+
getProvider: (id) => tx((sql) => first(sql, "SELECT * FROM provider_connections WHERE id = $1", [id], providerOf)),
|
|
387
|
+
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)),
|
|
388
|
+
insertTrust(row) {
|
|
389
|
+
return tx(async (sql) => {
|
|
390
|
+
await sql.query(`INSERT INTO workload_trusts (id, name, issuer, audience, tenant, org_id, actions, jwks, disabled_at, created_at)
|
|
391
|
+
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)]);
|
|
392
|
+
});
|
|
393
|
+
},
|
|
394
|
+
getTrust: (id) => tx((sql) => first(sql, "SELECT * FROM workload_trusts WHERE id = $1", [id], trustOf)),
|
|
395
|
+
listTrusts: (issuer, audience) => tx(async (sql) => (await rows(sql, "SELECT * FROM workload_trusts WHERE issuer = $1 AND audience = $2 ORDER BY created_at, id", [issuer, audience])).map(trustOf)),
|
|
396
|
+
insertAudit(row) {
|
|
397
|
+
return tx(async (sql) => {
|
|
398
|
+
await sql.query(`INSERT INTO audit_events (id, at, org_id, actor_user_id, agent_id, audience, action, decision, target, detail)
|
|
399
|
+
VALUES ($1, $2::timestamptz, $3, $4, $5, $6, $7, $8, $9, $10)`, [row.id, asTime(row.at), row.orgId, row.actorUserId, row.agentId, row.audience, row.action, row.decision, row.target, row.detail]);
|
|
400
|
+
});
|
|
401
|
+
},
|
|
402
|
+
listAudit: (query) => tx(async (sql) => (await rows(sql, `SELECT * FROM audit_events
|
|
403
|
+
WHERE org_id = $1
|
|
404
|
+
AND ($2::text IS NULL OR action = $2)
|
|
405
|
+
AND ($3::text IS NULL OR actor_user_id = $3 OR target = $3)
|
|
406
|
+
AND ($4::text IS NULL OR detail LIKE '%' || $4 || '%')
|
|
407
|
+
AND ($5::timestamptz IS NULL OR at >= $5::timestamptz)
|
|
408
|
+
AND ($6::timestamptz IS NULL OR at <= $6::timestamptz)
|
|
409
|
+
ORDER BY at DESC, id DESC LIMIT $7 OFFSET $8`, [
|
|
410
|
+
query.orgId, query.action ?? null, query.subject ?? null, query.source ? `source=${query.source}` : null, query.from ?? null, query.to ?? null, query.limit, query.offset,
|
|
411
|
+
])).map(auditOf)),
|
|
412
|
+
getDeniedJti: (id) => tx((sql) => first(sql, "SELECT * FROM denied_jtis WHERE id = $1", [id], deniedOf)),
|
|
413
|
+
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]); }),
|
|
414
|
+
getIdempotency: (id) => tx((sql) => first(sql, "SELECT * FROM idempotency_records WHERE id = $1", [id], idempotencyOf)),
|
|
415
|
+
insertIdempotency(row) {
|
|
416
|
+
return tx(async (sql) => {
|
|
417
|
+
await sql.query("INSERT INTO idempotency_records (id, request_hash, status, body, created_at) VALUES ($1, $2, $3, $4, $5::timestamptz)", [row.id, row.requestHash, row.status, row.body, asTime(row.createdAt)]);
|
|
418
|
+
});
|
|
419
|
+
},
|
|
420
|
+
insertApplication(row) {
|
|
421
|
+
return tx(async (sql) => {
|
|
422
|
+
await sql.query(`INSERT INTO applications (
|
|
423
|
+
id, org_id, title, description, status, allowed_scopes, allowed_features, created_at, updated_at
|
|
424
|
+
) VALUES (
|
|
425
|
+
$1, $2, $3, $4, $5, $6::text[], $7::text[], $8::timestamptz, $9::timestamptz
|
|
426
|
+
)`, [
|
|
427
|
+
row.id, row.orgId, row.title, row.description, row.status, row.allowedScopes, row.allowedFeatures, asTime(row.createdAt), asTime(row.updatedAt),
|
|
428
|
+
]);
|
|
429
|
+
});
|
|
430
|
+
},
|
|
431
|
+
getApplication: (id) => tx((sql) => first(sql, "SELECT * FROM applications WHERE id = $1", [id], applicationOf)),
|
|
432
|
+
listApplications: (orgId) => tx(async (sql) => (await rows(sql, "SELECT * FROM applications WHERE org_id = $1 ORDER BY created_at DESC, id DESC", [orgId])).map(applicationOf)),
|
|
433
|
+
updateApplication(row) {
|
|
434
|
+
return tx(async (sql) => {
|
|
435
|
+
const updated = await rows(sql, `UPDATE applications SET
|
|
436
|
+
title = $2, description = $3, status = $4, allowed_scopes = $5::text[], allowed_features = $6::text[], updated_at = $7::timestamptz,
|
|
437
|
+
product_name = $8, logo_url = $9, accent_color = $10, signup_mode = $11, allow_without_personal_org = $12
|
|
438
|
+
WHERE id = $1 RETURNING id`, [
|
|
439
|
+
row.id, row.title, row.description, row.status, row.allowedScopes, row.allowedFeatures, asTime(row.updatedAt),
|
|
440
|
+
row.productName || row.title, row.logoUrl ?? null, row.accentColor ?? null, row.signupMode ?? "open", row.allowRegistrationWithoutPersonalOrg === true,
|
|
441
|
+
]);
|
|
442
|
+
if (!updated.length)
|
|
443
|
+
throw new StoreError("not_found", "Application not found.");
|
|
444
|
+
});
|
|
445
|
+
},
|
|
446
|
+
insertEnvironment(row) {
|
|
447
|
+
return tx(async (sql) => {
|
|
448
|
+
await sql.query(`INSERT INTO app_environments (
|
|
449
|
+
id, app_id, org_id, name, title, status, secret_enc, secret_hash, key_version,
|
|
450
|
+
previous_secret_enc, previous_secret_hash, previous_key_version, previous_key_expires_at, created_at, updated_at
|
|
451
|
+
) VALUES (
|
|
452
|
+
$1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13::timestamptz, $14::timestamptz, $15::timestamptz
|
|
453
|
+
)`, [
|
|
454
|
+
row.id, row.appId, row.orgId, row.name, row.title, row.status, row.secretEnc, row.secretHash, row.keyVersion,
|
|
455
|
+
row.previousSecretEnc, row.previousSecretHash, row.previousKeyVersion, asTimeOrNull(row.previousKeyExpiresAt), asTime(row.createdAt), asTime(row.updatedAt),
|
|
456
|
+
]);
|
|
457
|
+
});
|
|
458
|
+
},
|
|
459
|
+
getEnvironment: (id) => tx((sql) => first(sql, "SELECT * FROM app_environments WHERE id = $1", [id], environmentOf)),
|
|
460
|
+
listEnvironments: (appId) => tx(async (sql) => (await rows(sql, "SELECT * FROM app_environments WHERE app_id = $1 ORDER BY created_at, name", [appId])).map(environmentOf)),
|
|
461
|
+
updateEnvironment(row) {
|
|
462
|
+
return tx(async (sql) => {
|
|
463
|
+
const updated = await rows(sql, `UPDATE app_environments SET
|
|
464
|
+
title = $2, status = $3, secret_enc = $4, secret_hash = $5, key_version = $6,
|
|
465
|
+
previous_secret_enc = $7, previous_secret_hash = $8, previous_key_version = $9,
|
|
466
|
+
previous_key_expires_at = $10::timestamptz, updated_at = $11::timestamptz
|
|
467
|
+
WHERE id = $1 RETURNING id`, [
|
|
468
|
+
row.id, row.title, row.status, row.secretEnc, row.secretHash, row.keyVersion,
|
|
469
|
+
row.previousSecretEnc, row.previousSecretHash, row.previousKeyVersion, asTimeOrNull(row.previousKeyExpiresAt), asTime(row.updatedAt),
|
|
470
|
+
]);
|
|
471
|
+
if (!updated.length)
|
|
472
|
+
throw new StoreError("not_found", "Environment not found.");
|
|
473
|
+
});
|
|
474
|
+
},
|
|
475
|
+
insertAppToken(row) {
|
|
476
|
+
return tx(async (sql) => {
|
|
477
|
+
await sql.query(`INSERT INTO app_tokens (
|
|
478
|
+
id, app_id, environment_id, org_id, owner_identity_id, identity_type, payload, encrypted, revoked_at, expires_at, created_at
|
|
479
|
+
) VALUES ($1, $2, $3, $4, $5, $6, $7::jsonb, $8, $9::timestamptz, $10::timestamptz, $11::timestamptz)`, [
|
|
480
|
+
row.id, row.appId, row.environmentId, row.orgId, row.ownerIdentityId, row.identityType, JSON.stringify(row.payload), row.encrypted,
|
|
481
|
+
asTimeOrNull(row.revokedAt), asTimeOrNull(row.expiresAt), asTime(row.createdAt),
|
|
482
|
+
]);
|
|
483
|
+
});
|
|
484
|
+
},
|
|
485
|
+
getAppToken: (id) => tx((sql) => first(sql, "SELECT * FROM app_tokens WHERE id = $1", [id], appTokenOf)),
|
|
486
|
+
listAppTokens: (filter) => tx(async (sql) => (await rows(sql, `SELECT * FROM app_tokens
|
|
487
|
+
WHERE ($1::text IS NULL OR app_id = $1) AND ($2::text IS NULL OR environment_id = $2) AND ($3::text IS NULL OR owner_identity_id = $3) AND ($4::text IS NULL OR org_id = $4)
|
|
488
|
+
ORDER BY created_at DESC, id DESC`, [filter.appId ?? null, filter.environmentId ?? null, filter.identityId ?? null, filter.orgId ?? null])).map(appTokenOf)),
|
|
489
|
+
revokeAppToken: (id, at) => tx(async (sql) => {
|
|
490
|
+
await sql.query("UPDATE app_tokens SET revoked_at = $2::timestamptz WHERE id = $1 AND revoked_at IS NULL", [id, asTime(at)]);
|
|
491
|
+
return first(sql, "SELECT * FROM app_tokens WHERE id = $1", [id], appTokenOf);
|
|
492
|
+
}),
|
|
493
|
+
revokeAppTokens: (filter, at) => tx(async (sql) => {
|
|
494
|
+
const updated = await rows(sql, `UPDATE app_tokens SET revoked_at = $5::timestamptz
|
|
495
|
+
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)
|
|
496
|
+
RETURNING id`, [filter.appId ?? null, filter.environmentId ?? null, filter.identityId ?? null, filter.orgId ?? null, asTime(at)]);
|
|
497
|
+
return updated.length;
|
|
498
|
+
}),
|
|
499
|
+
saveSignInConnection: (row) => tx(async (sql) => {
|
|
500
|
+
await sql.query(`INSERT INTO sign_in_connections (id, org_id, provider, client_id, client_secret_enc, directory_id, issuer, created_at)
|
|
501
|
+
VALUES ($1, $2, $3, $4, $5, $6, $7, $8::timestamptz)
|
|
502
|
+
ON CONFLICT (org_id, provider) DO UPDATE SET client_id = EXCLUDED.client_id, client_secret_enc = EXCLUDED.client_secret_enc, directory_id = EXCLUDED.directory_id, issuer = EXCLUDED.issuer`, [row.id, row.orgId, row.provider, row.clientId, row.clientSecretEnc, row.directoryId, row.issuer, asTime(row.createdAt)]);
|
|
503
|
+
}),
|
|
504
|
+
listSignInConnections: (orgId) => tx(async (sql) => (await rows(sql, "SELECT * FROM sign_in_connections WHERE org_id = $1 ORDER BY provider", [orgId])).map(signInOf)),
|
|
505
|
+
deleteSignInConnection: (orgId, provider) => tx(async (sql) => { await sql.query("DELETE FROM sign_in_connections WHERE org_id = $1 AND provider = $2", [orgId, provider]); }),
|
|
506
|
+
saveAppSignIn: (appId, providers) => tx(async (sql) => {
|
|
507
|
+
await sql.query(`INSERT INTO app_sign_in (app_id, providers) VALUES ($1, $2) ON CONFLICT (app_id) DO UPDATE SET providers = EXCLUDED.providers`, [appId, providers]);
|
|
508
|
+
}),
|
|
509
|
+
getAppSignIn: (appId) => tx(async (sql) => textsOf(await first(sql, "SELECT providers FROM app_sign_in WHERE app_id = $1", [appId], (row) => row))),
|
|
510
|
+
saveRedirects: (environmentId, uris) => tx(async (sql) => {
|
|
511
|
+
await sql.query(`INSERT INTO environment_redirects (environment_id, uris) VALUES ($1, $2) ON CONFLICT (environment_id) DO UPDATE SET uris = EXCLUDED.uris`, [environmentId, uris]);
|
|
512
|
+
}),
|
|
513
|
+
getRedirects: (environmentId) => tx(async (sql) => textsOf(await first(sql, "SELECT uris FROM environment_redirects WHERE environment_id = $1", [environmentId], (row) => row))),
|
|
514
|
+
insertSsoLogin: (row) => tx(async (sql) => {
|
|
515
|
+
await sql.query(`INSERT INTO sso_logins (id, state_hash, nonce, verifier, app_id, environment_id, org_id, provider, redirect_uri, app_state, expires_at, created_at)
|
|
516
|
+
VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11::timestamptz,$12::timestamptz)`, [
|
|
517
|
+
row.id, row.stateHash, row.nonce, row.verifier, row.appId, row.environmentId, row.orgId, row.provider, row.redirectUri, row.appState, asTime(row.expiresAt), asTime(row.createdAt),
|
|
518
|
+
]);
|
|
519
|
+
}),
|
|
520
|
+
takeSsoLogin: (stateHash, at) => tx(async (sql) => {
|
|
521
|
+
const found = await first(sql, "DELETE FROM sso_logins WHERE state_hash = $1 RETURNING *", [stateHash], ssoLoginOf);
|
|
522
|
+
if (!found || Date.parse(found.expiresAt) <= Date.parse(asTime(at)))
|
|
523
|
+
return null;
|
|
524
|
+
return found;
|
|
525
|
+
}),
|
|
526
|
+
insertSsoExchange: (row) => tx(async (sql) => {
|
|
527
|
+
await sql.query(`INSERT INTO sso_exchanges (id, code_hash, app_id, environment_id, token, token_id, subject, provider, expires_at, created_at)
|
|
528
|
+
VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9::timestamptz,$10::timestamptz)`, [
|
|
529
|
+
row.id, row.codeHash, row.appId, row.environmentId, row.token, row.tokenId, row.subject, row.provider, asTime(row.expiresAt), asTime(row.createdAt),
|
|
530
|
+
]);
|
|
531
|
+
}),
|
|
532
|
+
takeSsoExchange: (codeHash, at) => tx(async (sql) => {
|
|
533
|
+
const found = await first(sql, "DELETE FROM sso_exchanges WHERE code_hash = $1 RETURNING *", [codeHash], ssoExchangeOf);
|
|
534
|
+
if (!found || Date.parse(found.expiresAt) <= Date.parse(asTime(at)))
|
|
535
|
+
return null;
|
|
536
|
+
return found;
|
|
537
|
+
}),
|
|
538
|
+
insertServiceCredential: (row) => tx(async (sql) => {
|
|
539
|
+
await sql.query(`INSERT INTO service_credentials (id, org_id, name, secret_hash, app_ids, permissions, revoked_at, created_at)
|
|
540
|
+
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)]);
|
|
541
|
+
}),
|
|
542
|
+
listServiceCredentials: (orgId) => tx(async (sql) => (await rows(sql, "SELECT * FROM service_credentials WHERE org_id = $1 ORDER BY created_at DESC", [orgId])).map(serviceCredentialOf)),
|
|
543
|
+
findServiceCredentialByHash: (hash) => tx((sql) => first(sql, "SELECT * FROM service_credentials WHERE secret_hash = $1", [hash], serviceCredentialOf)),
|
|
544
|
+
revokeServiceCredential: (id, at) => tx(async (sql) => {
|
|
545
|
+
await sql.query("UPDATE service_credentials SET revoked_at = $2::timestamptz WHERE id = $1 AND revoked_at IS NULL", [id, asTime(at)]);
|
|
546
|
+
return first(sql, "SELECT * FROM service_credentials WHERE id = $1", [id], serviceCredentialOf);
|
|
547
|
+
}),
|
|
548
|
+
insertPrincipal: (row) => tx(async (sql) => {
|
|
549
|
+
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)]);
|
|
550
|
+
}),
|
|
551
|
+
listPrincipals: (orgId) => tx(async (sql) => (await rows(sql, "SELECT * FROM workload_principals WHERE org_id = $1 ORDER BY created_at DESC", [orgId])).map(principalOf)),
|
|
552
|
+
findPrincipalByClientId: (clientId) => tx((sql) => first(sql, "SELECT * FROM workload_principals WHERE client_id = $1", [clientId], principalOf)),
|
|
553
|
+
insertWorkloadCredential: (row) => tx(async (sql) => {
|
|
554
|
+
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)]);
|
|
555
|
+
}),
|
|
556
|
+
listWorkloadCredentials: (principalId) => tx(async (sql) => (await rows(sql, "SELECT * FROM workload_credentials WHERE principal_id = $1", [principalId])).map(workloadCredentialOf)),
|
|
557
|
+
insertAudience: (row) => tx(async (sql) => {
|
|
558
|
+
await sql.query(`INSERT INTO audiences (id, org_id, name, identifier, app_id, created_at) VALUES ($1,$2,$3,$4,$5,$6::timestamptz)`, [row.id, row.orgId, row.name, row.identifier, row.appId, asTime(row.createdAt)]);
|
|
559
|
+
}),
|
|
560
|
+
listAudiences: (orgId) => tx(async (sql) => (await rows(sql, "SELECT * FROM audiences WHERE org_id = $1", [orgId])).map(audienceOf)),
|
|
561
|
+
findAudience: (orgId, identifier) => tx((sql) => first(sql, "SELECT * FROM audiences WHERE org_id = $1 AND identifier = $2", [orgId, identifier], audienceOf)),
|
|
562
|
+
insertRole: (row) => tx(async (sql) => {
|
|
563
|
+
await sql.query(`INSERT INTO role_definitions (id, org_id, name, actions, created_at) VALUES ($1,$2,$3,$4,$5::timestamptz)`, [row.id, row.orgId, row.name, row.actions, asTime(row.createdAt)]);
|
|
564
|
+
}),
|
|
565
|
+
listRoles: (orgId) => tx(async (sql) => (await rows(sql, "SELECT * FROM role_definitions WHERE org_id = $1", [orgId])).map(roleOf)),
|
|
566
|
+
insertAssignment: (row) => tx(async (sql) => {
|
|
567
|
+
await sql.query(`INSERT INTO role_assignments (id, org_id, principal_id, role_id, scope, created_at) VALUES ($1,$2,$3,$4,$5,$6::timestamptz)`, [row.id, row.orgId, row.principalId, row.roleId, row.scope, asTime(row.createdAt)]);
|
|
568
|
+
}),
|
|
569
|
+
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)),
|
|
570
|
+
insertGatewayRoute: (row) => tx(async (sql) => {
|
|
571
|
+
await sql.query(`INSERT INTO gateway_routes (id, org_id, audience_id, method, path, data_action, resource, created_at) VALUES ($1,$2,$3,$4,$5,$6,$7,$8::timestamptz)`, [row.id, row.orgId, row.audienceId, row.method, row.path, row.dataAction, row.resource, asTime(row.createdAt)]);
|
|
572
|
+
}),
|
|
573
|
+
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)),
|
|
574
|
+
deleteGatewayRoute: (id, orgId) => tx(async (sql) => {
|
|
575
|
+
const removed = await rows(sql, "DELETE FROM gateway_routes WHERE id = $1 AND org_id = $2 RETURNING id", [id, orgId]);
|
|
576
|
+
if (!removed.length)
|
|
577
|
+
throw new StoreError("not_found", "Route not found.");
|
|
578
|
+
}),
|
|
579
|
+
...createSqlDirectory(tx),
|
|
580
|
+
ping: () => tx(async (sql) => { await sql.query("SELECT 1"); }),
|
|
581
|
+
purgeExpired(at) {
|
|
582
|
+
return tx(async (sql) => {
|
|
583
|
+
const stamp = asTime(at);
|
|
584
|
+
const seconds = Math.floor(Date.parse(stamp) / 1000);
|
|
585
|
+
await sql.query("DELETE FROM sessions WHERE expires_at <= $1::timestamptz", [stamp]);
|
|
586
|
+
await sql.query("DELETE FROM email_challenges WHERE expires_at <= $1::timestamptz", [stamp]);
|
|
587
|
+
await sql.query("DELETE FROM authorization_requests WHERE expires_at <= $1::timestamptz", [stamp]);
|
|
588
|
+
await sql.query("DELETE FROM denied_jtis WHERE exp <= $1", [seconds]);
|
|
589
|
+
await sql.query("DELETE FROM sso_logins WHERE expires_at <= $1::timestamptz", [stamp]);
|
|
590
|
+
await sql.query("DELETE FROM sso_exchanges WHERE expires_at <= $1::timestamptz", [stamp]);
|
|
591
|
+
});
|
|
592
|
+
},
|
|
593
|
+
};
|
|
594
|
+
return store;
|
|
595
|
+
}
|
|
596
|
+
function textsOf(row) {
|
|
597
|
+
const value = row?.uris ?? row?.providers;
|
|
598
|
+
return Array.isArray(value) ? value.map(String) : [];
|
|
599
|
+
}
|
|
600
|
+
function insertAuthorization(sql, row) {
|
|
601
|
+
return sql.query(`INSERT INTO authorization_requests (
|
|
602
|
+
id, kind, client_id, redirect_uri, code_challenge, audience, actions, resources, state, org_id, user_id, status, code_hash,
|
|
603
|
+
device_code_hash, user_code_hash, grant_id, agent_id, interval_seconds, last_poll_at, expires_at, created_at
|
|
604
|
+
) VALUES (
|
|
605
|
+
$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
|
|
606
|
+
)`, [
|
|
607
|
+
row.id, row.kind, row.clientId, row.redirectUri, row.codeChallenge, row.audience, row.actions, row.resources, row.state, row.orgId, row.userId,
|
|
608
|
+
row.status, row.codeHash, row.deviceCodeHash, row.userCodeHash, row.grantId, row.agentId, row.intervalSeconds, asTimeOrNull(row.lastPollAt),
|
|
609
|
+
asTime(row.expiresAt), asTime(row.createdAt),
|
|
610
|
+
]).then(() => undefined);
|
|
611
|
+
}
|
|
612
|
+
function insertLongToken(sql, row) {
|
|
613
|
+
return sql.query(`INSERT INTO long_lived_tokens (
|
|
614
|
+
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
|
|
615
|
+
) VALUES (
|
|
616
|
+
$1, $2, $3, $4, $5, $6, $7, $8, $9::text[], $10::text[], $11, $12, $13::timestamptz, $14::timestamptz, $15::timestamptz, $16::timestamptz
|
|
617
|
+
)`, [
|
|
618
|
+
row.id, row.prefix, row.hash, row.kind, row.name, row.userId, row.orgId, row.audience, row.actions, row.resources, row.grantId, row.agentId,
|
|
619
|
+
asTimeOrNull(row.expiresAt), asTimeOrNull(row.revokedAt), asTime(row.createdAt), asTimeOrNull(row.lastUsedAt),
|
|
620
|
+
]).then(() => undefined);
|
|
621
|
+
}
|
|
622
|
+
function insertRefresh(sql, row) {
|
|
623
|
+
return sql.query(`INSERT INTO refresh_tokens (
|
|
624
|
+
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
|
|
625
|
+
) VALUES (
|
|
626
|
+
$1, $2, $3, $4, $5, $6, $7, $8, $9::text[], $10::text[], $11, $12::timestamptz, $13::timestamptz, $14::timestamptz, $15::timestamptz
|
|
627
|
+
)`, [
|
|
628
|
+
row.id, row.hash, row.familyId, row.grantId, row.clientId, row.userId, row.orgId, row.audience, row.actions, row.resources, row.agentId,
|
|
629
|
+
asTime(row.expiresAt), asTimeOrNull(row.rotatedAt), asTimeOrNull(row.revokedAt), asTime(row.createdAt),
|
|
630
|
+
]).then(() => undefined);
|
|
631
|
+
}
|
|
632
|
+
//# sourceMappingURL=sql-store.js.map
|