@coffre/db 0.14.3 → 0.14.5

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.
Files changed (36) hide show
  1. package/dist/connect.d.ts +1 -1
  2. package/dist/{database-Ds1Y79h6.d.ts → database-wq1AVRAP.d.ts} +1 -1
  3. package/dist/dialect.d.ts +1 -1
  4. package/dist/grants.d.ts +1 -1
  5. package/dist/hyperdrive.d.ts +1 -1
  6. package/dist/index.d.ts +2 -2
  7. package/dist/log.d.ts +27 -1
  8. package/dist/log.js +50 -1
  9. package/dist/migrations/postgres/0020_vault_releases.sql +36 -0
  10. package/dist/migrations/postgres/0021_prune_vault_releases.sql +19 -0
  11. package/dist/migrations/postgres/meta/0020_snapshot.json +3334 -0
  12. package/dist/migrations/postgres/meta/0021_snapshot.json +3334 -0
  13. package/dist/migrations/postgres/meta/_journal.json +14 -0
  14. package/dist/migrations/sqlite/0017_vault_releases.sql +26 -0
  15. package/dist/migrations/sqlite/meta/0017_snapshot.json +3037 -0
  16. package/dist/migrations/sqlite/meta/_journal.json +7 -0
  17. package/dist/portable.d.ts +2 -2
  18. package/dist/{schema-DcVkJhCf.d.ts → schema-BfQEBqFv.d.ts} +73 -2
  19. package/dist/schema-sqlite.d.ts +75 -1
  20. package/dist/schema-sqlite.js +21 -1
  21. package/dist/schema-version.d.ts +1 -1
  22. package/dist/schema-version.js +21 -0
  23. package/dist/schema.d.ts +2 -2
  24. package/dist/schema.js +24 -2
  25. package/package.json +2 -2
  26. package/src/log.ts +52 -0
  27. package/src/migrations/postgres/0020_vault_releases.sql +36 -0
  28. package/src/migrations/postgres/0021_prune_vault_releases.sql +19 -0
  29. package/src/migrations/postgres/meta/0020_snapshot.json +3334 -0
  30. package/src/migrations/postgres/meta/0021_snapshot.json +3334 -0
  31. package/src/migrations/postgres/meta/_journal.json +14 -0
  32. package/src/migrations/sqlite/0017_vault_releases.sql +26 -0
  33. package/src/migrations/sqlite/meta/0017_snapshot.json +3037 -0
  34. package/src/migrations/sqlite/meta/_journal.json +7 -0
  35. package/src/schema.sqlite.ts +22 -0
  36. package/src/schema.ts +25 -0
package/dist/connect.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { t as Database } from "./database-Ds1Y79h6.js";
1
+ import { t as Database } from "./database-wq1AVRAP.js";
2
2
  import { Engine } from "./dialect.js";
3
3
  import { ClientConfig } from "pg";
4
4
  //#region src/postgres.d.ts
@@ -1,4 +1,4 @@
1
- import { g as schema_d_exports } from "./schema-DcVkJhCf.js";
1
+ import { g as schema_d_exports } from "./schema-BfQEBqFv.js";
2
2
  import { Query, Table } from "drizzle-orm";
3
3
  import { NodePgDatabase } from "drizzle-orm/node-postgres";
4
4
  import pg from "pg";
package/dist/dialect.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { i as Queryable } from "./database-Ds1Y79h6.js";
1
+ import { i as Queryable } from "./database-wq1AVRAP.js";
2
2
  import { SQL, SQLWrapper } from "drizzle-orm";
3
3
  import { PgTable } from "drizzle-orm/pg-core";
4
4
  //#region src/dialect.d.ts
package/dist/grants.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { i as Queryable } from "./database-Ds1Y79h6.js";
1
+ import { i as Queryable } from "./database-wq1AVRAP.js";
2
2
  import { Authenticity, Newest } from "./log.js";
3
3
  import { StoredEntry } from "@coffre/core/audit";
4
4
  import { Conversion, ConversionInput, InstanceRole, Scope } from "@coffre/core/access";
@@ -1,4 +1,4 @@
1
- import { n as PoolLike } from "./database-Ds1Y79h6.js";
1
+ import { n as PoolLike } from "./database-wq1AVRAP.js";
2
2
  import pg from "pg";
3
3
  //#region src/hyperdrive.d.ts
4
4
  /** Postgres through a Hyperdrive binding: `postgres(env.HYPERDRIVE)`. */
package/dist/index.d.ts CHANGED
@@ -1,3 +1,3 @@
1
- import { g as schema_d_exports } from "./schema-DcVkJhCf.js";
2
- import { a as Transaction, c as tablesOf, i as Queryable, l as prepared, n as PoolLike, o as createDatabase, r as QueryOutsideTransaction, s as own, t as Database } from "./database-Ds1Y79h6.js";
1
+ import { g as schema_d_exports } from "./schema-BfQEBqFv.js";
2
+ import { a as Transaction, c as tablesOf, i as Queryable, l as prepared, n as PoolLike, o as createDatabase, r as QueryOutsideTransaction, s as own, t as Database } from "./database-wq1AVRAP.js";
3
3
  export { Database, PoolLike, QueryOutsideTransaction, Queryable, Transaction, createDatabase, own, prepared, schema_d_exports as schema, tablesOf };
package/dist/log.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { a as Transaction, i as Queryable } from "./database-Ds1Y79h6.js";
1
+ import { a as Transaction, i as Queryable } from "./database-wq1AVRAP.js";
2
2
  import { Placeholder, SQL } from "drizzle-orm";
3
3
  import { LogKey, StoredEntry } from "@coffre/core/audit";
4
4
  //#region src/log.d.ts
@@ -48,6 +48,16 @@ export type Appended = {
48
48
  export declare class LogHeadMismatch extends Error {
49
49
  constructor(message: string);
50
50
  }
51
+ /**
52
+ * As many transactions as may already wait for the log's head do
53
+ * (`lockLogHeadQueued`): this one waits for nothing, and holds nothing.
54
+ * Its code is Postgres's for a lock not available, so every caller already
55
+ * answers it as one that gave up waiting: unavailable, ask again shortly.
56
+ */
57
+ export declare class HeadBusy extends Error {
58
+ readonly code = "55P03";
59
+ constructor();
60
+ }
51
61
  /**
52
62
  * The log's head is behind one this process wrote: the database was rolled
53
63
  * back, or entries were cut off its end. That cannot be told from a restore,
@@ -92,6 +102,22 @@ export declare function lockLogHead(tx: Transaction): Promise<{
92
102
  * SQLite's transactions hold the whole file, so the head is always free.
93
103
  */
94
104
  export declare function lockLogHeadIfFree(tx: Transaction): Promise<boolean>;
105
+ /**
106
+ * Lock the log's head, waiting for it as `lockLogHead` does, if fewer than
107
+ * `waiters` other transactions hold one of its places in line; otherwise
108
+ * refuse at once (`HeadBusy`), having waited for nothing. A place is an
109
+ * advisory lock, tried, never waited for, and held to the end of the
110
+ * transaction, which holds the head by then: so at most `waiters`
111
+ * connections wait for the head, or hold it, through here, and a burst
112
+ * beyond them answers in one round trip rather than seconds later, holding
113
+ * a connection all the while. One statement: the place, then, only if one
114
+ * was free, the head; refused, one more says whether the head is there at
115
+ * all. SQLite's transactions hold the whole file.
116
+ */
117
+ export declare function lockLogHeadQueued(tx: Transaction, waiters: number): Promise<{
118
+ nextSeq: bigint;
119
+ headHash: Buffer;
120
+ }>;
95
121
  /**
96
122
  * Append `entries` under `key`. `check`, when given, runs once the head is
97
123
  * locked and before anything is written: a writer's own condition on the
package/dist/log.js CHANGED
@@ -12,6 +12,19 @@ var LogHeadMismatch = class extends Error {
12
12
  }
13
13
  };
14
14
  /**
15
+ * As many transactions as may already wait for the log's head do
16
+ * (`lockLogHeadQueued`): this one waits for nothing, and holds nothing.
17
+ * Its code is Postgres's for a lock not available, so every caller already
18
+ * answers it as one that gave up waiting: unavailable, ask again shortly.
19
+ */
20
+ var HeadBusy = class extends Error {
21
+ code = "55P03";
22
+ constructor() {
23
+ super("too many requests wait for the audit log's head: ask again shortly");
24
+ this.name = "HeadBusy";
25
+ }
26
+ };
27
+ /**
15
28
  * The log's head is behind one this process wrote: the database was rolled
16
29
  * back, or entries were cut off its end. That cannot be told from a restore,
17
30
  * so the append refuses and someone has to look.
@@ -99,6 +112,42 @@ async function lockLogHeadIfFree(tx) {
99
112
  if (rows.length > 0) holding.add(tx);
100
113
  return rows.length > 0;
101
114
  }
115
+ /**
116
+ * Lock the log's head, waiting for it as `lockLogHead` does, if fewer than
117
+ * `waiters` other transactions hold one of its places in line; otherwise
118
+ * refuse at once (`HeadBusy`), having waited for nothing. A place is an
119
+ * advisory lock, tried, never waited for, and held to the end of the
120
+ * transaction, which holds the head by then: so at most `waiters`
121
+ * connections wait for the head, or hold it, through here, and a burst
122
+ * beyond them answers in one round trip rather than seconds later, holding
123
+ * a connection all the while. One statement: the place, then, only if one
124
+ * was free, the head; refused, one more says whether the head is there at
125
+ * all. SQLite's transactions hold the whole file.
126
+ */
127
+ async function lockLogHeadQueued(tx, waiters) {
128
+ if (engineOf(tx) === "sqlite") return lockLogHead(tx);
129
+ const { rows } = await tx.execute(sql`
130
+ SELECT next_seq, head_hash FROM audit_chain_head
131
+ WHERE only_row AND (SELECT true FROM generate_series(1, ${waiters}::int) AS place WHERE pg_try_advisory_xact_lock(${HEAD_LINE}, place) LIMIT 1)
132
+ FOR UPDATE`);
133
+ const [head] = rows;
134
+ if (head === void 0) {
135
+ const { rows: [found] } = await tx.execute(sql`SELECT EXISTS (SELECT 1 FROM audit_chain_head WHERE only_row) AS found`);
136
+ if (found?.found !== true) throw new Error("audit_chain_head is missing; refusing to write an unchained entry");
137
+ throw new HeadBusy();
138
+ }
139
+ holding.add(tx);
140
+ return {
141
+ nextSeq: BigInt(head.next_seq),
142
+ headHash: head.head_hash
143
+ };
144
+ }
145
+ /**
146
+ * The first key of the head's places in line, Postgres's advisory locks:
147
+ * the second is the place. A space apart from the members' queues and the
148
+ * migrator's key.
149
+ */
150
+ const HEAD_LINE = 1668245096;
102
151
  const lockedHead = prepared((db) => {
103
152
  const { auditChainHead } = tablesOf(db);
104
153
  return forUpdate(db, db.select({
@@ -388,4 +437,4 @@ async function newestAuthentic(page, check) {
388
437
  return "unreached";
389
438
  }
390
439
  //#endregion
391
- export { BATCH_BYTES, KeyRetired, LOOK_BACK, LogHeadMismatch, LogRewound, MOVES_FROM, appendEntries, entryColumns, forgetLogHeads, lockLogHead, lockLogHeadIfFree, missingEntry, newestAuthentic, newestSeqQuery, newestVaultEntries, newestVaultSeq, withinBytes };
440
+ export { BATCH_BYTES, HeadBusy, KeyRetired, LOOK_BACK, LogHeadMismatch, LogRewound, MOVES_FROM, appendEntries, entryColumns, forgetLogHeads, lockLogHead, lockLogHeadIfFree, lockLogHeadQueued, missingEntry, newestAuthentic, newestSeqQuery, newestVaultEntries, newestVaultSeq, withinBytes };
@@ -0,0 +1,36 @@
1
+ -- Releases (W199): each key the vault released to a principal, and when last, so that its bulk limit counts the keys released within a window from a row per key, not from every read the principal ever made. The database keeps it, from each vault `secret.read` allowed, in the append's own transaction; the release before neither reads it nor knows it is kept, and its appends keep it too.
2
+ CREATE TABLE "vault_releases" (
3
+ "principal" text NOT NULL,
4
+ "key" text NOT NULL,
5
+ "released_at" bigint NOT NULL,
6
+ CONSTRAINT "vault_releases_pkey" PRIMARY KEY("principal","key")
7
+ );
8
+ --> statement-breakpoint
9
+ -- Room in each page for the next version of its rows: a read moves its keys' times on in place (a HOT update), so the
10
+ -- table and its key stay a row a key, however often each is read: the page prunes the versions before as it is read.
11
+ ALTER TABLE vault_releases SET (fillfactor = 50);--> statement-breakpoint
12
+ -- Each key the entry names, as the count read them before: the secret, or each item of a read's list at one place, or, for an entry that names none, which only a forged one is, the entry itself. As the owner, so that no login may write the table: the vault's appends reach it only through the log.
13
+ CREATE FUNCTION vault_releases_keep() RETURNS trigger
14
+ LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, pg_temp AS $$
15
+ BEGIN
16
+ INSERT INTO public.vault_releases AS kept (principal, key, released_at)
17
+ SELECT DISTINCT NEW.actor, coalesce(NEW.secret_id::text, CASE jsonb_typeof(one -> 'secretId') WHEN 'string' THEN one ->> 'secretId' END, 'entry:' || NEW.seq), NEW.occurred_at
18
+ FROM (SELECT) AS entry
19
+ LEFT JOIN LATERAL jsonb_path_query(CASE WHEN NEW.secret_id IS NULL THEN NEW.metadata::jsonb END, 'strict $.secrets ? (@.type() == "array")[*]', '{}', true) AS one ON true
20
+ ON CONFLICT (principal, key) DO UPDATE SET released_at = greatest(kept.released_at, excluded.released_at);
21
+ RETURN NULL;
22
+ END
23
+ $$;--> statement-breakpoint
24
+ -- A trigger runs its function whoever may execute it: no login may call it otherwise.
25
+ REVOKE ALL ON FUNCTION vault_releases_keep() FROM PUBLIC;--> statement-breakpoint
26
+ CREATE TRIGGER audit_log_releases AFTER INSERT ON audit_log FOR EACH ROW
27
+ WHEN (NEW.author = 'vault' AND NEW.action = 'secret.read' AND NEW.decision = 'allow')
28
+ EXECUTE FUNCTION vault_releases_keep();--> statement-breakpoint
29
+ -- Then the releases already in the log, in the same transaction: an append waits from the trigger to the commit, and none is missed.
30
+ INSERT INTO vault_releases (principal, key, released_at)
31
+ SELECT e.actor, coalesce(e.secret_id::text, CASE jsonb_typeof(one -> 'secretId') WHEN 'string' THEN one ->> 'secretId' END, 'entry:' || e.seq), max(e.occurred_at)
32
+ FROM audit_log e
33
+ LEFT JOIN LATERAL jsonb_path_query(CASE WHEN e.secret_id IS NULL THEN e.metadata::jsonb END, 'strict $.secrets ? (@.type() == "array")[*]', '{}', true) AS one ON true
34
+ WHERE e.author = 'vault' AND e.action = 'secret.read' AND e.decision = 'allow'
35
+ GROUP BY 1, 2;--> statement-breakpoint
36
+ GRANT SELECT ON vault_releases TO coffre_vault, coffre_backup;
@@ -0,0 +1,19 @@
1
+ -- Releases pruned (W199, T111): the vault's checkpoint forgets the releases no window can count again, those over a day and an hour old by the database's clock, at most at_most a call. A bulk limit's window is a day at most (the vault's config), and the hour is a margin for the clock stepping back: no caller chooses what is kept, so the vault's login, which still deletes no row itself, cannot forget a release a window counts. The release before never calls it.
2
+ CREATE FUNCTION prune_vault_releases(at_most integer) RETURNS integer
3
+ LANGUAGE sql SECURITY DEFINER SET search_path = pg_catalog, pg_temp SET lock_timeout = '3s' AS $$
4
+ -- The bound in the DELETE's own WHERE too: a row a read moved on since the subquery's snapshot is checked again,
5
+ -- as it is now, and kept.
6
+ WITH bound AS (SELECT (extract(epoch from clock_timestamp()) * 1000)::bigint - 25 * 3600000 AS before),
7
+ pruned AS (
8
+ DELETE FROM public.vault_releases
9
+ WHERE released_at < (SELECT before FROM bound)
10
+ AND ctid IN (
11
+ -- Any of them, each past every window; a row an append holds is left to the next run, rather than waited for.
12
+ SELECT ctid FROM public.vault_releases WHERE released_at < (SELECT before FROM bound) LIMIT at_most FOR UPDATE SKIP LOCKED
13
+ )
14
+ RETURNING 1
15
+ )
16
+ SELECT count(*)::integer FROM pruned;
17
+ $$;--> statement-breakpoint
18
+ REVOKE ALL ON FUNCTION prune_vault_releases(integer) FROM PUBLIC;--> statement-breakpoint
19
+ GRANT EXECUTE ON FUNCTION prune_vault_releases(integer) TO coffre_vault;