@sentropic/artifacts 0.2.27 → 0.2.28

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/CHANGELOG.md CHANGED
@@ -1,5 +1,14 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.2.28
4
+
5
+ - Add DB blob placement: migration `0014_db_blob_placement.sql` (`placement`, `blob_bytes`,
6
+ `upload_staging_bytes`), `db-blob` and `composite-blob` adapters with advisory digest-lock
7
+ coordination, and placement-aware publication writes with keyset-paged blob enumeration.
8
+ - Harden the blob bridge: create-only verified S3/local puts, bounded pages with sealed
9
+ keyset cursors, and store-level `listKeysPaged` delegation.
10
+ - Stays in `0.2.x` (cluster-mesh peer `>=0.2.0 <0.3.0`).
11
+
3
12
  ## 0.2.27
4
13
 
5
14
  - Wire the builder terminal failure through the live package: a `reconcile` answer with
@@ -0,0 +1,35 @@
1
+ /**
2
+ * CMF-S2 — composite `db+s3` blob adapter.
3
+ *
4
+ * Routes new `putBlob` keys by mode and size (`db`: DB, `s3`: object,
5
+ * `db+s3`: DB at or below the inline threshold, object above), preserves
6
+ * registered placement on rewrites, and resolves reads
7
+ * through the registered `artifacts.blobs.placement` (probing DB then object
8
+ * for prepared-but-unfinalized blobs), and coordinates `deleteBlob` across
9
+ * both sides under the caller's digest lock so neither an orphan DB row nor
10
+ * an orphan object survives GC. Enumeration is the ordered union; bounded
11
+ * pages merge both sides by keyset resume under one sealed continuation
12
+ * (`listKeysPaged`, CR-4) so no side is ever bulk-loaded.
13
+ */
14
+ import type { PublicationBlobStore } from '../server/publication.js';
15
+ import type { FinalizeTxClient } from '../server/commit/types.js';
16
+ export type CompositeBlobMode = 'db' | 's3' | 'db+s3';
17
+ export type RegisteredBlobPlacement = 'db' | 'object';
18
+ export interface CompositeBlobPlacements {
19
+ /** Registered placement of a finalized blob; undefined before finalization. */
20
+ getPlacement(key: string): Promise<RegisteredBlobPlacement | undefined>;
21
+ }
22
+ export interface CompositeBlobOptions {
23
+ readonly db: PublicationBlobStore;
24
+ readonly s3: PublicationBlobStore;
25
+ readonly mode: CompositeBlobMode;
26
+ /** `db+s3` only: blobs at or below this byte size land in the DB. */
27
+ readonly inlineMaxBytes: number;
28
+ readonly placements: CompositeBlobPlacements;
29
+ /** Runs work under the digest lock shared with GC; direct when absent. */
30
+ readonly withDigestLock?: (digest: string, work: () => Promise<void>, transaction?: FinalizeTxClient) => Promise<void>;
31
+ }
32
+ /** Pure routing decision, shared with the publication promotion path. */
33
+ export declare function placementForPut(mode: CompositeBlobMode, sizeBytes: number, inlineMaxBytes: number): RegisteredBlobPlacement;
34
+ /** Create the composite blob store (no env reads, no connections). */
35
+ export declare function createCompositeBlobStore(options: CompositeBlobOptions): PublicationBlobStore;
@@ -0,0 +1,106 @@
1
+ function digestOfKey(key) {
2
+ const hex = key.split('/').pop() ?? '';
3
+ if (!/^[0-9a-f]{64}$/.test(hex))
4
+ throw new Error(`invalid blob key: ${key}`);
5
+ return `sha256:${hex}`;
6
+ }
7
+ /** Pure routing decision, shared with the publication promotion path. */
8
+ export function placementForPut(mode, sizeBytes, inlineMaxBytes) {
9
+ if (mode === 'db')
10
+ return 'db';
11
+ if (mode === 's3')
12
+ return 'object';
13
+ if (!Number.isSafeInteger(inlineMaxBytes) || inlineMaxBytes < 1)
14
+ throw new Error('invalid inline max bytes');
15
+ return sizeBytes <= inlineMaxBytes ? 'db' : 'object';
16
+ }
17
+ /** Create the composite blob store (no env reads, no connections). */
18
+ export function createCompositeBlobStore(options) {
19
+ const { db, s3, mode, inlineMaxBytes, placements } = options;
20
+ if (mode !== 'db' && mode !== 's3' && mode !== 'db+s3')
21
+ throw new Error(`invalid blob placement mode: ${mode}`);
22
+ const lock = options.withDigestLock ?? (async (_digest, work) => { await work(); });
23
+ return {
24
+ async putBlob(key, bytes) {
25
+ // Registration survives collection; retries must restore its readable side.
26
+ const placement = await placements.getPlacement(key) ?? placementForPut(mode, bytes.byteLength, inlineMaxBytes);
27
+ const target = placement === 'db' ? db : s3;
28
+ await target.putBlob(key, bytes);
29
+ },
30
+ async getBlob(key) {
31
+ const placement = await placements.getPlacement(key);
32
+ if (placement === 'db')
33
+ return db.getBlob(key);
34
+ if (placement === 'object')
35
+ return s3.getBlob(key);
36
+ return (await db.getBlob(key)) ?? s3.getBlob(key);
37
+ },
38
+ async getBlobRange(key, start, endInclusive) {
39
+ const placement = await placements.getPlacement(key);
40
+ if (placement === 'db')
41
+ return db.getBlobRange?.(key, start, endInclusive);
42
+ if (placement === 'object')
43
+ return s3.getBlobRange?.(key, start, endInclusive);
44
+ return (await db.getBlobRange?.(key, start, endInclusive)) ??
45
+ s3.getBlobRange?.(key, start, endInclusive);
46
+ },
47
+ async listKeys(prefix) {
48
+ const [fromDb, fromS3] = await Promise.all([db.listKeys(prefix), s3.listKeys(prefix)]);
49
+ return [...new Set([...fromDb, ...fromS3])].sort();
50
+ },
51
+ async listKeysPaged(prefix, page) {
52
+ // Ordered union over one shared keyset resume: both sides fetch their
53
+ // first `maxItems` keys after the same resume key, which always covers
54
+ // the union's first `maxItems` keys (a union member ranks no higher in
55
+ // its own side than in the union). Bounded per side, no bulk load; the
56
+ // bridge applies the byte budget and seals the single resume key.
57
+ if (!Number.isSafeInteger(page.maxItems) || page.maxItems < 1)
58
+ throw new Error('invalid blob page maxItems');
59
+ const sides = [db, s3];
60
+ const fetched = await Promise.all(sides.map(async (side) => {
61
+ const input = page.startAfter === undefined
62
+ ? { maxItems: page.maxItems, maxEncodedBytes: page.maxEncodedBytes }
63
+ : { maxItems: page.maxItems, maxEncodedBytes: page.maxEncodedBytes, startAfter: page.startAfter };
64
+ if (side.listKeysPaged !== undefined)
65
+ return side.listKeysPaged(prefix, input);
66
+ const all = (await side.listKeys(prefix)).filter((key) => key.startsWith(prefix)).sort();
67
+ const start = page.startAfter === undefined ? 0 : (() => {
68
+ const index = all.findIndex((key) => key > page.startAfter);
69
+ return index === -1 ? all.length : index;
70
+ })();
71
+ const keys = all.slice(start, start + page.maxItems);
72
+ return { keys, hasMore: start + page.maxItems < all.length };
73
+ }));
74
+ const seen = new Set();
75
+ for (const result of fetched) {
76
+ for (const key of result.keys)
77
+ seen.add(key);
78
+ }
79
+ const union = [...seen].sort();
80
+ const keys = union.slice(0, page.maxItems);
81
+ const hasMore = fetched.some((result) => result.hasMore) || union.length > page.maxItems;
82
+ return { keys, hasMore };
83
+ },
84
+ async deleteBlob(key, transaction) {
85
+ await lock(digestOfKey(key), async () => {
86
+ // Deferred per side: a synchronously-throwing store (unknown key)
87
+ // must settle as a rejection inside allSettled, never escape during
88
+ // argument evaluation and leave the other side floating unawaited.
89
+ const attempt = async (side) => {
90
+ await side.deleteBlob(key);
91
+ };
92
+ const outcomes = await Promise.allSettled([attempt(db), attempt(s3)]);
93
+ for (const outcome of outcomes) {
94
+ if (outcome.status === 'rejected' &&
95
+ !(outcome.reason instanceof Error && outcome.reason.message === `unknown blob: ${key}`) &&
96
+ outcome.reason?.name !== 'NoSuchKey' && outcome.reason?.name !== 'NotFound') {
97
+ throw outcome.reason;
98
+ }
99
+ }
100
+ if (outcomes.every((outcome) => outcome.status === 'rejected')) {
101
+ throw outcomes[0].reason;
102
+ }
103
+ }, transaction);
104
+ },
105
+ };
106
+ }
@@ -0,0 +1,14 @@
1
+ /**
2
+ * CMF-S2 — Postgres DB blob placement (`artifacts.blob_bytes`).
3
+ *
4
+ * DB-mode `ArtifactBlobPort`: digest-addressed blobs in the `blob_bytes`
5
+ * table (no FK to `artifacts.blobs`, so preparation-phase puts succeed before
6
+ * `registerBlob`). Create-only (`ON CONFLICT DO NOTHING`) + read-back
7
+ * verification: identical retries are idempotent, different bytes fail closed
8
+ * without overwriting. The runtime role holds SELECT + INSERT only; DELETE
9
+ * belongs to the lifecycle maintenance role (CR-5).
10
+ */
11
+ import type { Pool } from 'pg';
12
+ import type { PublicationBlobStore } from '../server/publication.js';
13
+ /** Create a DB-backed blob store over an injected pg pool (no env reads). */
14
+ export declare function createPostgresDbBlobStore(pool: Pool): PublicationBlobStore;
@@ -0,0 +1,79 @@
1
+ import { assertBlobPrefix } from '../server/blob-prefix.js';
2
+ import { cloneBlobBytes, verifyBytesForKey, verifyStoredBytesForKey } from '../server/blob-bridge.js';
3
+ /** Per-call fetch cap: one page never materializes more than this. */
4
+ const PAGE_FETCH_CAP = 1000;
5
+ const BLOB_KEY_PATTERN = /^artifacts\/([A-Za-z0-9_-]+)\/blobs\/sha256\/([0-9a-f]{64})$/;
6
+ const SCOPE_PREFIX_PATTERN = /^artifacts\/([A-Za-z0-9_-]+)\/blobs\/sha256\//;
7
+ function splitKey(key) {
8
+ const match = BLOB_KEY_PATTERN.exec(key);
9
+ if (!match)
10
+ throw new Error(`invalid blob key: ${key}`);
11
+ return { scope: match[1], digest: `sha256:${match[2]}` };
12
+ }
13
+ /** Create a DB-backed blob store over an injected pg pool (no env reads). */
14
+ export function createPostgresDbBlobStore(pool) {
15
+ return {
16
+ async putBlob(key, bytes) {
17
+ const snapshot = cloneBlobBytes(bytes);
18
+ verifyBytesForKey(key, snapshot);
19
+ const { scope, digest } = splitKey(key);
20
+ await pool.query(`INSERT INTO artifacts.blob_bytes (storage_scope_id, digest, bytes) VALUES ($1, $2, $3)
21
+ ON CONFLICT (storage_scope_id, digest) DO NOTHING`, [scope, digest, Buffer.from(snapshot)]);
22
+ const stored = await this.getBlob(key);
23
+ if (stored === undefined)
24
+ throw new Error(`blob missing after write: ${key}`);
25
+ },
26
+ async getBlob(key) {
27
+ const { scope, digest } = splitKey(key);
28
+ const { rows } = await pool.query('SELECT bytes FROM artifacts.blob_bytes WHERE storage_scope_id = $1 AND digest = $2', [scope, digest]);
29
+ if (rows[0] === undefined)
30
+ return undefined;
31
+ return verifyStoredBytesForKey(key, new Uint8Array(rows[0].bytes));
32
+ },
33
+ async getBlobRange(key, start, endInclusive) {
34
+ const stored = await this.getBlob(key);
35
+ if (stored === undefined || !Number.isSafeInteger(start) || !Number.isSafeInteger(endInclusive) ||
36
+ start < 0 || endInclusive < start)
37
+ return undefined;
38
+ return stored.slice(start, Math.min(endInclusive + 1, stored.length));
39
+ },
40
+ async listKeys(prefix) {
41
+ assertBlobPrefix(prefix);
42
+ const match = SCOPE_PREFIX_PATTERN.exec(prefix);
43
+ if (!match)
44
+ throw new Error(`blob listing requires a scope prefix: ${prefix}`);
45
+ const { rows } = await pool.query('SELECT digest FROM artifacts.blob_bytes WHERE storage_scope_id = $1 ORDER BY digest', [match[1]]);
46
+ return rows
47
+ .map((row) => `artifacts/${match[1]}/blobs/sha256/${row.digest.slice('sha256:'.length)}`)
48
+ .filter((key) => key.startsWith(prefix))
49
+ .sort();
50
+ },
51
+ async deleteBlob(key) {
52
+ const { scope, digest } = splitKey(key);
53
+ const result = await pool.query('DELETE FROM artifacts.blob_bytes WHERE storage_scope_id = $1 AND digest = $2', [scope, digest]);
54
+ if (result.rowCount === 0)
55
+ throw new Error(`unknown blob: ${key}`);
56
+ },
57
+ async listKeysPaged(prefix, page) {
58
+ assertBlobPrefix(prefix);
59
+ const match = SCOPE_PREFIX_PATTERN.exec(prefix);
60
+ if (!match)
61
+ throw new Error(`blob listing requires a scope prefix: ${prefix}`);
62
+ if (!Number.isSafeInteger(page.maxItems) || page.maxItems < 1)
63
+ throw new Error('invalid blob page maxItems');
64
+ const after = page.startAfter === undefined ? undefined : (() => {
65
+ if (!page.startAfter.startsWith(prefix))
66
+ throw new Error(`invalid blob page resume key: ${page.startAfter}`);
67
+ return splitKey(page.startAfter).digest;
68
+ })();
69
+ const limit = Math.min(page.maxItems + 1, PAGE_FETCH_CAP);
70
+ const { rows } = await pool.query(`SELECT digest FROM artifacts.blob_bytes WHERE storage_scope_id = $1
71
+ AND substr(digest, 1, length($2::text)) = $2
72
+ AND ($3::text IS NULL OR digest > $3) ORDER BY digest LIMIT $4`, [match[1], `sha256:${prefix.slice(match[0].length)}`, after ?? null, limit]);
73
+ const keys = rows.map((row) => `artifacts/${match[1]}/blobs/sha256/${row.digest.slice('sha256:'.length)}`)
74
+ .filter((key) => key.startsWith(prefix))
75
+ .sort();
76
+ return { keys: keys.slice(0, page.maxItems), hasMore: rows.length === limit };
77
+ },
78
+ };
79
+ }
@@ -7,11 +7,10 @@
7
7
  * read-back, atomic temp-file+rename writes, and strict deletes (unknown keys
8
8
  * fail so callers notice, per the port contract).
9
9
  */
10
- import { createHash } from 'node:crypto';
11
- import { existsSync, mkdirSync, readdirSync, readFileSync, renameSync, rmSync, unlinkSync, writeFileSync } from 'node:fs';
10
+ import { existsSync, linkSync, mkdirSync, readdirSync, readFileSync, rmSync, unlinkSync, writeFileSync } from 'node:fs';
12
11
  import { dirname, join } from 'node:path';
13
- import { blobDigestOfKey } from '../server/publication.js';
14
12
  import { assertBlobPrefix } from '../server/blob-prefix.js';
13
+ import { cloneBlobBytes, verifyBytesForKey, verifyStoredBytesForKey } from '../server/blob-bridge.js';
15
14
  const BLOB_KEY_PATTERN = /^artifacts\/[A-Za-z0-9_-]+\/blobs\/sha256\/[0-9a-f]{64}$/;
16
15
  /** Reject anything but digest-addressed blob keys, before any I/O. */
17
16
  function assertBlobKey(key) {
@@ -19,8 +18,8 @@ function assertBlobKey(key) {
19
18
  throw new Error(`invalid blob key (must be artifacts/<scope>/blobs/sha256/<hex>): ${key}`);
20
19
  }
21
20
  }
22
- function sha256Hex(bytes) {
23
- return createHash('sha256').update(bytes).digest('hex');
21
+ function readVerified(key, target) {
22
+ return verifyStoredBytesForKey(key, new Uint8Array(readFileSync(target)));
24
23
  }
25
24
  /** Create a filesystem-backed blob store rooted at `root` (created on demand). */
26
25
  export function createLocalBlobStore(root) {
@@ -40,30 +39,44 @@ export function createLocalBlobStore(root) {
40
39
  };
41
40
  return {
42
41
  async putBlob(key, bytes) {
43
- assertBlobKey(key);
44
- const expected = blobDigestOfKey(key).slice('sha256:'.length);
45
- const actual = sha256Hex(bytes);
46
- if (actual !== expected) {
47
- throw new Error(`digest mismatch for blob key ${key}: content sha256:${actual}`);
48
- }
42
+ // CR-1: clone before verification, then verify before any I/O.
43
+ const snapshot = cloneBlobBytes(bytes);
44
+ verifyBytesForKey(key, snapshot);
49
45
  const target = pathOf(key);
46
+ if (existsSync(target)) {
47
+ // Create-only: digest-verified read proves the stored bytes name the
48
+ // key, hence equal the snapshot barring SHA-256 collision.
49
+ readVerified(key, target);
50
+ return;
51
+ }
50
52
  mkdirSync(dirname(target), { recursive: true });
51
53
  const temp = `${target}.tmp-${process.pid}-${Math.random().toString(36).slice(2)}`;
52
- writeFileSync(temp, bytes);
53
- renameSync(temp, target);
54
+ writeFileSync(temp, snapshot, { flag: 'wx' });
55
+ try {
56
+ // Atomic create-only: link fails with EEXIST instead of overwriting.
57
+ linkSync(temp, target);
58
+ }
59
+ catch (error) {
60
+ if (error.code === 'EEXIST') {
61
+ readVerified(key, target);
62
+ return;
63
+ }
64
+ throw error;
65
+ }
66
+ finally {
67
+ try {
68
+ unlinkSync(temp);
69
+ }
70
+ catch { /* already linked or never created */ }
71
+ }
54
72
  },
55
73
  async getBlob(key) {
56
74
  assertBlobKey(key);
57
75
  const target = pathOf(key);
58
76
  if (!existsSync(target))
59
77
  return undefined;
60
- const bytes = new Uint8Array(readFileSync(target));
61
- const expected = blobDigestOfKey(key).slice('sha256:'.length);
62
- const actual = sha256Hex(bytes);
63
- if (actual !== expected) {
64
- throw new Error(`digest mismatch on read for blob key ${key}: stored sha256:${actual}`);
65
- }
66
- return bytes;
78
+ // CR-2: digest verified before serving bytes as verified.
79
+ return readVerified(key, target);
67
80
  },
68
81
  async listKeys(prefix) {
69
82
  assertBlobPrefix(prefix);
@@ -133,8 +133,8 @@ export function createPostgresArtifactStore(pool) {
133
133
  for (const file of parsed.files ?? []) {
134
134
  if (typeof file.digest !== 'string' || typeof file.size !== 'number')
135
135
  continue;
136
- await client.query(`INSERT INTO artifacts.blobs (storage_scope_id, digest, size)
137
- VALUES ($1, $2, $3) ON CONFLICT DO NOTHING`, [scopeId, file.digest, file.size]);
136
+ await client.query(`INSERT INTO artifacts.blobs (storage_scope_id, digest, size, placement)
137
+ VALUES ($1, $2, $3, 'object') ON CONFLICT DO NOTHING`, [scopeId, file.digest, file.size]);
138
138
  }
139
139
  await client.query('COMMIT');
140
140
  }
@@ -11,6 +11,9 @@
11
11
  */
12
12
  import { DeleteObjectCommand, GetObjectCommand, ListObjectsV2Command, PutObjectCommand, } from '@aws-sdk/client-s3';
13
13
  import { assertBlobPrefix } from '../server/blob-prefix.js';
14
+ import { cloneBlobBytes, verifyBytesForKey, verifyStoredBytesForKey } from '../server/blob-bridge.js';
15
+ /** Per-call fetch cap: one page never materializes more than this (S3 MaxKeys bound). */
16
+ const PAGE_FETCH_CAP = 1000;
14
17
  const BLOB_KEY_PATTERN = /^artifacts\/[A-Za-z0-9_-]+\/blobs\/sha256\/[0-9a-f]{64}$/;
15
18
  /** Reject anything but digest-addressed blob keys, before any I/O. */
16
19
  function assertBlobKey(key) {
@@ -20,10 +23,32 @@ function assertBlobKey(key) {
20
23
  }
21
24
  /** Create an S3-backed blob store over an injected client (no env reads). */
22
25
  export function createS3BlobStore(options) {
23
- return {
26
+ const store = {
24
27
  async putBlob(key, bytes) {
25
- assertBlobKey(key);
26
- await options.client.send(new PutObjectCommand({ Bucket: options.bucket, Key: key, Body: bytes }));
28
+ // CR-1: clone before verification, then verify before any I/O.
29
+ const snapshot = cloneBlobBytes(bytes);
30
+ verifyBytesForKey(key, snapshot);
31
+ try {
32
+ await options.client.send(new PutObjectCommand({ Bucket: options.bucket, Key: key, Body: snapshot, IfNoneMatch: '*' }));
33
+ }
34
+ catch (error) {
35
+ // Create-only: the key already exists. Settle by read-back — identical
36
+ // bytes are idempotent (verified digest match), different bytes fail
37
+ // closed without overwrite.
38
+ if (typeof error === 'object' && error !== null && 'name' in error &&
39
+ error.name === 'PreconditionFailed') {
40
+ const stored = await store.getBlob(key);
41
+ if (stored !== undefined) {
42
+ verifyStoredBytesForKey(key, stored);
43
+ return;
44
+ }
45
+ }
46
+ throw error;
47
+ }
48
+ const stored = await store.getBlob(key);
49
+ if (stored === undefined)
50
+ throw new Error(`blob missing after write: ${key}`);
51
+ verifyStoredBytesForKey(key, stored);
27
52
  },
28
53
  async getBlob(key) {
29
54
  assertBlobKey(key);
@@ -32,7 +57,8 @@ export function createS3BlobStore(options) {
32
57
  if (out.Body === undefined)
33
58
  return undefined;
34
59
  const collected = await out.Body.transformToByteArray();
35
- return new Uint8Array(collected);
60
+ // CR-2: digest and length verified before serving bytes as verified.
61
+ return verifyStoredBytesForKey(key, new Uint8Array(collected));
36
62
  }
37
63
  catch (error) {
38
64
  if (typeof error === 'object' && error !== null && 'name' in error) {
@@ -84,5 +110,29 @@ export function createS3BlobStore(options) {
84
110
  assertBlobKey(key);
85
111
  await options.client.send(new DeleteObjectCommand({ Bucket: options.bucket, Key: key }));
86
112
  },
113
+ async listKeysPaged(prefix, page) {
114
+ assertBlobPrefix(prefix);
115
+ if (!Number.isSafeInteger(page.maxItems) || page.maxItems < 1)
116
+ throw new Error('invalid blob page maxItems');
117
+ if (page.startAfter !== undefined) {
118
+ if (!page.startAfter.startsWith(prefix)) {
119
+ throw new Error(`invalid blob page resume key: ${page.startAfter}`);
120
+ }
121
+ assertBlobKey(page.startAfter);
122
+ }
123
+ // Keyset resume: one bounded ListObjectsV2 from the resume key (no
124
+ // full-prefix load). The caller replays byte-trimmed tails by key.
125
+ const maxKeys = Math.min(page.maxItems + 1, PAGE_FETCH_CAP);
126
+ const out = await options.client.send(new ListObjectsV2Command({ Bucket: options.bucket, Prefix: prefix,
127
+ StartAfter: page.startAfter, MaxKeys: maxKeys }));
128
+ const keys = (out.Contents ?? []).flatMap((entry) => entry.Key === undefined ? [] : [entry.Key])
129
+ .filter((key) => key.startsWith(prefix))
130
+ .sort();
131
+ return {
132
+ keys: keys.slice(0, page.maxItems),
133
+ hasMore: out.IsTruncated === true || keys.length > page.maxItems,
134
+ };
135
+ },
87
136
  };
137
+ return store;
88
138
  }
@@ -0,0 +1,13 @@
1
+ /**
2
+ * CMF-S2 — SQLite DB blob placement (`blob_bytes`).
3
+ *
4
+ * SQLite equivalent of `db-blob.ts`: digest-addressed blobs in the
5
+ * `blob_bytes` table (no FK to `blobs`, so preparation-phase puts succeed
6
+ * before registration). Create-only (`ON CONFLICT DO NOTHING`) + read-back
7
+ * verification: identical retries are idempotent, different bytes fail closed
8
+ * without overwriting.
9
+ */
10
+ import type { PublicationBlobStore } from '../server/publication.js';
11
+ import { type SqliteDatabase } from './sqlite-sql.js';
12
+ /** Create a SQLite-backed blob store over an open database (no env reads). */
13
+ export declare function createSqliteDbBlobStore(db: SqliteDatabase): PublicationBlobStore;
@@ -0,0 +1,80 @@
1
+ import { assertBlobPrefix } from '../server/blob-prefix.js';
2
+ import { cloneBlobBytes, verifyBytesForKey, verifyStoredBytesForKey } from '../server/blob-bridge.js';
3
+ import { runQuery } from './sqlite-sql.js';
4
+ /** Per-call fetch cap: one page never materializes more than this. */
5
+ const PAGE_FETCH_CAP = 1000;
6
+ const BLOB_KEY_PATTERN = /^artifacts\/([A-Za-z0-9_-]+)\/blobs\/sha256\/([0-9a-f]{64})$/;
7
+ const SCOPE_PREFIX_PATTERN = /^artifacts\/([A-Za-z0-9_-]+)\/blobs\/sha256\//;
8
+ function splitKey(key) {
9
+ const match = BLOB_KEY_PATTERN.exec(key);
10
+ if (!match)
11
+ throw new Error(`invalid blob key: ${key}`);
12
+ return { scope: match[1], digest: `sha256:${match[2]}` };
13
+ }
14
+ /** Create a SQLite-backed blob store over an open database (no env reads). */
15
+ export function createSqliteDbBlobStore(db) {
16
+ return {
17
+ async putBlob(key, bytes) {
18
+ const snapshot = cloneBlobBytes(bytes);
19
+ verifyBytesForKey(key, snapshot);
20
+ const { scope, digest } = splitKey(key);
21
+ runQuery(db, `INSERT INTO blob_bytes (storage_scope_id, digest, bytes) VALUES ($1, $2, $3)
22
+ ON CONFLICT (storage_scope_id, digest) DO NOTHING`, [scope, digest, Buffer.from(snapshot)]);
23
+ const stored = await this.getBlob(key);
24
+ if (stored === undefined)
25
+ throw new Error(`blob missing after write: ${key}`);
26
+ },
27
+ async getBlob(key) {
28
+ const { scope, digest } = splitKey(key);
29
+ const { rows } = runQuery(db, 'SELECT bytes FROM blob_bytes WHERE storage_scope_id = $1 AND digest = $2', [scope, digest]);
30
+ if (rows[0] === undefined)
31
+ return undefined;
32
+ return verifyStoredBytesForKey(key, new Uint8Array(rows[0].bytes));
33
+ },
34
+ async getBlobRange(key, start, endInclusive) {
35
+ const stored = await this.getBlob(key);
36
+ if (stored === undefined || !Number.isSafeInteger(start) || !Number.isSafeInteger(endInclusive) ||
37
+ start < 0 || endInclusive < start)
38
+ return undefined;
39
+ return stored.slice(start, Math.min(endInclusive + 1, stored.length));
40
+ },
41
+ async listKeys(prefix) {
42
+ assertBlobPrefix(prefix);
43
+ const match = SCOPE_PREFIX_PATTERN.exec(prefix);
44
+ if (!match)
45
+ throw new Error(`blob listing requires a scope prefix: ${prefix}`);
46
+ const { rows } = runQuery(db, 'SELECT digest FROM blob_bytes WHERE storage_scope_id = $1 ORDER BY digest', [match[1]]);
47
+ return rows
48
+ .map((row) => `artifacts/${match[1]}/blobs/sha256/${row.digest.slice('sha256:'.length)}`)
49
+ .filter((key) => key.startsWith(prefix))
50
+ .sort();
51
+ },
52
+ async deleteBlob(key) {
53
+ const { scope, digest } = splitKey(key);
54
+ const result = runQuery(db, 'DELETE FROM blob_bytes WHERE storage_scope_id = $1 AND digest = $2', [scope, digest]);
55
+ if (result.rowCount === 0)
56
+ throw new Error(`unknown blob: ${key}`);
57
+ },
58
+ async listKeysPaged(prefix, page) {
59
+ assertBlobPrefix(prefix);
60
+ const match = SCOPE_PREFIX_PATTERN.exec(prefix);
61
+ if (!match)
62
+ throw new Error(`blob listing requires a scope prefix: ${prefix}`);
63
+ if (!Number.isSafeInteger(page.maxItems) || page.maxItems < 1)
64
+ throw new Error('invalid blob page maxItems');
65
+ const after = page.startAfter === undefined ? undefined : (() => {
66
+ if (!page.startAfter.startsWith(prefix))
67
+ throw new Error(`invalid blob page resume key: ${page.startAfter}`);
68
+ return splitKey(page.startAfter).digest;
69
+ })();
70
+ const limit = Math.min(page.maxItems + 1, PAGE_FETCH_CAP);
71
+ const { rows } = runQuery(db, `SELECT digest FROM blob_bytes WHERE storage_scope_id = $1
72
+ AND substr(digest, 1, length($2)) = $2
73
+ AND ($3 IS NULL OR digest > $3) ORDER BY digest LIMIT $4`, [match[1], `sha256:${prefix.slice(match[0].length)}`, after ?? null, limit]);
74
+ const keys = rows.map((row) => `artifacts/${match[1]}/blobs/sha256/${row.digest.slice('sha256:'.length)}`)
75
+ .filter((key) => key.startsWith(prefix))
76
+ .sort();
77
+ return { keys: keys.slice(0, page.maxItems), hasMore: rows.length === limit };
78
+ },
79
+ };
80
+ }
@@ -162,7 +162,8 @@ export function createSqliteArtifactStore(db, writer) {
162
162
  for (const file of parsed.files ?? []) {
163
163
  if (typeof file.digest !== 'string' || typeof file.size !== 'number')
164
164
  continue;
165
- runQuery(db, 'INSERT INTO blobs (storage_scope_id, digest, size) VALUES ($1, $2, $3) ON CONFLICT (storage_scope_id, digest) DO NOTHING', [scopeId, file.digest, file.size]);
165
+ runQuery(db, `INSERT INTO blobs (storage_scope_id, digest, size, placement) VALUES ($1, $2, $3, 'object')
166
+ ON CONFLICT (storage_scope_id, digest) DO NOTHING`, [scopeId, file.digest, file.size]);
166
167
  }
167
168
  // 0004 publication_updated_at side effect.
168
169
  runQuery(db, 'UPDATE artifacts SET updated_at = $2 WHERE id = $1', [release.artifactId, release.createdAt]);
@@ -14,6 +14,12 @@ export interface SqliteWriter {
14
14
  }
15
15
  /** Open (creating if needed) a durable local database file and apply the DDL. */
16
16
  export declare function openSqliteDatabase(path: string): SqliteDatabase;
17
+ /**
18
+ * CMF-S2 — idempotent DB blob placement upgrade for local files.
19
+ * `CREATE TABLE IF NOT EXISTS` re-runs cleanly on every open; the `blobs`
20
+ * placement column is added only when missing so existing files reopen.
21
+ */
22
+ export declare function applySqliteBlobPlacementUpgrade(db: SqliteDatabase): void;
17
23
  /** Create the serialized writer over one database connection. */
18
24
  export declare function createSqliteWriter(db: SqliteDatabase): SqliteWriter;
19
25
  export type SqliteArtifactStore = PostgresArtifactStore;
@@ -23,6 +29,7 @@ export { createSqliteArtifactStore, createSqliteCommitExecutor };
23
29
  export { createSqliteManagementUnit } from './sqlite-management.js';
24
30
  export { createSqliteActivationStore, type SqliteActivationStore } from './sqlite-activation.js';
25
31
  export { createLocalBlobStore } from './local-blob.js';
32
+ export { createSqliteDbBlobStore } from './sqlite-blob.js';
26
33
  /** One-call wiring: open a file, create the writer, build store + executor. */
27
34
  export declare function openSqliteArtifacts(path: string): {
28
35
  db: SqliteDatabase;
@@ -29,8 +29,34 @@ export function openSqliteDatabase(path) {
29
29
  db.exec('PRAGMA foreign_keys = ON');
30
30
  db.exec(DDL_ARTIFACTS);
31
31
  db.exec(DDL_ACTIVATION);
32
+ applySqliteBlobPlacementUpgrade(db);
32
33
  return db;
33
34
  }
35
+ /**
36
+ * CMF-S2 — idempotent DB blob placement upgrade for local files.
37
+ * `CREATE TABLE IF NOT EXISTS` re-runs cleanly on every open; the `blobs`
38
+ * placement column is added only when missing so existing files reopen.
39
+ */
40
+ export function applySqliteBlobPlacementUpgrade(db) {
41
+ db.exec(`CREATE TABLE IF NOT EXISTS blob_bytes (
42
+ storage_scope_id TEXT NOT NULL,
43
+ digest TEXT NOT NULL,
44
+ bytes BLOB NOT NULL,
45
+ created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ', 'now')),
46
+ PRIMARY KEY (storage_scope_id, digest)
47
+ )`);
48
+ db.exec(`CREATE TABLE IF NOT EXISTS upload_staging_bytes (
49
+ storage_scope_id TEXT NOT NULL,
50
+ upload_id TEXT NOT NULL,
51
+ bytes BLOB NOT NULL,
52
+ updated_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ', 'now')),
53
+ PRIMARY KEY (storage_scope_id, upload_id)
54
+ )`);
55
+ const columns = db.prepare('SELECT name FROM pragma_table_info(?)').all('blobs');
56
+ if (!columns.some((column) => column.name === 'placement')) {
57
+ db.exec(`ALTER TABLE blobs ADD COLUMN placement TEXT NOT NULL DEFAULT 'object'`);
58
+ }
59
+ }
34
60
  /** Create the serialized writer over one database connection. */
35
61
  export function createSqliteWriter(db) {
36
62
  let tail = Promise.resolve();
@@ -81,6 +107,7 @@ export { createSqliteArtifactStore, createSqliteCommitExecutor };
81
107
  export { createSqliteManagementUnit } from './sqlite-management.js';
82
108
  export { createSqliteActivationStore } from './sqlite-activation.js';
83
109
  export { createLocalBlobStore } from './local-blob.js';
110
+ export { createSqliteDbBlobStore } from './sqlite-blob.js';
84
111
  /** One-call wiring: open a file, create the writer, build store + executor. */
85
112
  export function openSqliteArtifacts(path) {
86
113
  const db = openSqliteDatabase(path);
@@ -10,7 +10,7 @@ export { createRadarKeyDerivation } from './server/command-identity.js';
10
10
  export type { ArtifactKeyDerivationBinding } from './server/command-identity.js';
11
11
  export declare const ARTIFACTS_PROVIDER_ID = "sentropic.artifacts";
12
12
  export declare const ARTIFACTS_APP_ID = "sentropic-artifacts";
13
- export declare const ARTIFACTS_PROVIDER_VERSION = "0.2.27";
13
+ export declare const ARTIFACTS_PROVIDER_VERSION = "0.2.28";
14
14
  export declare const ARTIFACTS_TOOL_NAMES: readonly ["artifacts_get_template", "artifacts_get_api_guide", "artifacts_ensure", "artifacts_publish", "artifacts_create_upload", "artifacts_commit_upload", "artifacts_list", "artifacts_get", "artifacts_get_source", "artifacts_fork", "artifacts_set_access", "artifacts_promote", "artifacts_renew", "artifacts_delete", "artifacts_restore", "artifacts_list_versions", "artifacts_revert", "artifacts_lookup_people", "artifacts_list_access", "artifacts_publish_bundle", "artifacts_revoke_reader_consent", "artifacts_create_upload_page", "artifacts_list_assets", "artifacts_publish_bundle_v2", "artifacts_list_app_sources", "artifacts_fetch_app_source", "artifacts_git_attach", "artifacts_git_commit", "artifacts_git_publish", "artifacts_git_live", "artifacts_live_write", "artifacts_live_read", "artifacts_live_reset", "artifacts_live_status", "artifacts_live_control", "artifacts_live_invite", "artifacts_live_accept_invitation", "artifacts_live_revoke_invitation", "artifacts_live_invitations"];
15
15
  export type ArtifactsToolName = (typeof ARTIFACTS_TOOL_NAMES)[number];
16
16
  export interface ArtifactsToolDefinition {
package/dist/mcp-core.js CHANGED
@@ -7,7 +7,7 @@ export * from './profile/index.js';
7
7
  export { createRadarKeyDerivation } from './server/command-identity.js';
8
8
  export const ARTIFACTS_PROVIDER_ID = 'sentropic.artifacts';
9
9
  export const ARTIFACTS_APP_ID = 'sentropic-artifacts';
10
- export const ARTIFACTS_PROVIDER_VERSION = '0.2.27';
10
+ export const ARTIFACTS_PROVIDER_VERSION = '0.2.28';
11
11
  export const ARTIFACTS_TOOL_NAMES = ARTIFACT_CAPABILITY_NAMES;
12
12
  // ---------------------------------------------------------------------------
13
13
  // Byte-stable tool definitions (MCP tool-definition stability rule).
@@ -0,0 +1,69 @@
1
+ import { type PublicationBlobStore } from './publication.js';
2
+ export interface BoundedBlobPage {
3
+ readonly maxItems: number;
4
+ readonly maxEncodedBytes: number;
5
+ readonly continuation?: string;
6
+ }
7
+ export interface BoundedBlobKeys {
8
+ readonly keys: string[];
9
+ readonly continuation?: string;
10
+ }
11
+ /** Clone the caller buffer so verification never observes a mutated view. */
12
+ export declare function cloneBlobBytes(bytes: Uint8Array): Uint8Array;
13
+ /**
14
+ * Fail closed before any I/O when the bytes do not name the key digest.
15
+ * Returns the verified digest (`sha256:<hex>`).
16
+ */
17
+ export declare function verifyBytesForKey(key: string, bytes: Uint8Array): string;
18
+ /** Fail closed when stored bytes no longer name their key (CR-2). */
19
+ export declare function verifyStoredBytesForKey(key: string, bytes: Uint8Array): Uint8Array;
20
+ /**
21
+ * CMF-S1 (CR-4) — sealed page-cursor states. `keyset` resumes after a full
22
+ * key (offset-free, so a byte-trimmed page replays exactly); `offset` serves
23
+ * the in-memory fallback for stores without `listKeysPaged`. Composite stores
24
+ * seal their own dual state (see `composite-blob.ts`). States are opaque to
25
+ * callers and bound to their prefix scope: a foreign or tampered cursor is
26
+ * refused, never applied.
27
+ */
28
+ export type BlobPageCursorState = {
29
+ readonly kind: 'keyset';
30
+ readonly after?: string;
31
+ } | {
32
+ readonly kind: 'offset';
33
+ readonly offset: number;
34
+ };
35
+ /** Seal a cursor state for a prefix scope (opaque, integrity-protected). */
36
+ export declare function sealBlobPageCursor(prefix: string, state: BlobPageCursorState): string;
37
+ /** Open a sealed cursor for a prefix scope (rejects foreign/tampered states). */
38
+ export declare function openBlobPageCursor(continuation: string, prefix: string): BlobPageCursorState;
39
+ /**
40
+ * Trim a key list to the encoded-byte budget (CR-4). The first key is always
41
+ * kept (a single key larger than the budget fails closed instead of looping
42
+ * forever); the caller resumes after the last kept key.
43
+ */
44
+ export declare function cutBlobKeysByBudget(keys: readonly string[], maxEncodedBytes: number): {
45
+ kept: string[];
46
+ dropped: number;
47
+ };
48
+ /**
49
+ * Bounded slice of an ordered key list under one prefix (CR-4).
50
+ * The continuation is opaque to callers, bound to its prefix scope, and
51
+ * integrity-tagged: a foreign or tampered cursor is refused, never applied.
52
+ */
53
+ export declare function pageBlobKeys(all: readonly string[], prefix: string, page: BoundedBlobPage): BoundedBlobKeys;
54
+ /**
55
+ * Bounded key enumeration over any blob store (CR-4).
56
+ * Stores with `listKeysPaged` page at the backend (keyset resume, bounded
57
+ * work per call); the rest fall back to `listKeys` + in-memory slicing.
58
+ * Either way every page honors the item and encoded-byte budgets and carries
59
+ * an opaque scope-bound integrity-protected continuation forward.
60
+ */
61
+ export declare function listBlobKeysPaged(store: Pick<PublicationBlobStore, 'listKeys' | 'listKeysPaged'>, prefix: string, page: BoundedBlobPage): Promise<BoundedBlobKeys>;
62
+ /**
63
+ * Wrap an upstream blob store with the bridge guards.
64
+ * putBlob clones first, verifies before any I/O, then delegates to an
65
+ * upstream that implements create-only writes; a conflicting write is
66
+ * settled by read-back: identical bytes are idempotent, different bytes
67
+ * fail closed without overwriting. getBlob verifies digest before serving.
68
+ */
69
+ export declare function createVerifiedBlobStore(upstream: PublicationBlobStore): PublicationBlobStore;
@@ -0,0 +1,229 @@
1
+ /**
2
+ * CMF-S1 — hardened blob bridge (MODULE_STORAGE CR-1/CR-2/CR-4).
3
+ *
4
+ * Additive on the 0.2.x line: the `PublicationBlobStore` shape is unchanged.
5
+ * This module adds the guard every blob write/read passes through on CM:
6
+ * caller-buffer clone before verification (CR-1), sha256-of-bytes against the
7
+ * key digest before any I/O, create-only writes (identical retry idempotent,
8
+ * different bytes refused without touching the stored object), digest-verified
9
+ * reads (CR-2), and bounded key pages with an opaque scope-bound
10
+ * integrity-tagged continuation (CR-4).
11
+ *
12
+ * The page shape is structural with `CommonBoundedPage`
13
+ * (`@sentropic/cluster-mesh` `storage/common-contract.ts`): same fields, no
14
+ * dependency from this package to cluster-mesh.
15
+ */
16
+ import { createHash, createHmac, randomBytes } from 'node:crypto';
17
+ import { blobDigestOfKey } from './publication.js';
18
+ import { assertBlobPrefix } from './blob-prefix.js';
19
+ /** Per-process pagination secret: cursors are unforgeable without it, invalid after restart. */
20
+ const PAGE_MAC_KEY = randomBytes(32);
21
+ const BLOB_KEY_PATTERN = /^artifacts\/[A-Za-z0-9_-]+\/blobs\/sha256\/[0-9a-f]{64}$/;
22
+ /** Clone the caller buffer so verification never observes a mutated view. */
23
+ export function cloneBlobBytes(bytes) {
24
+ return new Uint8Array(bytes);
25
+ }
26
+ function sha256Hex(bytes) {
27
+ return createHash('sha256').update(bytes).digest('hex');
28
+ }
29
+ /**
30
+ * Fail closed before any I/O when the bytes do not name the key digest.
31
+ * Returns the verified digest (`sha256:<hex>`).
32
+ */
33
+ export function verifyBytesForKey(key, bytes) {
34
+ if (!BLOB_KEY_PATTERN.test(key))
35
+ throw new Error(`invalid blob key: ${key}`);
36
+ const expected = blobDigestOfKey(key);
37
+ const actual = `sha256:${sha256Hex(bytes)}`;
38
+ if (actual !== expected)
39
+ throw new Error(`digest mismatch for blob key ${key}: content ${actual}`);
40
+ return expected;
41
+ }
42
+ /** Fail closed when stored bytes no longer name their key (CR-2). */
43
+ export function verifyStoredBytesForKey(key, bytes) {
44
+ verifyBytesForKey(key, bytes);
45
+ return bytes;
46
+ }
47
+ function cursorTag(prefix, state) {
48
+ return createHmac('sha256', PAGE_MAC_KEY).update(`blob-page/v1:${prefix}\n${state}`).digest('hex');
49
+ }
50
+ /** Seal a cursor state for a prefix scope (opaque, integrity-protected). */
51
+ export function sealBlobPageCursor(prefix, state) {
52
+ const encoded = JSON.stringify(state);
53
+ const cursor = { v: 1, prefix, state: JSON.parse(encoded),
54
+ tag: cursorTag(prefix, encoded) };
55
+ return Buffer.from(JSON.stringify(cursor), 'utf8').toString('base64url');
56
+ }
57
+ /** Open a sealed cursor for a prefix scope (rejects foreign/tampered states). */
58
+ export function openBlobPageCursor(continuation, prefix) {
59
+ let parsed;
60
+ try {
61
+ parsed = JSON.parse(Buffer.from(continuation, 'base64url').toString('utf8'));
62
+ }
63
+ catch {
64
+ throw new Error('invalid blob page continuation');
65
+ }
66
+ const state = parsed?.state;
67
+ const validKind = state?.kind === 'keyset' || state?.kind === 'offset';
68
+ const validOffset = state?.kind !== 'offset' || (typeof state.offset === 'number' &&
69
+ Number.isSafeInteger(state.offset) && state.offset >= 0);
70
+ const validAfter = state?.kind !== 'keyset' || state.after === undefined || typeof state.after === 'string';
71
+ if (parsed?.v !== 1 || !validKind || !validOffset || !validAfter || parsed.prefix !== prefix ||
72
+ parsed.tag !== cursorTag(parsed.prefix, JSON.stringify(state))) {
73
+ throw new Error('invalid blob page continuation');
74
+ }
75
+ return state;
76
+ }
77
+ /**
78
+ * Trim a key list to the encoded-byte budget (CR-4). The first key is always
79
+ * kept (a single key larger than the budget fails closed instead of looping
80
+ * forever); the caller resumes after the last kept key.
81
+ */
82
+ export function cutBlobKeysByBudget(keys, maxEncodedBytes) {
83
+ const kept = [];
84
+ let encoded = 0;
85
+ for (const key of keys) {
86
+ const size = Buffer.byteLength(key, 'utf8');
87
+ if (size > maxEncodedBytes)
88
+ throw new Error('blob key exceeds page byte budget');
89
+ if (kept.length > 0 && encoded + size > maxEncodedBytes)
90
+ break;
91
+ kept.push(key);
92
+ encoded += size;
93
+ }
94
+ return { kept, dropped: keys.length - kept.length };
95
+ }
96
+ function encodeCursor(prefix, offset) {
97
+ return sealBlobPageCursor(prefix, { kind: 'offset', offset });
98
+ }
99
+ function decodeCursor(continuation, prefix) {
100
+ const state = openBlobPageCursor(continuation, prefix);
101
+ if (state.kind !== 'offset')
102
+ throw new Error('invalid blob page continuation');
103
+ return state.offset;
104
+ }
105
+ /**
106
+ * Bounded slice of an ordered key list under one prefix (CR-4).
107
+ * The continuation is opaque to callers, bound to its prefix scope, and
108
+ * integrity-tagged: a foreign or tampered cursor is refused, never applied.
109
+ */
110
+ export function pageBlobKeys(all, prefix, page) {
111
+ assertBlobPrefix(prefix);
112
+ if (!Number.isSafeInteger(page.maxItems) || page.maxItems < 1)
113
+ throw new Error('invalid blob page maxItems');
114
+ if (!Number.isSafeInteger(page.maxEncodedBytes) || page.maxEncodedBytes < 1) {
115
+ throw new Error('invalid blob page maxEncodedBytes');
116
+ }
117
+ const offset = page.continuation === undefined ? 0 : decodeCursor(page.continuation, prefix);
118
+ const keys = [];
119
+ let encoded = 0;
120
+ let index = offset;
121
+ for (; index < all.length && keys.length < page.maxItems; index += 1) {
122
+ const key = all[index];
123
+ const size = Buffer.byteLength(key, 'utf8');
124
+ if (keys.length > 0 && encoded + size > page.maxEncodedBytes)
125
+ break;
126
+ if (size > page.maxEncodedBytes)
127
+ throw new Error('blob key exceeds page byte budget');
128
+ keys.push(key);
129
+ encoded += size;
130
+ }
131
+ if (index >= all.length)
132
+ return { keys };
133
+ return { keys, continuation: encodeCursor(prefix, index) };
134
+ }
135
+ /**
136
+ * Bounded key enumeration over any blob store (CR-4).
137
+ * Stores with `listKeysPaged` page at the backend (keyset resume, bounded
138
+ * work per call); the rest fall back to `listKeys` + in-memory slicing.
139
+ * Either way every page honors the item and encoded-byte budgets and carries
140
+ * an opaque scope-bound integrity-protected continuation forward.
141
+ */
142
+ export async function listBlobKeysPaged(store, prefix, page) {
143
+ assertBlobPrefix(prefix);
144
+ if (!Number.isSafeInteger(page.maxItems) || page.maxItems < 1)
145
+ throw new Error('invalid blob page maxItems');
146
+ if (!Number.isSafeInteger(page.maxEncodedBytes) || page.maxEncodedBytes < 1) {
147
+ throw new Error('invalid blob page maxEncodedBytes');
148
+ }
149
+ if (store.listKeysPaged !== undefined) {
150
+ const after = page.continuation === undefined ? undefined : (() => {
151
+ const state = openBlobPageCursor(page.continuation, prefix);
152
+ if (state.kind !== 'keyset')
153
+ throw new Error('invalid blob page continuation');
154
+ if (state.after !== undefined && !state.after.startsWith(prefix)) {
155
+ throw new Error('invalid blob page continuation');
156
+ }
157
+ return state.after;
158
+ })();
159
+ const side = after === undefined
160
+ ? { maxItems: page.maxItems, maxEncodedBytes: page.maxEncodedBytes }
161
+ : { maxItems: page.maxItems, maxEncodedBytes: page.maxEncodedBytes, startAfter: after };
162
+ const result = await store.listKeysPaged(prefix, side);
163
+ const capped = result.keys.slice(0, page.maxItems);
164
+ const { kept, dropped } = cutBlobKeysByBudget(capped, page.maxEncodedBytes);
165
+ const done = !result.hasMore && dropped === 0 && result.keys.length === capped.length;
166
+ if (kept.length === 0) {
167
+ if (result.keys.length === 0 && !result.hasMore)
168
+ return { keys: [] };
169
+ throw new Error('blob key exceeds page byte budget');
170
+ }
171
+ if (done)
172
+ return { keys: kept };
173
+ return { keys: kept, continuation: sealBlobPageCursor(prefix, { kind: 'keyset', after: kept[kept.length - 1] }) };
174
+ }
175
+ const all = (await store.listKeys(prefix)).filter((key) => key.startsWith(prefix)).sort();
176
+ return pageBlobKeys(all, prefix, page);
177
+ }
178
+ /**
179
+ * Wrap an upstream blob store with the bridge guards.
180
+ * putBlob clones first, verifies before any I/O, then delegates to an
181
+ * upstream that implements create-only writes; a conflicting write is
182
+ * settled by read-back: identical bytes are idempotent, different bytes
183
+ * fail closed without overwriting. getBlob verifies digest before serving.
184
+ */
185
+ export function createVerifiedBlobStore(upstream) {
186
+ return {
187
+ async putBlob(key, bytes) {
188
+ const snapshot = cloneBlobBytes(bytes);
189
+ verifyBytesForKey(key, snapshot);
190
+ try {
191
+ await upstream.putBlob(key, snapshot);
192
+ }
193
+ catch (error) {
194
+ const stored = await upstream.getBlob(key).catch(() => undefined);
195
+ if (stored !== undefined) {
196
+ verifyStoredBytesForKey(key, stored);
197
+ if (stored.byteLength === snapshot.byteLength &&
198
+ sha256Hex(stored) === sha256Hex(snapshot))
199
+ return;
200
+ }
201
+ throw error;
202
+ }
203
+ const stored = await upstream.getBlob(key);
204
+ if (stored === undefined)
205
+ throw new Error(`blob missing after write: ${key}`);
206
+ verifyStoredBytesForKey(key, stored);
207
+ },
208
+ async getBlob(key) {
209
+ const stored = await upstream.getBlob(key);
210
+ if (stored === undefined)
211
+ return undefined;
212
+ return verifyStoredBytesForKey(key, stored);
213
+ },
214
+ async getBlobRange(key, start, endInclusive) {
215
+ return upstream.getBlobRange?.(key, start, endInclusive);
216
+ },
217
+ async listKeys(prefix) {
218
+ return upstream.listKeys(prefix);
219
+ },
220
+ ...(upstream.listKeysPaged === undefined ? {} : {
221
+ async listKeysPaged(prefix, page) {
222
+ return upstream.listKeysPaged(prefix, page);
223
+ },
224
+ }),
225
+ async deleteBlob(key, transaction) {
226
+ await upstream.deleteBlob(key, transaction);
227
+ },
228
+ };
229
+ }
@@ -22,7 +22,7 @@ export interface GcReport {
22
22
  }[];
23
23
  }
24
24
  export interface GcService {
25
- collect(blobs: PublicationBlobStore, prefix: string, claims: DeletionClaimStore): Promise<GcReport>;
25
+ collect(blobs: PublicationBlobStore, prefix: string, claims: DeletionClaimStore, transaction?: FinalizeTxClient): Promise<GcReport>;
26
26
  }
27
27
  /**
28
28
  * Durable exclusive deletion claims (spec r2 A4/A6). Purge claims a digest
@@ -33,7 +33,9 @@ export interface DeletionClaimStore {
33
33
  /** Share this exclusion across claims, reference/pin creation and erasure. */
34
34
  withDigestLock<T>(digest: string, action: (locked: DeletionClaimAccess) => Promise<T>): Promise<T>;
35
35
  /** Exclusive claim; throws when the digest is already claimed. */
36
- claim(digest: string, holder: string): Promise<void>;
36
+ claim(digest: string, holder: string, blobKey?: string): Promise<void>;
37
+ /** Bounded recovery independent of the physical object listing. */
38
+ listPendingKeys?(prefix: string, limit: number): Promise<string[]>;
37
39
  /** Release the claim after the blob is gone (or the purge aborts). */
38
40
  releaseClaim(digest: string): Promise<void>;
39
41
  isClaimed(digest: string): Promise<boolean>;
package/dist/server/gc.js CHANGED
@@ -68,7 +68,7 @@ export function createPostgresGcService(executor, refsForTransaction) {
68
68
  try {
69
69
  const refs = refsForTransaction(client);
70
70
  const claims = createPostgresDeletionClaimStore(client);
71
- const report = await createGcService(refs).collect(blobs, prefix, claims);
71
+ const report = await createGcService(refs).collect(blobs, prefix, claims, client);
72
72
  await client.commit();
73
73
  return report;
74
74
  }
@@ -122,11 +122,11 @@ export function createPostgresDeletionClaimStore(client) {
122
122
  const { rows } = await client.query(`SELECT EXISTS (SELECT 1 FROM artifacts.object_intents WHERE ${predicate}) AS present`, [digest]);
123
123
  return rows[0]?.present === true;
124
124
  },
125
- async claim(digest, holder) {
125
+ async claim(digest, holder, blobKey) {
126
126
  if (await access.isClaimed(digest))
127
127
  throw new Error(`deletion already claimed: ${digest}`);
128
128
  await client.query(`INSERT INTO artifacts.object_intents (id, kind, payload)
129
- VALUES ($1, 'delete-blob', $2::jsonb)`, [crypto.randomUUID(), JSON.stringify({ deletionClaim: true, digest, holder })]);
129
+ VALUES ($1, 'delete-blob', $2::jsonb)`, [crypto.randomUUID(), JSON.stringify({ deletionClaim: true, digest, holder, blobKey })]);
130
130
  },
131
131
  async releaseClaim(digest) {
132
132
  const { rowCount } = await client.query(`UPDATE artifacts.object_intents SET state = 'done', updated_at = now() WHERE ${predicate}`, [digest]);
@@ -136,16 +136,28 @@ export function createPostgresDeletionClaimStore(client) {
136
136
  };
137
137
  const withDigestLock = async (digest, action) => {
138
138
  await client.query('SELECT pg_advisory_xact_lock(hashtextextended($1, 0))', [`artifacts-blob:${digest}`]);
139
+ // Always acquire the digest lock before locking a reservation row.
140
+ // Re-check pending state here and persist retry rotation under that lock.
141
+ await client.query(`UPDATE artifacts.object_intents SET updated_at = clock_timestamp()
142
+ WHERE ${predicate}`, [digest]);
139
143
  return action(access);
140
144
  };
141
145
  return { ...access, withDigestLock,
146
+ async listPendingKeys(prefix, limit) {
147
+ // Enumeration must not lock rows: physical listing can reach the same keys.
148
+ const { rows } = await client.query(`SELECT payload->>'blobKey' AS key FROM artifacts.object_intents
149
+ WHERE kind = 'delete-blob' AND state = 'pending' AND payload->>'deletionClaim' = 'true'
150
+ AND starts_with(payload->>'blobKey', $1)
151
+ ORDER BY updated_at, id LIMIT $2`, [prefix, limit]);
152
+ return rows.map(row => row.key);
153
+ },
142
154
  async listClaims() {
143
155
  const { rows } = await client.query(`SELECT id, state, payload->>'digest' AS digest, payload->>'holder' AS holder
144
156
  FROM artifacts.object_intents WHERE kind = 'delete-blob'
145
157
  AND payload->>'deletionClaim' = 'true' ORDER BY created_at, id`, []);
146
158
  return rows.map((row) => ({ claimId: row.id, digest: row.digest, holder: row.holder, state: row.state }));
147
159
  },
148
- claim: (digest, holder) => withDigestLock(digest, (locked) => locked.claim(digest, holder)),
160
+ claim: (digest, holder, blobKey) => withDigestLock(digest, (locked) => locked.claim(digest, holder, blobKey)),
149
161
  releaseClaim: (digest) => withDigestLock(digest, (locked) => locked.releaseClaim(digest)) };
150
162
  }
151
163
  export function createMemoryDeletionClaimStore() {
@@ -207,17 +219,22 @@ export function createClaimGuardedRefs(refs, claims) {
207
219
  /** Create a GC service over an injected refcount store (no driver imports). */
208
220
  export function createGcService(refs) {
209
221
  return {
210
- async collect(blobs, prefix, claims) {
222
+ async collect(blobs, prefix, claims, transaction) {
211
223
  const report = { deleted: [], retained: [], failures: [] };
212
- for (const key of await blobs.listKeys(prefix)) {
213
- let digest;
224
+ const pending = await claims.listPendingKeys?.(prefix, 100) ?? [];
225
+ const candidates = [];
226
+ for (const key of new Set([...pending, ...await blobs.listKeys(prefix)])) {
214
227
  try {
215
- digest = blobDigestOfKey(key);
228
+ candidates.push({ key, digest: blobDigestOfKey(key) });
216
229
  }
217
230
  catch {
218
231
  report.retained.push(key);
219
- continue;
220
232
  }
233
+ }
234
+ // Transactional digest locks survive each deletion: order the entire union,
235
+ // independent of reservation priority, physical listing order and scope.
236
+ candidates.sort((a, b) => a.digest < b.digest ? -1 : a.digest > b.digest ? 1 : 0);
237
+ for (const { key, digest } of candidates) {
221
238
  if ((await refs.count(digest)) !== 0 || (await refs.isPinned(digest))) {
222
239
  report.retained.push(key);
223
240
  continue;
@@ -226,20 +243,25 @@ export function createGcService(refs) {
226
243
  await claims.withDigestLock(digest, async (locked) => {
227
244
  const alreadyClaimed = await locked.isClaimed(digest);
228
245
  if (!alreadyClaimed)
229
- await locked.claim(digest, 'gc');
246
+ await locked.claim(digest, 'gc', key);
230
247
  let deleted = false;
248
+ let deleting = false;
231
249
  try {
232
250
  if ((await refs.count(digest)) !== 0 || (await refs.isPinned(digest))) {
233
251
  report.retained.push(key);
234
252
  return;
235
253
  }
236
- await blobs.deleteBlob(key);
254
+ deleting = true;
255
+ // Retry a lost DELETE response even when neither placement has bytes left.
256
+ if (!alreadyClaimed || (await blobs.listKeys(key)).includes(key)) {
257
+ await blobs.deleteBlob(key, transaction);
258
+ }
237
259
  deleted = true;
238
260
  report.deleted.push(key);
239
261
  }
240
262
  finally {
241
- // Preserve a purge claim until erasure; always release our GC claim.
242
- if (!alreadyClaimed || deleted)
263
+ // Failed erasure keeps durable debt for the next collection.
264
+ if (deleted || (!alreadyClaimed && !deleting))
243
265
  await locked.releaseClaim(digest);
244
266
  }
245
267
  });
@@ -1,12 +1,14 @@
1
1
  import type { PreparationIntentStore } from './object-intents.js';
2
2
  import { type PublicationBlobStore } from './publication.js';
3
3
  import type { DeletionClaimStore, RefcountStore } from './gc.js';
4
+ import type { FinalizeTxClient } from './commit/types.js';
4
5
  export interface PreparationCleanupHost {
5
6
  readonly intents: PreparationIntentStore;
6
7
  readonly blobs: PublicationBlobStore;
7
8
  readonly refs: RefcountStore;
8
9
  /** PostgreSQL callers retain the transaction-scoped exclusion through DELETE. */
9
10
  readonly claims: DeletionClaimStore;
11
+ readonly transaction?: FinalizeTxClient;
10
12
  readonly cleanupBatchSize?: number;
11
13
  }
12
14
  export interface PreparationAttempt {
@@ -88,7 +88,7 @@ export async function scheduleBoundedPreparationCleanup(host, throughMs) {
88
88
  await claims.claim(digest, `cleanup:${intent.intentId}`);
89
89
  try {
90
90
  if ((await host.blobs.listKeys(key)).includes(key))
91
- await host.blobs.deleteBlob(key);
91
+ await host.blobs.deleteBlob(key, host.transaction);
92
92
  }
93
93
  finally {
94
94
  await claims.releaseClaim(digest);
@@ -28,6 +28,24 @@ export interface PublicationStateStore {
28
28
  getCurrentReleaseId(artifactId: string): Promise<string | undefined>;
29
29
  compareAndSwapCurrent(artifactId: string, expected: string | null, next: string): Promise<boolean>;
30
30
  }
31
+ /**
32
+ * CMF-S1 (CR-4) — bounded keyset page over a digest-addressed blob prefix.
33
+ * `startAfter` resumes after a full key (exclusive); absent starts at the
34
+ * prefix. Stores return at most `maxItems` keys (fewer under `maxEncodedBytes`
35
+ * only when the caller trims; see `cutBlobKeysByBudget`); `hasMore` is true
36
+ * when unreturned keys remain. Resume is by key, never by offset, so a
37
+ * trimmed page replays exactly (bounded re-read, no skip, no duplication).
38
+ * Enumerating the whole prefix still uses `listKeys` (GC/crash recovery).
39
+ */
40
+ export interface BlobKeyPage {
41
+ readonly maxItems: number;
42
+ readonly maxEncodedBytes: number;
43
+ readonly startAfter?: string;
44
+ }
45
+ export interface BlobKeyPageResult {
46
+ readonly keys: string[];
47
+ readonly hasMore: boolean;
48
+ }
31
49
  export interface PublicationBlobStore {
32
50
  putBlob(key: string, bytes: Uint8Array): Promise<void>;
33
51
  getBlob(key: string): Promise<Uint8Array | undefined>;
@@ -38,8 +56,14 @@ export interface PublicationBlobStore {
38
56
  getBlobRange?(key: string, start: number, endInclusive: number): Promise<Uint8Array | undefined>;
39
57
  /** List keys under a prefix (orphan enumeration for crash recovery/GC). */
40
58
  listKeys(prefix: string): Promise<string[]>;
59
+ /**
60
+ * CMF-S1 (CR-4): bounded keyset page. Optional: the bridge
61
+ * (`listBlobKeysPaged`) falls back to `listKeys` + in-memory slicing when
62
+ * absent. Every in-repo store implements it.
63
+ */
64
+ listKeysPaged?(prefix: string, page: BlobKeyPage): Promise<BlobKeyPageResult>;
41
65
  /** Delete a key (strict: unknown keys fail so callers notice). */
42
- deleteBlob(key: string): Promise<void>;
66
+ deleteBlob(key: string, transaction?: import('./commit/types.js').FinalizeTxClient): Promise<void>;
43
67
  }
44
68
  /** Derive the `sha256:<hex>` digest from a digest-addressed blob key. */
45
69
  export declare function blobDigestOfKey(key: string): string;
@@ -167,7 +191,7 @@ export interface PublicationUnitWriter {
167
191
  }>;
168
192
  putSource(artifactId: string, source: SourceRef): Promise<void>;
169
193
  putRelease(release: ReleaseRecord): Promise<void>;
170
- registerBlob(storageScopeId: string, digest: string, size: number): Promise<void>;
194
+ registerBlob(storageScopeId: string, digest: string, size: number, placement?: 'db' | 'object'): Promise<void>;
171
195
  promoteCurrentLatestWins(artifactId: string, releaseId: string): Promise<void>;
172
196
  addReleaseRef(digest: string, holder: string): Promise<void>;
173
197
  completeIntent(intentId: string): Promise<void>;
@@ -204,6 +228,14 @@ export interface GuardedPublicationDeps {
204
228
  readonly blobConcurrency?: number;
205
229
  /** Per-publish blob-staging budget in ms; one shared deadline for every concurrent blob operation. */
206
230
  readonly blobDeadlineMs?: number;
231
+ /**
232
+ * CMF-S2 — DB placement promotion. Decides, per staged blob size, whether
233
+ * the finalized `artifacts.blobs` row reads 'db' (bytes in `blob_bytes`)
234
+ * instead of the default 'object'. Absent = 'object' (current behavior).
235
+ * Promotion only; a publication never demotes a row (mode changes go
236
+ * through placement migration).
237
+ */
238
+ readonly placementForSize?: (sizeBytes: number) => 'db' | 'object';
207
239
  }
208
240
  export interface GuardedPublicationService {
209
241
  replayFinalized(input: Omit<GuardedPublishInput, 'files' | 'source' | 'profile'>): Promise<FinalizeResult | undefined>;
@@ -77,6 +77,18 @@ export function createMemoryBlobStore() {
77
77
  assertBlobPrefix(prefix);
78
78
  return [...blobs.keys()].filter((key) => key.startsWith(prefix)).sort();
79
79
  },
80
+ async listKeysPaged(prefix, page) {
81
+ assertBlobPrefix(prefix);
82
+ const ordered = [...blobs.keys()].filter((key) => key.startsWith(prefix)).sort();
83
+ const start = page.startAfter === undefined ? 0 : (() => {
84
+ if (!page.startAfter.startsWith(prefix))
85
+ throw new Error(`invalid blob page resume key: ${page.startAfter}`);
86
+ const index = ordered.findIndex((key) => key > page.startAfter);
87
+ return index === -1 ? ordered.length : index;
88
+ })();
89
+ const keys = ordered.slice(start, start + page.maxItems);
90
+ return { keys, hasMore: start + page.maxItems < ordered.length };
91
+ },
80
92
  deleteBlob(key) {
81
93
  if (!blobs.has(key))
82
94
  throw new Error(`unknown blob: ${key}`);
@@ -307,9 +319,9 @@ export function createPostgresPublicationUnitWriter(client) {
307
319
  VALUES ($1, $2, $3, $4, 'ready', $5, $6, $7, $8)`, [release.releaseId, release.artifactId, release.manifestDigest, release.manifest, release.createdAt,
308
320
  release.authorPrincipalId ?? null, release.parentReleaseId ?? null, release.revertedFromReleaseId ?? null]);
309
321
  },
310
- async registerBlob(storageScopeId, digest, size) {
311
- await client.query(`INSERT INTO artifacts.blobs (storage_scope_id, digest, size)
312
- VALUES ($1, $2, $3) ON CONFLICT DO NOTHING`, [storageScopeId, digest, size]);
322
+ async registerBlob(storageScopeId, digest, size, placement = 'object') {
323
+ await client.query(`INSERT INTO artifacts.blobs (storage_scope_id, digest, size, placement)
324
+ VALUES ($1, $2, $3, $4) ON CONFLICT DO NOTHING`, [storageScopeId, digest, size, placement]);
313
325
  },
314
326
  async promoteCurrentLatestWins(artifactId, releaseId) {
315
327
  // CR-3 latest-wins: last committer wins the pointer, no loser conflict.
@@ -481,7 +493,8 @@ export function createGuardedPublicationService(deps) {
481
493
  createdAt: new Date(nowMs).toISOString(),
482
494
  });
483
495
  for (const staged of prepared.entries) {
484
- await unit.registerBlob(input.storageScopeId, staged.entry.digest, staged.entry.size);
496
+ const placement = deps.placementForSize?.(staged.entry.size) ?? 'object';
497
+ await unit.registerBlob(input.storageScopeId, staged.entry.digest, staged.entry.size, placement);
485
498
  await unit.addReleaseRef(staged.entry.digest, releaseId);
486
499
  addedRefs.push(staged.entry.digest);
487
500
  }
@@ -0,0 +1,32 @@
1
+ -- CMF-S2 — DB blob placement (additive, IF NOT EXISTS only).
2
+ --
3
+ -- `artifacts.blobs.placement` records where the bytes of a registered blob
4
+ -- live: 'object' (S3 placement, pre-0014 rows read as such) or 'db'
5
+ -- (`artifacts.blob_bytes`). `artifacts.blob_bytes` carries NO foreign key to
6
+ -- `artifacts.blobs`: preparation-phase `putBlob` runs before `registerBlob`
7
+ -- commits inside finalization, so prepared bytes must land without a parent
8
+ -- row; unreferenced prepared bytes stay protected by `artifacts.object_intents`
9
+ -- and collected by the lifecycle GC. `artifacts.upload_staging_bytes` is the
10
+ -- DB-mode staging buffer (`artifacts/<scope>/staging/<uploadId>`), swept by
11
+ -- TTL like the object-prefix staging sweeper.
12
+ ALTER TABLE artifacts.blobs
13
+ ADD COLUMN IF NOT EXISTS placement TEXT NOT NULL DEFAULT 'object'
14
+ CHECK (placement IN ('object', 'db'));
15
+
16
+ CREATE TABLE IF NOT EXISTS artifacts.blob_bytes (
17
+ storage_scope_id TEXT NOT NULL,
18
+ digest TEXT NOT NULL CHECK (digest ~ '^sha256:[0-9a-f]{64}$'),
19
+ bytes BYTEA NOT NULL,
20
+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
21
+ PRIMARY KEY (storage_scope_id, digest)
22
+ );
23
+
24
+ CREATE TABLE IF NOT EXISTS artifacts.upload_staging_bytes (
25
+ storage_scope_id TEXT NOT NULL,
26
+ upload_id UUID NOT NULL,
27
+ bytes BYTEA NOT NULL,
28
+ updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
29
+ PRIMARY KEY (storage_scope_id, upload_id)
30
+ );
31
+ CREATE INDEX IF NOT EXISTS upload_staging_bytes_by_updated
32
+ ON artifacts.upload_staging_bytes (updated_at);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sentropic/artifacts",
3
- "version": "0.2.27",
3
+ "version": "0.2.28",
4
4
  "description": "Generic configurable artifacts MCP and artifact service: StorageScope/Artifact/Binding/Release model, canonical manifests, object authorization, idempotent intents (spec-v8 §9).",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -29,6 +29,14 @@
29
29
  "types": "./dist/codecs.d.ts",
30
30
  "import": "./dist/codecs.js"
31
31
  },
32
+ "./adapters/db-blob": {
33
+ "types": "./dist/adapters/db-blob.d.ts",
34
+ "import": "./dist/adapters/db-blob.js"
35
+ },
36
+ "./adapters/composite-blob": {
37
+ "types": "./dist/adapters/composite-blob.d.ts",
38
+ "import": "./dist/adapters/composite-blob.js"
39
+ },
32
40
  "./adapters/s3": {
33
41
  "types": "./dist/adapters/s3.d.ts",
34
42
  "import": "./dist/adapters/s3.js"
@@ -135,6 +143,10 @@
135
143
  "types": "./dist/server/publication.d.ts",
136
144
  "import": "./dist/server/publication.js"
137
145
  },
146
+ "./server/blob-bridge": {
147
+ "types": "./dist/server/blob-bridge.d.ts",
148
+ "import": "./dist/server/blob-bridge.js"
149
+ },
138
150
  "./server/access": {
139
151
  "types": "./dist/server/access.d.ts",
140
152
  "import": "./dist/server/access.js"