@sentropic/artifacts 0.2.27 → 0.2.29
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 +16 -0
- package/dist/adapters/composite-blob.d.ts +35 -0
- package/dist/adapters/composite-blob.js +106 -0
- package/dist/adapters/db-blob.d.ts +14 -0
- package/dist/adapters/db-blob.js +79 -0
- package/dist/adapters/local-blob.js +33 -20
- package/dist/adapters/postgres.js +2 -2
- package/dist/adapters/s3.js +54 -4
- package/dist/adapters/sqlite-blob.d.ts +13 -0
- package/dist/adapters/sqlite-blob.js +80 -0
- package/dist/adapters/sqlite-store.js +2 -1
- package/dist/adapters/sqlite.d.ts +7 -0
- package/dist/adapters/sqlite.js +27 -0
- package/dist/mcp-core.d.ts +1 -1
- package/dist/mcp-core.js +1 -1
- package/dist/server/blob-bridge.d.ts +69 -0
- package/dist/server/blob-bridge.js +229 -0
- package/dist/server/gc.d.ts +4 -2
- package/dist/server/gc.js +35 -13
- package/dist/server/preparation-cleanup.d.ts +2 -0
- package/dist/server/preparation-cleanup.js +1 -1
- package/dist/server/publication.d.ts +34 -2
- package/dist/server/publication.js +17 -4
- package/dist/server/upload-page.d.ts +8 -0
- package/dist/server/upload-page.js +21 -9
- package/migrations/0014_db_blob_placement.sql +32 -0
- package/package.json +14 -2
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,21 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.2.29
|
|
4
|
+
|
|
5
|
+
- Fix the browser upload script syntax and authorize the inline scripts and style with a fresh
|
|
6
|
+
CSP nonce on each render. Existing HTML-only hosts can keep calling `renderUploadPage`.
|
|
7
|
+
Hosts that send a CSP header can use the matching `html` and `csp` from
|
|
8
|
+
`renderUploadPageDocument`. Browsers enforce `frame-ancestors` only in that header.
|
|
9
|
+
|
|
10
|
+
## 0.2.28
|
|
11
|
+
|
|
12
|
+
- Add DB blob placement: migration `0014_db_blob_placement.sql` (`placement`, `blob_bytes`,
|
|
13
|
+
`upload_staging_bytes`), `db-blob` and `composite-blob` adapters with advisory digest-lock
|
|
14
|
+
coordination, and placement-aware publication writes with keyset-paged blob enumeration.
|
|
15
|
+
- Harden the blob bridge: create-only verified S3/local puts, bounded pages with sealed
|
|
16
|
+
keyset cursors, and store-level `listKeysPaged` delegation.
|
|
17
|
+
- Stays in `0.2.x` (cluster-mesh peer `>=0.2.0 <0.3.0`).
|
|
18
|
+
|
|
3
19
|
## 0.2.27
|
|
4
20
|
|
|
5
21
|
- 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 {
|
|
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
|
|
23
|
-
return
|
|
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
|
-
|
|
44
|
-
const
|
|
45
|
-
|
|
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,
|
|
53
|
-
|
|
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
|
-
|
|
61
|
-
|
|
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
|
}
|
package/dist/adapters/s3.js
CHANGED
|
@@ -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
|
-
|
|
26
|
+
const store = {
|
|
24
27
|
async putBlob(key, bytes) {
|
|
25
|
-
|
|
26
|
-
|
|
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
|
-
|
|
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,
|
|
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;
|
package/dist/adapters/sqlite.js
CHANGED
|
@@ -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);
|
package/dist/mcp-core.d.ts
CHANGED
|
@@ -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.
|
|
13
|
+
export declare const ARTIFACTS_PROVIDER_VERSION = "0.2.29";
|
|
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.
|
|
10
|
+
export const ARTIFACTS_PROVIDER_VERSION = '0.2.29';
|
|
11
11
|
export const ARTIFACTS_TOOL_NAMES = ARTIFACT_CAPABILITY_NAMES;
|
|
12
12
|
// ---------------------------------------------------------------------------
|
|
13
13
|
// Byte-stable tool definitions (MCP tool-definition stability rule).
|