@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
|
@@ -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
|
+
}
|
package/dist/server/gc.d.ts
CHANGED
|
@@ -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
|
-
|
|
213
|
-
|
|
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
|
|
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
|
-
|
|
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
|
-
//
|
|
242
|
-
if (!alreadyClaimed
|
|
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
|
-
|
|
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
|
}
|
|
@@ -66,6 +66,14 @@ export declare const BROWSER_EXTENSION_FALLBACK_MIME: Readonly<Record<string, st
|
|
|
66
66
|
export declare function renderUploadPage(options: {
|
|
67
67
|
s3Origins: readonly string[];
|
|
68
68
|
}): string;
|
|
69
|
+
/** Render the document and its matching CSP for hosts that send a CSP header. */
|
|
70
|
+
export declare function renderUploadPageDocument(options: {
|
|
71
|
+
s3Origins: readonly string[];
|
|
72
|
+
}): {
|
|
73
|
+
html: string;
|
|
74
|
+
csp: string;
|
|
75
|
+
nonce: string;
|
|
76
|
+
};
|
|
69
77
|
export interface UploadPageProfileCaps {
|
|
70
78
|
readonly maxFiles: number;
|
|
71
79
|
readonly maxFileBytes: number;
|
|
@@ -125,10 +125,14 @@ export function parseUploadPageCookie(header) {
|
|
|
125
125
|
}
|
|
126
126
|
/** Page CSP (§A.4): no external assets; S3 origins are host-supplied. */
|
|
127
127
|
export function uploadPageCsp(s3Origins) {
|
|
128
|
+
return buildUploadPageCsp(s3Origins);
|
|
129
|
+
}
|
|
130
|
+
function buildUploadPageCsp(s3Origins, nonce) {
|
|
128
131
|
if (s3Origins.length === 0 || s3Origins.some((origin) => !/^https:\/\/[A-Za-z0-9.-]+(?::\d+)?$/.test(origin))) {
|
|
129
132
|
throw new Error('invalid page S3 origins: the page refuses to render without them');
|
|
130
133
|
}
|
|
131
|
-
|
|
134
|
+
const inlineSource = nonce === undefined ? '' : ` 'nonce-${nonce}'`;
|
|
135
|
+
return ["default-src 'none'", `script-src 'self'${inlineSource}`, `style-src 'self'${inlineSource}`,
|
|
132
136
|
'img-src \'self\' blob:', 'font-src \'self\'', `connect-src 'self' ${s3Origins.join(' ')}`,
|
|
133
137
|
'base-uri \'none\'', 'form-action \'none\'', 'frame-ancestors \'none\''].join('; ');
|
|
134
138
|
}
|
|
@@ -154,17 +158,24 @@ export const BROWSER_EXTENSION_FALLBACK_MIME = Object.freeze({
|
|
|
154
158
|
* PUTs in flight; commit each file before opening further sessions.
|
|
155
159
|
*/
|
|
156
160
|
export function renderUploadPage(options) {
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
161
|
+
return renderUploadPageDocument(options).html;
|
|
162
|
+
}
|
|
163
|
+
/** Render the document and its matching CSP for hosts that send a CSP header. */
|
|
164
|
+
export function renderUploadPageDocument(options) {
|
|
165
|
+
const nonce = randomBytes(16).toString('base64');
|
|
166
|
+
const csp = buildUploadPageCsp(options.s3Origins, nonce);
|
|
167
|
+
// Browsers only enforce frame-ancestors in an HTTP header.
|
|
168
|
+
const metaCsp = csp.replace("; frame-ancestors 'none'", '');
|
|
169
|
+
const config = JSON.stringify({ s3Origins: [...options.s3Origins] }).replace(/</g, '\\u003c');
|
|
170
|
+
const html = `<!doctype html>
|
|
160
171
|
<html lang="en">
|
|
161
172
|
<head>
|
|
162
173
|
<meta charset="utf-8">
|
|
163
174
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
164
|
-
<meta http-equiv="Content-Security-Policy" content="${
|
|
175
|
+
<meta http-equiv="Content-Security-Policy" content="${metaCsp.replace(/"/g, '"')}">
|
|
165
176
|
<meta name="color-scheme" content="light dark">
|
|
166
177
|
<title>Upload files</title>
|
|
167
|
-
<style>body{font-family:system-ui,sans-serif;max-width:42rem;margin:2rem auto;padding:0 1rem}
|
|
178
|
+
<style nonce="${nonce}">body{font-family:system-ui,sans-serif;max-width:42rem;margin:2rem auto;padding:0 1rem}
|
|
168
179
|
#drop{border:2px dashed #888;border-radius:.5rem;padding:2rem;text-align:center;margin:1rem 0}
|
|
169
180
|
#drop.over{border-color:#06c;background:#06c1}
|
|
170
181
|
li{margin:.25rem 0;font-size:.9rem}pre{white-space:pre-wrap;word-break:break-all;background:#8882;padding:1rem}</style>
|
|
@@ -179,8 +190,8 @@ When every file shows <b>staged</b>, go back to the chat and say <b>done</b>.</p
|
|
|
179
190
|
<button id="copy" type="button">Copy asset list (chat fallback)</button>
|
|
180
191
|
<pre id="assetJson" hidden></pre>
|
|
181
192
|
<p id="error" role="alert"></p>
|
|
182
|
-
<script>window.__ARTIFACTS_UPLOAD__ = ${config};</script>
|
|
183
|
-
<script>
|
|
193
|
+
<script nonce="${nonce}">window.__ARTIFACTS_UPLOAD__ = ${config};</script>
|
|
194
|
+
<script nonce="${nonce}">
|
|
184
195
|
'use strict';
|
|
185
196
|
const sessionId = location.pathname.split('/').filter(Boolean).pop();
|
|
186
197
|
let token = (location.hash.match(/#t=([^&]+)/) || [])[1] || '';
|
|
@@ -200,7 +211,7 @@ const EXT_TYPES = ${JSON.stringify(BROWSER_EXTENSION_FALLBACK_MIME)};
|
|
|
200
211
|
const chunked = (bytes, f) => {
|
|
201
212
|
const view = new Uint8Array(bytes);
|
|
202
213
|
let out = '';
|
|
203
|
-
for (let i = 0; i < view.length; i += 0x8000) out += f(view.subarray(i, i + 0x8000))
|
|
214
|
+
for (let i = 0; i < view.length; i += 0x8000) out += f(view.subarray(i, i + 0x8000));
|
|
204
215
|
return out;
|
|
205
216
|
};
|
|
206
217
|
const hex = (bytes) => chunked(bytes, (part) => [...part].map((b) => b.toString(16).padStart(2, '0')).join(''));
|
|
@@ -283,6 +294,7 @@ api('exchange', { token }).then(() => {
|
|
|
283
294
|
</script>
|
|
284
295
|
</body>
|
|
285
296
|
</html>`;
|
|
297
|
+
return { html, csp, nonce };
|
|
286
298
|
}
|
|
287
299
|
export function createUploadPageService(deps, options) {
|
|
288
300
|
const now = options?.now ?? (() => new Date());
|