@coffre/db 0.5.1 → 0.6.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/grants.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { i as Queryable } from "./database-C63WjCrC.js";
2
2
  import { Authenticity, Newest } from "./log.js";
3
- import { Conversion, InstanceRole, Scope } from "@coffre/core/access";
3
+ import { Conversion, ConversionInput, InstanceRole, Scope } from "@coffre/core/access";
4
4
  import { StoredEntry } from "@coffre/core/audit";
5
5
  //#region src/grants.d.ts
6
6
  /**
@@ -48,6 +48,17 @@ export declare function storedRole({ owner, role, scope }: StoredRole): {
48
48
  };
49
49
  /** The columns that store a member's instance role and scope: `owner` too, for a vault of 0.4 to read. */
50
50
  export declare function roleColumns(role: InstanceRole, scope: Scope): StoredRole;
51
+ /** Every project not deleted, with its environments not deleted: what a grant on every project of 0.4 reached. */
52
+ export declare function liveProjects(db: Queryable): Promise<ConversionInput['projects']>;
53
+ /**
54
+ * What the vault makes of a member's grants on every project of 0.4
55
+ * (`convertEveryProjectGrants`), from their instance role and their grants
56
+ * as stored, those live at `at`: the vault as it converts them, under their
57
+ * row's lock, and `coffre migrate` before, from the rows as they are. The
58
+ * role is the one their row holds: the vault converts these before it makes
59
+ * the Owners its deployment names.
60
+ */
61
+ export declare function everyProjectConversion(principal: string, role: InstanceRole, grants: readonly GrantRow[], at: number, projects: ConversionInput['projects']): Conversion;
51
62
  /** What the vault does, when this version first runs, to one member's grants on every project of 0.4. */
52
63
  export type EveryProjectPreview = {
53
64
  principal: string;
@@ -78,9 +89,7 @@ export type EveryProjectPreview = {
78
89
  * `reported`, by the vault's own rule (`tamperedMembers`) over the entries as
79
90
  * they read: whether that report is the vault's own, or forged so as to
80
91
  * hide what it will do, only the vault can tell. Any member the vault
81
- * converts is listed. A root admin's it leaves while they are one, until
82
- * they are not; which they are, the vault's configuration says and the
83
- * database does not, so they are listed too.
92
+ * converts is listed.
84
93
  */
85
94
  export declare function everyProjectPreview(db: Queryable, at: number): Promise<EveryProjectPreview[]>;
86
95
  /** A service token or trust binding of 0.4, which carries no scope of its own yet. */
package/dist/grants.js CHANGED
@@ -1,8 +1,8 @@
1
1
  import { tablesOf } from "./index.js";
2
+ import { tombstone, truth } from "./dialect.js";
2
3
  import { LOOK_BACK, entryColumns, newestAuthentic } from "./log.js";
3
- import { and, desc, eq, gt, inArray, isNull, lt, or, sql } from "drizzle-orm";
4
+ import { and, asc, desc, eq, gt, inArray, isNull, lt, or, sql } from "drizzle-orm";
4
5
  import { EVERYWHERE, administers, convertEveryProjectGrants, isInstanceRole, isScope, normalScope, unscoped } from "@coffre/core/access";
5
- import { isTombstone } from "@coffre/core/schemas";
6
6
  import { ACCESS_ACTIONS } from "@coffre/core/vault";
7
7
  //#region src/grants.ts
8
8
  /** Grants, lapsed ones too unless `liveAt` says when to judge them: one member's, or everyone's. */
@@ -60,6 +60,54 @@ function roleColumns(role, scope) {
60
60
  scope: role === "member" || unscoped(normal) ? null : JSON.stringify(normal)
61
61
  };
62
62
  }
63
+ /** Every project not deleted, with its environments not deleted: what a grant on every project of 0.4 reached. */
64
+ async function liveProjects(db) {
65
+ const { projects, environments } = tablesOf(db);
66
+ const [found, inside] = await Promise.all([db.select({
67
+ id: projects.id,
68
+ deleted: truth(tombstone(projects.slug))
69
+ }).from(projects).orderBy(asc(projects.id)), db.select({
70
+ id: environments.id,
71
+ projectId: environments.projectId,
72
+ slug: environments.slug,
73
+ deleted: truth(tombstone(environments.slug))
74
+ }).from(environments).orderBy(asc(environments.id))]);
75
+ return found.filter((project) => !project.deleted).map((project) => ({
76
+ id: project.id,
77
+ environments: inside.filter((environment) => environment.projectId === project.id && !environment.deleted).map(({ id, slug }) => ({
78
+ id,
79
+ slug
80
+ }))
81
+ }));
82
+ }
83
+ /**
84
+ * What the vault makes of a member's grants on every project of 0.4
85
+ * (`convertEveryProjectGrants`), from their instance role and their grants
86
+ * as stored, those live at `at`: the vault as it converts them, under their
87
+ * row's lock, and `coffre migrate` before, from the rows as they are. The
88
+ * role is the one their row holds: the vault converts these before it makes
89
+ * the Owners its deployment names.
90
+ */
91
+ function everyProjectConversion(principal, role, grants, at, projects) {
92
+ const person = principal.startsWith("user:");
93
+ const live = grants.filter((grant) => grant.expiresAt === null || grant.expiresAt > at);
94
+ return convertEveryProjectGrants({
95
+ person,
96
+ role: person ? role : "member",
97
+ everyProject: live.filter((grant) => grant.projectId === null && grant.environmentId === null).map((grant) => ({
98
+ environmentSlug: grant.environmentSlug,
99
+ role: grant.role,
100
+ expiresAt: grant.expiresAt
101
+ })),
102
+ grants: live.filter((grant) => grant.projectId !== null).map((grant) => ({
103
+ projectId: grant.projectId,
104
+ environmentId: grant.environmentId,
105
+ role: grant.role,
106
+ expiresAt: grant.expiresAt
107
+ })),
108
+ projects
109
+ });
110
+ }
63
111
  /**
64
112
  * What the vault will make of the grants on every project of 0.4 that live
65
113
  * members hold, by the rule it converts them with
@@ -71,16 +119,15 @@ function roleColumns(role, scope) {
71
119
  * `reported`, by the vault's own rule (`tamperedMembers`) over the entries as
72
120
  * they read: whether that report is the vault's own, or forged so as to
73
121
  * hide what it will do, only the vault can tell. Any member the vault
74
- * converts is listed. A root admin's it leaves while they are one, until
75
- * they are not; which they are, the vault's configuration says and the
76
- * database does not, so they are listed too.
122
+ * converts is listed.
77
123
  */
78
124
  async function everyProjectPreview(db, at) {
79
125
  const { vaultMembers, projects, environments } = tablesOf(db);
80
- const held = (await readGrants(db, { liveAt: at })).filter((grant) => grant.projectId === null && grant.environmentId === null);
126
+ const grants = await readGrants(db, { liveAt: at });
127
+ const held = grants.filter((grant) => grant.projectId === null && grant.environmentId === null);
81
128
  if (held.length === 0) return [];
82
129
  const holders = [...new Set(held.map((grant) => grant.principal))].sort();
83
- const [members, grants, places, inside, tampered] = await Promise.all([
130
+ const [members, places, inside, live, tampered] = await Promise.all([
84
131
  db.select({
85
132
  principal: vaultMembers.principal,
86
133
  status: vaultMembers.status,
@@ -88,7 +135,6 @@ async function everyProjectPreview(db, at) {
88
135
  role: vaultMembers.role,
89
136
  scope: vaultMembers.scope
90
137
  }).from(vaultMembers),
91
- readGrants(db, { liveAt: at }),
92
138
  db.select({
93
139
  id: projects.id,
94
140
  slug: projects.slug
@@ -98,43 +144,21 @@ async function everyProjectPreview(db, at) {
98
144
  projectId: environments.projectId,
99
145
  slug: environments.slug
100
146
  }).from(environments),
147
+ liveProjects(db),
101
148
  tamperedMembers(db)
102
149
  ]);
103
- const live = places.filter((project) => !isTombstone(project.slug)).map((project) => ({
104
- id: project.id,
105
- environments: inside.filter((environment) => environment.projectId === project.id && !isTombstone(environment.slug)).map(({ id, slug }) => ({
106
- id,
107
- slug
108
- }))
109
- }));
110
150
  const paths = Object.fromEntries(places.flatMap((project) => [[project.id, project.slug], ...inside.filter((environment) => environment.projectId === project.id).map((environment) => [environment.id, `${project.slug}/${environment.slug}`])]));
111
151
  return holders.flatMap((principal) => {
112
152
  const member = members.find((row) => row.principal === principal);
113
153
  if (member?.status !== "active") return [];
114
- const theirs = held.filter((grant) => grant.principal === principal);
115
154
  return [{
116
155
  principal,
117
- before: theirs.map((grant) => ({
156
+ before: held.filter((grant) => grant.principal === principal).map((grant) => ({
118
157
  place: grant.environmentSlug === null ? "*" : `*/${grant.environmentSlug}`,
119
158
  role: grant.role,
120
159
  expiresAt: grant.expiresAt
121
160
  })),
122
- conversion: convertEveryProjectGrants({
123
- person: principal.startsWith("user:"),
124
- role: principal.startsWith("user:") ? storedRole(member).role : "member",
125
- everyProject: theirs.map((grant) => ({
126
- environmentSlug: grant.environmentSlug,
127
- role: grant.role,
128
- expiresAt: grant.expiresAt
129
- })),
130
- grants: grants.filter((grant) => grant.principal === principal && grant.projectId !== null).map((grant) => ({
131
- projectId: grant.projectId,
132
- environmentId: grant.environmentId,
133
- role: grant.role,
134
- expiresAt: grant.expiresAt
135
- })),
136
- projects: live
137
- }),
161
+ conversion: everyProjectConversion(principal, storedRole(member).role, grants.filter((grant) => grant.principal === principal), at, live),
138
162
  paths,
139
163
  reported: tampered.has(principal)
140
164
  }];
@@ -224,4 +248,4 @@ async function tamperReportsAbout(db, principal, limit, after, before) {
224
248
  return await db.select(entryColumns(db)).from(auditLog).where(and(eq(auditLog.author, "vault"), eq(auditLog.subjectPrincipal, principal), eq(auditLog.action, "vault.tampered"), inArray(auditLog.code, [...TAMPER_CODES]), gt(auditLog.seq, after), before === void 0 ? void 0 : lt(auditLog.seq, before))).orderBy(desc(auditLog.seq)).limit(limit);
225
249
  }
226
250
  //#endregion
227
- export { accessEntriesAbout, everyProjectPreview, insertGrant, newestAccess, readGrants, reportStands, roleColumns, storedRole, tamperedMembers, unsealedCredentials };
251
+ export { accessEntriesAbout, everyProjectConversion, everyProjectPreview, insertGrant, liveProjects, newestAccess, readGrants, reportStands, roleColumns, storedRole, tamperedMembers, unsealedCredentials };
package/dist/log.d.ts CHANGED
@@ -450,6 +450,8 @@ export type Authenticity = {
450
450
  authentic: (entry: StoredEntry) => boolean;
451
451
  forged: (entry: StoredEntry) => void;
452
452
  };
453
+ /** Up to `limit` of the entries in the vault's name, allowed, of one `action`, before `before` (the newest when undefined), newest first. */
454
+ export declare function newestVaultEntries(db: Queryable, action: string, limit: number, before?: bigint): Promise<StoredEntry[]>;
453
455
  /** How many entries in its name the vault reads back, a page at a time, for its own newest of a kind (`newestAuthentic`). */
454
456
  export declare const LOOK_BACK: {
455
457
  page: number;
package/dist/log.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import { t as afterCommit } from "./commits-BuW-NL3n.js";
2
2
  import { tablesOf } from "./index.js";
3
3
  import { clockMillis, forUpdate } from "./dialect.js";
4
- import { desc, eq } from "drizzle-orm";
4
+ import { and, desc, eq, lt } from "drizzle-orm";
5
5
  import { GENESIS_HASH, sealEntry } from "@coffre/core/audit";
6
6
  //#region src/log.ts
7
7
  /** The log's head does not name its last entry: something moved it, or cut the log behind it. */
@@ -163,6 +163,11 @@ function entryColumns(db) {
163
163
  hash: auditLog.hash
164
164
  };
165
165
  }
166
+ /** Up to `limit` of the entries in the vault's name, allowed, of one `action`, before `before` (the newest when undefined), newest first. */
167
+ async function newestVaultEntries(db, action, limit, before) {
168
+ const { auditLog } = tablesOf(db);
169
+ return await db.select(entryColumns(db)).from(auditLog).where(and(eq(auditLog.author, "vault"), eq(auditLog.action, action), eq(auditLog.decision, "allow"), before === void 0 ? void 0 : lt(auditLog.seq, before))).orderBy(desc(auditLog.seq)).limit(limit);
170
+ }
166
171
  /** How many entries in its name the vault reads back, a page at a time, for its own newest of a kind (`newestAuthentic`). */
167
172
  const LOOK_BACK = {
168
173
  page: 32,
@@ -189,4 +194,4 @@ async function newestAuthentic(page, check) {
189
194
  return "unreached";
190
195
  }
191
196
  //#endregion
192
- export { LOOK_BACK, LogHeadMismatch, LogRewound, appendEntries, entryColumns, forgetLogHeads, lockLogHead, newestAuthentic };
197
+ export { LOOK_BACK, LogHeadMismatch, LogRewound, appendEntries, entryColumns, forgetLogHeads, lockLogHead, newestAuthentic, newestVaultEntries };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@coffre/db",
3
- "version": "0.5.1",
3
+ "version": "0.6.0",
4
4
  "description": "coffre's database: the schema, its migrations and the connections, on Postgres or SQLite.",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -79,7 +79,7 @@
79
79
  "drizzle-orm": "0.45.2",
80
80
  "pg": "8.16.3",
81
81
  "pg-connection-string": "2.14.0",
82
- "@coffre/core": "0.5.1"
82
+ "@coffre/core": "0.6.0"
83
83
  },
84
84
  "devDependencies": {
85
85
  "@types/node": "26.1.1",
package/src/grants.ts CHANGED
@@ -7,17 +7,18 @@ import {
7
7
  normalScope,
8
8
  unscoped,
9
9
  type Conversion,
10
+ type ConversionInput,
10
11
  type InstanceRole,
11
12
  type Role,
12
13
  type Scope,
13
14
  } from '@coffre/core/access';
14
15
  import type { StoredEntry } from '@coffre/core/audit';
15
- import { isTombstone } from '@coffre/core/schemas';
16
16
  import { ACCESS_ACTIONS } from '@coffre/core/vault';
17
- import { and, desc, eq, gt, inArray, isNull, lt, or, sql, type SQL } from 'drizzle-orm';
17
+ import { and, asc, desc, eq, gt, inArray, isNull, like, lt, or, sql, type SQL } from 'drizzle-orm';
18
18
 
19
19
  import { tablesOf, type Queryable } from './database.ts';
20
- import { entryColumns, LOOK_BACK, newestAuthentic, type Authenticity, type Newest } from './log.ts';
20
+ import { tombstone, truth } from './dialect.ts';
21
+ import { entryColumns, LOOK_BACK, newestAuthentic, newestVaultEntries, type Authenticity, type Newest } from './log.ts';
21
22
 
22
23
  /**
23
24
  * One grant, as `vault_grants` holds it: on a project (`environmentId`
@@ -93,6 +94,49 @@ export function roleColumns(role: InstanceRole, scope: Scope): StoredRole {
93
94
  return { owner: administers(role), role, scope: role === 'member' || unscoped(normal) ? null : JSON.stringify(normal) };
94
95
  }
95
96
 
97
+ /** Every project not deleted, with its environments not deleted: what a grant on every project of 0.4 reached. */
98
+ export async function liveProjects(db: Queryable): Promise<ConversionInput['projects']> {
99
+ const { projects, environments } = tablesOf(db);
100
+ const [found, inside] = await Promise.all([
101
+ db.select({ id: projects.id, deleted: truth(tombstone(projects.slug)) }).from(projects).orderBy(asc(projects.id)),
102
+ db.select({ id: environments.id, projectId: environments.projectId, slug: environments.slug, deleted: truth(tombstone(environments.slug)) }).from(environments).orderBy(asc(environments.id)),
103
+ ]);
104
+ return found.filter((project) => !project.deleted).map((project) => ({
105
+ id: project.id,
106
+ environments: inside.filter((environment) => environment.projectId === project.id && !environment.deleted).map(({ id, slug }) => ({ id, slug })),
107
+ }));
108
+ }
109
+
110
+ /**
111
+ * What the vault makes of a member's grants on every project of 0.4
112
+ * (`convertEveryProjectGrants`), from their instance role and their grants
113
+ * as stored, those live at `at`: the vault as it converts them, under their
114
+ * row's lock, and `coffre migrate` before, from the rows as they are. The
115
+ * role is the one their row holds: the vault converts these before it makes
116
+ * the Owners its deployment names.
117
+ */
118
+ export function everyProjectConversion(
119
+ principal: string,
120
+ role: InstanceRole,
121
+ grants: readonly GrantRow[],
122
+ at: number,
123
+ projects: ConversionInput['projects'],
124
+ ): Conversion {
125
+ const person = principal.startsWith('user:');
126
+ const live = grants.filter((grant) => grant.expiresAt === null || grant.expiresAt > at);
127
+ return convertEveryProjectGrants({
128
+ person,
129
+ role: person ? role : 'member',
130
+ everyProject: live
131
+ .filter((grant) => grant.projectId === null && grant.environmentId === null)
132
+ .map((grant) => ({ environmentSlug: grant.environmentSlug, role: grant.role as Role, expiresAt: grant.expiresAt })),
133
+ grants: live
134
+ .filter((grant) => grant.projectId !== null)
135
+ .map((grant) => ({ projectId: grant.projectId, environmentId: grant.environmentId, role: grant.role as Role, expiresAt: grant.expiresAt })),
136
+ projects,
137
+ });
138
+ }
139
+
96
140
  /** What the vault does, when this version first runs, to one member's grants on every project of 0.4. */
97
141
  export type EveryProjectPreview = {
98
142
  principal: string;
@@ -120,28 +164,23 @@ export type EveryProjectPreview = {
120
164
  * `reported`, by the vault's own rule (`tamperedMembers`) over the entries as
121
165
  * they read: whether that report is the vault's own, or forged so as to
122
166
  * hide what it will do, only the vault can tell. Any member the vault
123
- * converts is listed. A root admin's it leaves while they are one, until
124
- * they are not; which they are, the vault's configuration says and the
125
- * database does not, so they are listed too.
167
+ * converts is listed.
126
168
  */
127
169
  export async function everyProjectPreview(db: Queryable, at: number): Promise<EveryProjectPreview[]> {
128
170
  const { vaultMembers, projects, environments } = tablesOf(db);
129
- const held = (await readGrants(db, { liveAt: at })).filter((grant) => grant.projectId === null && grant.environmentId === null);
171
+ const grants = await readGrants(db, { liveAt: at });
172
+ const held = grants.filter((grant) => grant.projectId === null && grant.environmentId === null);
130
173
  if (held.length === 0) return [];
131
174
  const holders = [...new Set(held.map((grant) => grant.principal))].sort();
132
- const [members, grants, places, inside, tampered] = await Promise.all([
175
+ const [members, places, inside, live, tampered] = await Promise.all([
133
176
  db.select({ principal: vaultMembers.principal, status: vaultMembers.status, owner: vaultMembers.owner, role: vaultMembers.role, scope: vaultMembers.scope }).from(vaultMembers),
134
- readGrants(db, { liveAt: at }),
135
177
  db.select({ id: projects.id, slug: projects.slug }).from(projects),
136
178
  db.select({ id: environments.id, projectId: environments.projectId, slug: environments.slug }).from(environments),
179
+ liveProjects(db),
137
180
  // The vault's own rule (`reportStands`), over every entry in its name, for everyone in two queries.
138
181
  tamperedMembers(db),
139
182
  ]);
140
- // A deleted place keeps its row under a tombstone's slug, its own or its project's: no grant reaches it.
141
- const live = places.filter((project) => !isTombstone(project.slug)).map((project) => ({
142
- id: project.id,
143
- environments: inside.filter((environment) => environment.projectId === project.id && !isTombstone(environment.slug)).map(({ id, slug }) => ({ id, slug })),
144
- }));
183
+ // A deleted place keeps its row under a tombstone's slug, its own or its project's, named as it was.
145
184
  const paths = Object.fromEntries(places.flatMap((project) => [
146
185
  [project.id, project.slug],
147
186
  ...inside.filter((environment) => environment.projectId === project.id).map((environment) => [environment.id, `${project.slug}/${environment.slug}`]),
@@ -153,15 +192,7 @@ export async function everyProjectPreview(db: Queryable, at: number): Promise<Ev
153
192
  return [{
154
193
  principal,
155
194
  before: theirs.map((grant) => ({ place: grant.environmentSlug === null ? '*' : `*/${grant.environmentSlug}`, role: grant.role, expiresAt: grant.expiresAt })),
156
- conversion: convertEveryProjectGrants({
157
- person: principal.startsWith('user:'),
158
- role: principal.startsWith('user:') ? storedRole(member).role : 'member',
159
- everyProject: theirs.map((grant) => ({ environmentSlug: grant.environmentSlug, role: grant.role as Role, expiresAt: grant.expiresAt })),
160
- grants: grants
161
- .filter((grant) => grant.principal === principal && grant.projectId !== null)
162
- .map((grant) => ({ projectId: grant.projectId, environmentId: grant.environmentId, role: grant.role as Role, expiresAt: grant.expiresAt })),
163
- projects: live,
164
- }),
195
+ conversion: everyProjectConversion(principal, storedRole(member).role, grants.filter((grant) => grant.principal === principal), at, live),
165
196
  paths,
166
197
  reported: tampered.has(principal),
167
198
  }];
package/src/log.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { GENESIS_HASH, sealEntry, type LogFields, type LogKey, type StoredEntry } from '@coffre/core/audit';
2
- import { desc, eq } from 'drizzle-orm';
2
+ import { and, desc, eq, lt } from 'drizzle-orm';
3
3
 
4
4
  import { afterCommit } from './commits.ts';
5
5
  import { tablesOf, type Queryable, type Transaction } from './database.ts';
@@ -225,6 +225,25 @@ export function entryColumns(db: Queryable) {
225
225
  */
226
226
  export type Authenticity = { authentic: (entry: StoredEntry) => boolean; forged: (entry: StoredEntry) => void };
227
227
 
228
+ /** Up to `limit` of the entries in the vault's name, allowed, of one `action`, before `before` (the newest when undefined), newest first. */
229
+ export async function newestVaultEntries(db: Queryable, action: string, limit: number, before?: bigint): Promise<StoredEntry[]> {
230
+ const { auditLog } = tablesOf(db);
231
+ const rows = await db
232
+ .select(entryColumns(db))
233
+ .from(auditLog)
234
+ .where(
235
+ and(
236
+ eq(auditLog.author, 'vault'),
237
+ eq(auditLog.action, action),
238
+ eq(auditLog.decision, 'allow'),
239
+ before === undefined ? undefined : lt(auditLog.seq, before),
240
+ ),
241
+ )
242
+ .orderBy(desc(auditLog.seq))
243
+ .limit(limit);
244
+ return rows as StoredEntry[];
245
+ }
246
+
228
247
  /** How many entries in its name the vault reads back, a page at a time, for its own newest of a kind (`newestAuthentic`). */
229
248
  export const LOOK_BACK = { page: 32, pages: 32 };
230
249
 
package/src/schema.ts CHANGED
@@ -205,8 +205,7 @@ export const vaultMembers = pgTable(
205
205
  principal: text().primaryKey(),
206
206
  status: text().notNull(),
207
207
  // An owner of 0.4: an Admin, unless `role` says otherwise. Written as
208
- // whether `role` administers, for a vault of 0.4 to read. Root admins
209
- // come from the vault's configuration, never from a row.
208
+ // whether `role` administers, for a vault of 0.4 to read.
210
209
  owner: boolean().notNull().default(false),
211
210
  // A person's instance role (`INSTANCE_ROLES` in @coffre/core/access),
212
211
  // and where it applies, as JSON (`Scope`, projects by id); null on a row