@sentropic/artifacts 0.2.13 → 0.2.15
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 +37 -0
- package/dist/adapters/local-blob.d.ts +3 -0
- package/dist/adapters/local-blob.js +93 -0
- package/dist/adapters/postgres-uploads.d.ts +14 -0
- package/dist/adapters/postgres-uploads.js +174 -0
- package/dist/adapters/s3.js +23 -0
- package/dist/adapters/sqlite-activation.d.ts +20 -0
- package/dist/adapters/sqlite-activation.js +205 -0
- package/dist/adapters/sqlite-commit.d.ts +15 -0
- package/dist/adapters/sqlite-commit.js +89 -0
- package/dist/adapters/sqlite-management.d.ts +10 -0
- package/dist/adapters/sqlite-management.js +60 -0
- package/dist/adapters/sqlite-sql.d.ts +32 -0
- package/dist/adapters/sqlite-sql.js +36 -0
- package/dist/adapters/sqlite-store.d.ts +12 -0
- package/dist/adapters/sqlite-store.js +410 -0
- package/dist/adapters/sqlite.d.ts +33 -0
- package/dist/adapters/sqlite.js +95 -0
- package/dist/content/handler.d.ts +5 -0
- package/dist/content/handler.js +80 -9
- package/dist/http.d.ts +16 -0
- package/dist/http.js +435 -97
- package/dist/mcp-core.d.ts +3 -3
- package/dist/mcp-core.js +43 -4
- package/dist/profile/contracts.d.ts +1 -1
- package/dist/profile/contracts.js +4 -0
- package/dist/profile/index.js +12 -2
- package/dist/profile/schemas.js +60 -0
- package/dist/profile/validation.js +31 -4
- package/dist/server/command-identity.d.ts +1 -1
- package/dist/server/command-identity.js +4 -3
- package/dist/server/gc.d.ts +28 -3
- package/dist/server/gc.js +81 -5
- package/dist/server/management.js +10 -5
- package/dist/server/metrics.d.ts +21 -0
- package/dist/server/metrics.js +6 -0
- package/dist/server/ports.d.ts +7 -0
- package/dist/server/ports.js +7 -0
- package/dist/server/publication-limits.d.ts +8 -0
- package/dist/server/publication-limits.js +8 -0
- package/dist/server/publication.d.ts +5 -0
- package/dist/server/publication.js +6 -0
- package/dist/server/source-read.d.ts +12 -9
- package/dist/server/source-read.js +17 -5
- package/dist/server/upload-page.d.ts +157 -0
- package/dist/server/upload-page.js +438 -0
- package/dist/server/uploads.d.ts +75 -1
- package/dist/server/uploads.js +187 -27
- package/migrations/0009_upload_pages.sql +25 -0
- package/package.json +13 -1
- package/sql/sqlite/0001_artifacts.sql +156 -0
- package/sql/sqlite/0002_activation.sql +73 -0
package/dist/server/uploads.js
CHANGED
|
@@ -28,11 +28,23 @@ import { createHash } from 'node:crypto';
|
|
|
28
28
|
import { validateFileBytes } from './mime.js';
|
|
29
29
|
export const UPLOAD_URL_TTL_SECONDS = 600; // presigned URL: ≤ 10 minutes
|
|
30
30
|
export const UPLOAD_SESSION_TTL_MS = 24 * 60 * 60 * 1000; // staged file: 24 h
|
|
31
|
+
/**
|
|
32
|
+
* Files parity LOT 2 §D — staged-file TTL (host option, ceiling 7 days),
|
|
33
|
+
* orphan staging-key grace, and the per-run orphan bound.
|
|
34
|
+
*/
|
|
35
|
+
export const STAGED_FILE_TTL_MS = 24 * 60 * 60 * 1000;
|
|
36
|
+
export const STAGED_FILE_TTL_MAX_MS = 7 * 24 * 60 * 60 * 1000;
|
|
37
|
+
export const ORPHAN_STAGING_GRACE_MS = 60 * 60 * 1000;
|
|
38
|
+
export const ORPHAN_SWEEP_MAX_KEYS = 500;
|
|
31
39
|
export const STAGING_KEY_PATTERN = /^artifacts\/[A-Za-z0-9_-]+\/staging\/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
|
|
32
40
|
/** Staging key of one upload session. */
|
|
33
41
|
export function stagingKey(storageScopeId, uploadId) {
|
|
34
42
|
return `artifacts/${storageScopeId}/staging/${uploadId}`;
|
|
35
43
|
}
|
|
44
|
+
/** Staging prefix of one scope (LOT 2 §D.1 orphan pass enumerates it). */
|
|
45
|
+
export function stagingPrefix(storageScopeId) {
|
|
46
|
+
return `artifacts/${storageScopeId}/staging/`;
|
|
47
|
+
}
|
|
36
48
|
/**
|
|
37
49
|
* Value of the `x-amz-checksum-sha256` header for a canonical `sha256:<hex>`
|
|
38
50
|
* digest: S3 expects the base64 of the raw digest bytes (no `sha256:` prefix).
|
|
@@ -56,18 +68,18 @@ export function assertStagingPrefix(prefix) {
|
|
|
56
68
|
}
|
|
57
69
|
}
|
|
58
70
|
/** In-memory StagingStore double for unit tests. */
|
|
59
|
-
export function createMemoryStaging() {
|
|
71
|
+
export function createMemoryStaging(now = () => new Date()) {
|
|
60
72
|
const staged = new Map();
|
|
61
73
|
return {
|
|
62
74
|
put(key, bytes) {
|
|
63
75
|
assertStagingKey(key);
|
|
64
|
-
staged.set(key, new Uint8Array(bytes));
|
|
76
|
+
staged.set(key, { bytes: new Uint8Array(bytes), lastModified: now().toISOString() });
|
|
65
77
|
return Promise.resolve();
|
|
66
78
|
},
|
|
67
79
|
get(key) {
|
|
68
80
|
assertStagingKey(key);
|
|
69
|
-
const
|
|
70
|
-
return Promise.resolve(
|
|
81
|
+
const entry = staged.get(key);
|
|
82
|
+
return Promise.resolve(entry === undefined ? undefined : new Uint8Array(entry.bytes));
|
|
71
83
|
},
|
|
72
84
|
delete(key) {
|
|
73
85
|
assertStagingKey(key);
|
|
@@ -78,13 +90,29 @@ export function createMemoryStaging() {
|
|
|
78
90
|
assertStagingPrefix(prefix);
|
|
79
91
|
return Promise.resolve([...staged.keys()].filter((key) => key.startsWith(prefix)).sort());
|
|
80
92
|
},
|
|
93
|
+
listEntries(prefix) {
|
|
94
|
+
assertStagingPrefix(prefix);
|
|
95
|
+
return Promise.resolve([...staged.entries()]
|
|
96
|
+
.filter(([key]) => key.startsWith(prefix))
|
|
97
|
+
.map(([key, entry]) => ({ key, lastModified: entry.lastModified })).sort((a, b) => (a.key < b.key ? -1 : 1)));
|
|
98
|
+
},
|
|
81
99
|
};
|
|
82
100
|
}
|
|
83
101
|
/** In-memory UploadSessionStore double for unit tests. */
|
|
84
102
|
export function createMemoryUploadSessionStore(now = () => new Date()) {
|
|
85
103
|
const sessions = new Map();
|
|
86
104
|
const stagedFiles = new Map();
|
|
87
|
-
|
|
105
|
+
// LOT 2 §D.2: per-scope serialization of the quota check and insert.
|
|
106
|
+
const scopeTails = new Map();
|
|
107
|
+
const scopeLock = (storageScopeId, action) => {
|
|
108
|
+
const previous = scopeTails.get(storageScopeId) ?? Promise.resolve();
|
|
109
|
+
let release;
|
|
110
|
+
const gate = new Promise((resolve) => { release = resolve; });
|
|
111
|
+
scopeTails.set(storageScopeId, previous.then(() => gate));
|
|
112
|
+
return previous.then(() => action(store)).finally(release);
|
|
113
|
+
};
|
|
114
|
+
const scopeOfStaged = (record) => sessions.get(record.uploadId)?.storageScopeId;
|
|
115
|
+
const store = {
|
|
88
116
|
create(session) {
|
|
89
117
|
sessions.set(session.uploadId, session);
|
|
90
118
|
return Promise.resolve();
|
|
@@ -127,7 +155,35 @@ export function createMemoryUploadSessionStore(now = () => new Date()) {
|
|
|
127
155
|
listStagedFiles(artifactId) {
|
|
128
156
|
return Promise.resolve([...stagedFiles.values()].filter((record) => record.artifactId === artifactId));
|
|
129
157
|
},
|
|
158
|
+
sumOpenMaxSize(storageScopeId) {
|
|
159
|
+
let total = 0;
|
|
160
|
+
for (const session of sessions.values()) {
|
|
161
|
+
if (session.storageScopeId === storageScopeId && session.state === 'open')
|
|
162
|
+
total += session.maxSize;
|
|
163
|
+
}
|
|
164
|
+
return Promise.resolve(total);
|
|
165
|
+
},
|
|
166
|
+
sumStagedBytesByScope(storageScopeId) {
|
|
167
|
+
let total = 0;
|
|
168
|
+
for (const record of stagedFiles.values()) {
|
|
169
|
+
if (scopeOfStaged(record) === storageScopeId)
|
|
170
|
+
total += record.size;
|
|
171
|
+
}
|
|
172
|
+
return Promise.resolve(total);
|
|
173
|
+
},
|
|
174
|
+
listPageSessions(pageSessionId) {
|
|
175
|
+
return Promise.resolve([...sessions.values()].filter((session) => session.pageSessionId === pageSessionId));
|
|
176
|
+
},
|
|
177
|
+
withScopeLock: scopeLock,
|
|
178
|
+
listExpiredStaged(at, ttlMs) {
|
|
179
|
+
return Promise.resolve([...stagedFiles.values()].filter((record) => new Date(record.createdAt).getTime() + ttlMs <= at.getTime()));
|
|
180
|
+
},
|
|
181
|
+
deleteStagedFile(uploadId) {
|
|
182
|
+
stagedFiles.delete(uploadId);
|
|
183
|
+
return Promise.resolve();
|
|
184
|
+
},
|
|
130
185
|
};
|
|
186
|
+
return store;
|
|
131
187
|
}
|
|
132
188
|
/**
|
|
133
189
|
* Memory signer double: records every signed PUT and simulates S3's
|
|
@@ -181,6 +237,14 @@ export function createMemoryUploadSigner() {
|
|
|
181
237
|
},
|
|
182
238
|
};
|
|
183
239
|
}
|
|
240
|
+
/** Digest-addressed CAS blob key of one scope and canonical `sha256:<hex>` digest. */
|
|
241
|
+
export function casBlobKey(storageScopeId, digest) {
|
|
242
|
+
return `artifacts/${storageScopeId}/blobs/${digest.replace(':', '/')}`;
|
|
243
|
+
}
|
|
244
|
+
/** LOT 2 §D.1: true when a staged file is older than the staged-file TTL. */
|
|
245
|
+
export function stagedFileExpired(record, nowMs, ttlMs) {
|
|
246
|
+
return new Date(record.createdAt).getTime() + ttlMs <= nowMs;
|
|
247
|
+
}
|
|
184
248
|
export function createUploadService(deps, options) {
|
|
185
249
|
const now = options.now ?? (() => new Date());
|
|
186
250
|
const ids = options.ids ?? (() => crypto.randomUUID());
|
|
@@ -190,36 +254,78 @@ export function createUploadService(deps, options) {
|
|
|
190
254
|
if (!Number.isSafeInteger(options.maxSessionsPerPrincipal) || options.maxSessionsPerPrincipal < 1) {
|
|
191
255
|
throw new Error('invalid upload session quota');
|
|
192
256
|
}
|
|
257
|
+
if (options.stagingQuotaBytesPerScope !== undefined &&
|
|
258
|
+
(!Number.isSafeInteger(options.stagingQuotaBytesPerScope) || options.stagingQuotaBytesPerScope < 1)) {
|
|
259
|
+
throw new Error('invalid scope staging quota');
|
|
260
|
+
}
|
|
261
|
+
if (options.stagedFileTtlMs !== undefined &&
|
|
262
|
+
(!Number.isSafeInteger(options.stagedFileTtlMs) || options.stagedFileTtlMs < 1 ||
|
|
263
|
+
options.stagedFileTtlMs > STAGED_FILE_TTL_MAX_MS)) {
|
|
264
|
+
throw new Error('invalid staged file TTL');
|
|
265
|
+
}
|
|
266
|
+
const channel = options.channel ?? 'agent';
|
|
267
|
+
const emit = (event) => {
|
|
268
|
+
if (options.metrics !== undefined)
|
|
269
|
+
options.metrics.emit({ ...event,
|
|
270
|
+
labels: { channel, ...(event.labels ?? {}) } });
|
|
271
|
+
};
|
|
193
272
|
return {
|
|
194
273
|
async create(input) {
|
|
195
274
|
if (input.maxSize !== undefined && (!Number.isSafeInteger(input.maxSize) || input.maxSize < 1)) {
|
|
196
275
|
throw new Error('invalid upload byte budget');
|
|
197
276
|
}
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
throw new Error(
|
|
277
|
+
if (input.pageSessionId !== undefined && (input.pageFileLimit === undefined ||
|
|
278
|
+
!Number.isSafeInteger(input.pageFileLimit) || input.pageFileLimit < 1)) {
|
|
279
|
+
throw new Error('invalid page file bound');
|
|
201
280
|
}
|
|
202
281
|
const maxSize = Math.min(input.maxSize ?? options.maxUploadBytes, options.maxUploadBytes);
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
282
|
+
// LOT 2 §D.2: the quota check and the insert run inside the scope lock,
|
|
283
|
+
// so parallel creates against one scope quota admit exactly the quota.
|
|
284
|
+
// Callers must not hold the scope lock across service calls (no nesting).
|
|
285
|
+
return deps.sessions.withScopeLock(input.storageScopeId, async (locked) => {
|
|
286
|
+
const open = await locked.countOpen(input.storageScopeId, input.ownerId);
|
|
287
|
+
if (open >= options.maxSessionsPerPrincipal) {
|
|
288
|
+
emit({ name: 'upload_quota_refusals', labels: { reason: 'open_session_quota' } });
|
|
289
|
+
throw new Error(`open upload session quota exceeded for principal (max ${options.maxSessionsPerPrincipal})`);
|
|
290
|
+
}
|
|
291
|
+
if (options.stagingQuotaBytesPerScope !== undefined) {
|
|
292
|
+
const reserved = await locked.sumOpenMaxSize(input.storageScopeId) +
|
|
293
|
+
await locked.sumStagedBytesByScope(input.storageScopeId);
|
|
294
|
+
if (reserved + maxSize > options.stagingQuotaBytesPerScope) {
|
|
295
|
+
emit({ name: 'upload_quota_refusals', labels: { reason: 'scope_staging_quota' } });
|
|
296
|
+
throw new Error(`scope staging quota exceeded (max ${options.stagingQuotaBytesPerScope} bytes)`);
|
|
297
|
+
}
|
|
298
|
+
}
|
|
299
|
+
if (input.pageSessionId !== undefined) {
|
|
300
|
+
const pageCount = (await locked.listPageSessions(input.pageSessionId)).length;
|
|
301
|
+
if (pageCount >= input.pageFileLimit) {
|
|
302
|
+
emit({ name: 'upload_quota_refusals', labels: { reason: 'page_file_quota' } });
|
|
303
|
+
throw new Error(`open upload page file quota exceeded (max ${input.pageFileLimit})`);
|
|
304
|
+
}
|
|
305
|
+
}
|
|
306
|
+
const uploadId = ids();
|
|
307
|
+
const createdAt = now().toISOString();
|
|
308
|
+
const expiresAt = new Date(now().getTime() + UPLOAD_SESSION_TTL_MS).toISOString();
|
|
309
|
+
const key = stagingKey(input.storageScopeId, uploadId);
|
|
310
|
+
await locked.create({
|
|
311
|
+
uploadId, artifactId: input.artifactId, storageScopeId: input.storageScopeId,
|
|
312
|
+
ownerId: input.ownerId, mimeType: input.mimeType, maxSize, state: 'open', expiresAt, createdAt,
|
|
313
|
+
...(input.pageSessionId === undefined ? {} : { pageSessionId: input.pageSessionId }),
|
|
314
|
+
});
|
|
315
|
+
emit({ name: 'upload_sessions_created' });
|
|
316
|
+
// The signature binds content-type and the EXACT declared Content-Length
|
|
317
|
+
// (a presigned PUT cannot carry a content-length range). The digest is
|
|
318
|
+
// declared at commit, so the PUT must also carry x-amz-checksum-sha256,
|
|
319
|
+
// which S3 validates against the body; commit re-verifies both.
|
|
320
|
+
const signed = await deps.signer.signPut({
|
|
321
|
+
key, contentType: input.mimeType, contentLength: maxSize, expiresInSeconds: UPLOAD_URL_TTL_SECONDS,
|
|
322
|
+
});
|
|
323
|
+
return {
|
|
324
|
+
uploadId, uploadUrl: signed.url, method: signed.method, expiresAt: signed.expiresAt, maxSize,
|
|
325
|
+
requiredHeaders: signed.headers, checksumHeader: 'x-amz-checksum-sha256',
|
|
326
|
+
stagingKey: key,
|
|
327
|
+
};
|
|
217
328
|
});
|
|
218
|
-
return {
|
|
219
|
-
uploadId, uploadUrl: signed.url, method: signed.method, expiresAt: signed.expiresAt, maxSize,
|
|
220
|
-
requiredHeaders: signed.headers, checksumHeader: 'x-amz-checksum-sha256',
|
|
221
|
-
stagingKey: key,
|
|
222
|
-
};
|
|
223
329
|
},
|
|
224
330
|
sessionForCommit(input) {
|
|
225
331
|
return deps.sessions.get(input.uploadId).then((session) => {
|
|
@@ -252,6 +358,7 @@ export function createUploadService(deps, options) {
|
|
|
252
358
|
const staged = {
|
|
253
359
|
uploadId: session.uploadId, artifactId: session.artifactId, createdAt: now().toISOString(),
|
|
254
360
|
path: record.path, mimeType: record.mimeType, digest: record.digest, size: record.size,
|
|
361
|
+
...(session.pageSessionId === undefined ? {} : { pageSessionId: session.pageSessionId }),
|
|
255
362
|
};
|
|
256
363
|
await deps.sessions.recordStagedFile(staged);
|
|
257
364
|
await deps.sessions.markCommitted(session.uploadId);
|
|
@@ -259,3 +366,56 @@ export function createUploadService(deps, options) {
|
|
|
259
366
|
},
|
|
260
367
|
};
|
|
261
368
|
}
|
|
369
|
+
export async function commitStagedUpload(service, deps, input, channel = 'agent') {
|
|
370
|
+
const emit = (event) => {
|
|
371
|
+
if (deps.metrics !== undefined)
|
|
372
|
+
deps.metrics.emit({ ...event,
|
|
373
|
+
labels: { channel, ...(event.labels ?? {}) } });
|
|
374
|
+
};
|
|
375
|
+
const fail = (error) => {
|
|
376
|
+
if (!(error instanceof Error) || !/budget exceeded/.test(error.message)) {
|
|
377
|
+
emit({ name: 'upload_commits', labels: { result: 'verification_failed' } });
|
|
378
|
+
}
|
|
379
|
+
throw error;
|
|
380
|
+
};
|
|
381
|
+
const session = await service.sessionForCommit(input).catch((error) => fail(error));
|
|
382
|
+
const key = stagingKey(input.storageScopeId, input.uploadId);
|
|
383
|
+
const bytes = await deps.staging.get(key) ??
|
|
384
|
+
fail(new Error(`staged object missing for ${input.uploadId}`));
|
|
385
|
+
try {
|
|
386
|
+
service.verifyStaged(session, bytes, { digest: input.digest, size: input.size, mimeType: input.mimeType });
|
|
387
|
+
}
|
|
388
|
+
catch (error) {
|
|
389
|
+
fail(error);
|
|
390
|
+
}
|
|
391
|
+
// LOT 2 §D.2: per-artifact staged caps, checked at commit for both channels.
|
|
392
|
+
const existing = await deps.sessions.listStagedFiles(input.artifactId);
|
|
393
|
+
const stagedBytes = existing.reduce((total, record) => total + record.size, 0);
|
|
394
|
+
if (existing.length + 1 > deps.budget.filesMax || stagedBytes + input.size > deps.budget.totalBytesMax) {
|
|
395
|
+
emit({ name: 'upload_quota_refusals', labels: { reason: 'staged_budget' } });
|
|
396
|
+
throw new Error(`staged file budget exceeded for artifact (max ${deps.budget.filesMax} files, ` +
|
|
397
|
+
`${deps.budget.totalBytesMax} bytes total)`);
|
|
398
|
+
}
|
|
399
|
+
const casKey = casBlobKey(input.storageScopeId, input.digest);
|
|
400
|
+
await deps.blobs.putBlob(casKey, bytes);
|
|
401
|
+
const readBack = await deps.blobs.getBlob(casKey);
|
|
402
|
+
if (readBack === undefined || readBack.byteLength !== input.size ||
|
|
403
|
+
`sha256:${createHash('sha256').update(readBack).digest('hex')}` !== input.digest) {
|
|
404
|
+
fail(new Error(`CAS read-back mismatch for ${input.uploadId}`));
|
|
405
|
+
}
|
|
406
|
+
const pinReason = `upload:${input.uploadId}`;
|
|
407
|
+
await deps.refs.pin(input.digest, pinReason);
|
|
408
|
+
let staged;
|
|
409
|
+
try {
|
|
410
|
+
staged = await service.completeCommit(session, { path: input.path, mimeType: input.mimeType,
|
|
411
|
+
digest: input.digest, size: input.size });
|
|
412
|
+
}
|
|
413
|
+
catch (error) {
|
|
414
|
+
await deps.refs.unpin(input.digest, pinReason).catch(() => undefined);
|
|
415
|
+
throw error;
|
|
416
|
+
}
|
|
417
|
+
await deps.staging.delete(key);
|
|
418
|
+
emit({ name: 'upload_commits', labels: { result: 'ok' } });
|
|
419
|
+
emit({ name: 'upload_bytes_committed', value: input.size });
|
|
420
|
+
return staged;
|
|
421
|
+
}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
-- Files parity LOT 2 §A — browser upload pages (additive, IF NOT EXISTS).
|
|
2
|
+
--
|
|
3
|
+
-- One row per minted browser upload page: the token hash (never the token),
|
|
4
|
+
-- the bound artifact/scope/owner, and the page file bound. Rows are kept
|
|
5
|
+
-- after expiry for audit; the sweeper flips them to 'expired'.
|
|
6
|
+
CREATE TABLE IF NOT EXISTS artifacts.upload_pages (
|
|
7
|
+
id UUID PRIMARY KEY,
|
|
8
|
+
artifact_id UUID NOT NULL REFERENCES artifacts.artifacts (id) ON DELETE CASCADE,
|
|
9
|
+
storage_scope_id TEXT NOT NULL,
|
|
10
|
+
owner_id TEXT NOT NULL,
|
|
11
|
+
token_hash TEXT NOT NULL,
|
|
12
|
+
state TEXT NOT NULL DEFAULT 'open' CHECK (state IN ('open', 'exchanged', 'closed', 'expired')),
|
|
13
|
+
max_files INTEGER NOT NULL CHECK (max_files > 0),
|
|
14
|
+
expires_at TIMESTAMPTZ NOT NULL,
|
|
15
|
+
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
|
16
|
+
exchanged_at TIMESTAMPTZ NULL
|
|
17
|
+
);
|
|
18
|
+
CREATE INDEX IF NOT EXISTS upload_pages_by_expiry ON artifacts.upload_pages (state, expires_at)
|
|
19
|
+
WHERE state IN ('open', 'exchanged');
|
|
20
|
+
|
|
21
|
+
-- Agent-channel rows stay NULL; browser sessions carry their page.
|
|
22
|
+
ALTER TABLE artifacts.uploads
|
|
23
|
+
ADD COLUMN IF NOT EXISTS page_session_id UUID REFERENCES artifacts.upload_pages (id) ON DELETE SET NULL;
|
|
24
|
+
CREATE INDEX IF NOT EXISTS uploads_by_page ON artifacts.uploads (page_session_id)
|
|
25
|
+
WHERE page_session_id IS NOT NULL;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@sentropic/artifacts",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.15",
|
|
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",
|
|
@@ -49,6 +49,10 @@
|
|
|
49
49
|
"types": "./dist/adapters/postgres-reader-consent.d.ts",
|
|
50
50
|
"import": "./dist/adapters/postgres-reader-consent.js"
|
|
51
51
|
},
|
|
52
|
+
"./adapters/postgres-uploads": {
|
|
53
|
+
"types": "./dist/adapters/postgres-uploads.d.ts",
|
|
54
|
+
"import": "./dist/adapters/postgres-uploads.js"
|
|
55
|
+
},
|
|
52
56
|
"./adapters/postgres-activation": {
|
|
53
57
|
"types": "./dist/adapters/postgres-activation.d.ts",
|
|
54
58
|
"import": "./dist/adapters/postgres-activation.js"
|
|
@@ -57,6 +61,10 @@
|
|
|
57
61
|
"types": "./dist/adapters/postgres-activation-vectors.d.ts",
|
|
58
62
|
"import": "./dist/adapters/postgres-activation-vectors.js"
|
|
59
63
|
},
|
|
64
|
+
"./sqlite": {
|
|
65
|
+
"types": "./dist/adapters/sqlite.d.ts",
|
|
66
|
+
"import": "./dist/adapters/sqlite.js"
|
|
67
|
+
},
|
|
60
68
|
"./sql/*": "./sql/*",
|
|
61
69
|
"./migrations/*": "./migrations/*",
|
|
62
70
|
"./server/ports": {
|
|
@@ -107,6 +115,10 @@
|
|
|
107
115
|
"types": "./dist/server/uploads.d.ts",
|
|
108
116
|
"import": "./dist/server/uploads.js"
|
|
109
117
|
},
|
|
118
|
+
"./server/upload-page": {
|
|
119
|
+
"types": "./dist/server/upload-page.d.ts",
|
|
120
|
+
"import": "./dist/server/upload-page.js"
|
|
121
|
+
},
|
|
110
122
|
"./server/publication": {
|
|
111
123
|
"types": "./dist/server/publication.d.ts",
|
|
112
124
|
"import": "./dist/server/publication.js"
|
|
@@ -0,0 +1,156 @@
|
|
|
1
|
+
-- U1 — SQLite DDL for the artifacts domain, owned by the SQLite adapter
|
|
2
|
+
-- (applied by openSqliteDatabase, never by the host migration journal).
|
|
3
|
+
--
|
|
4
|
+
-- SQLite has no schemas: the Postgres `artifacts.<table>` names map to plain
|
|
5
|
+
-- `<table>` in the single local file. Column types map TIMESTAMPTZ -> TEXT
|
|
6
|
+
-- (ISO-8601 UTC strings), JSONB -> TEXT (JSON), BOOLEAN -> INTEGER 0/1,
|
|
7
|
+
-- UUID -> TEXT, and gen_random_uuid() is supplied by the adapter. The 0004
|
|
8
|
+
-- terminal guards are enforced in adapter code (all writes are serialized
|
|
9
|
+
-- through one BEGIN IMMEDIATE writer, so check-then-write is atomic); the
|
|
10
|
+
-- publication updated_at side effect is folded into putRelease. Semantics
|
|
11
|
+
-- are identical to migrations/0001..0005.sql.
|
|
12
|
+
|
|
13
|
+
PRAGMA journal_mode = WAL;
|
|
14
|
+
PRAGMA synchronous = FULL;
|
|
15
|
+
PRAGMA foreign_keys = ON;
|
|
16
|
+
|
|
17
|
+
CREATE TABLE IF NOT EXISTS storage_scopes (
|
|
18
|
+
id TEXT PRIMARY KEY,
|
|
19
|
+
org_id TEXT NOT NULL,
|
|
20
|
+
created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ', 'now'))
|
|
21
|
+
);
|
|
22
|
+
|
|
23
|
+
CREATE TABLE IF NOT EXISTS artifacts (
|
|
24
|
+
id TEXT PRIMARY KEY,
|
|
25
|
+
storage_scope_id TEXT NOT NULL REFERENCES storage_scopes (id),
|
|
26
|
+
owner_id TEXT NOT NULL,
|
|
27
|
+
binding_name TEXT NOT NULL,
|
|
28
|
+
profile TEXT NOT NULL DEFAULT '{}',
|
|
29
|
+
created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ', 'now')),
|
|
30
|
+
lifecycle_state TEXT NOT NULL DEFAULT 'active'
|
|
31
|
+
CHECK (lifecycle_state IN ('active', 'withdrawn', 'deleted', 'purged')),
|
|
32
|
+
renewed_at TEXT,
|
|
33
|
+
is_public INTEGER NOT NULL DEFAULT 0,
|
|
34
|
+
access_mode TEXT NOT NULL DEFAULT 'restricted'
|
|
35
|
+
CHECK (access_mode IN ('restricted', 'platform', 'public')),
|
|
36
|
+
terminal_deleted_at TEXT,
|
|
37
|
+
updated_at TEXT DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ', 'now')),
|
|
38
|
+
metadata TEXT NOT NULL DEFAULT '{}',
|
|
39
|
+
UNIQUE (storage_scope_id, owner_id, binding_name)
|
|
40
|
+
);
|
|
41
|
+
|
|
42
|
+
CREATE TABLE IF NOT EXISTS releases (
|
|
43
|
+
id TEXT PRIMARY KEY,
|
|
44
|
+
artifact_id TEXT NOT NULL REFERENCES artifacts (id) ON DELETE CASCADE,
|
|
45
|
+
manifest_digest TEXT NOT NULL,
|
|
46
|
+
manifest TEXT NOT NULL,
|
|
47
|
+
state TEXT NOT NULL DEFAULT 'ready' CHECK (state IN ('ready', 'retired', 'purged')),
|
|
48
|
+
created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ', 'now')),
|
|
49
|
+
author_principal_id TEXT,
|
|
50
|
+
parent_release_id TEXT,
|
|
51
|
+
reverted_from_release_id TEXT
|
|
52
|
+
);
|
|
53
|
+
CREATE INDEX IF NOT EXISTS releases_by_artifact ON releases (artifact_id);
|
|
54
|
+
|
|
55
|
+
CREATE TABLE IF NOT EXISTS artifact_current (
|
|
56
|
+
artifact_id TEXT PRIMARY KEY REFERENCES artifacts (id) ON DELETE CASCADE,
|
|
57
|
+
release_id TEXT NOT NULL REFERENCES releases (id) ON DELETE RESTRICT
|
|
58
|
+
);
|
|
59
|
+
|
|
60
|
+
CREATE TABLE IF NOT EXISTS blobs (
|
|
61
|
+
storage_scope_id TEXT NOT NULL,
|
|
62
|
+
digest TEXT NOT NULL,
|
|
63
|
+
size INTEGER NOT NULL CHECK (size >= 0),
|
|
64
|
+
created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ', 'now')),
|
|
65
|
+
PRIMARY KEY (storage_scope_id, digest)
|
|
66
|
+
);
|
|
67
|
+
|
|
68
|
+
CREATE TABLE IF NOT EXISTS uploads (
|
|
69
|
+
id TEXT PRIMARY KEY,
|
|
70
|
+
max_size INTEGER NOT NULL CHECK (max_size > 0),
|
|
71
|
+
size INTEGER NOT NULL DEFAULT 0 CHECK (size >= 0),
|
|
72
|
+
mime_type TEXT NOT NULL,
|
|
73
|
+
state TEXT NOT NULL DEFAULT 'open' CHECK (state IN ('open', 'committed', 'discarded')),
|
|
74
|
+
created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ', 'now'))
|
|
75
|
+
);
|
|
76
|
+
CREATE INDEX IF NOT EXISTS uploads_by_state ON uploads (state);
|
|
77
|
+
|
|
78
|
+
CREATE TABLE IF NOT EXISTS object_intents (
|
|
79
|
+
id TEXT PRIMARY KEY,
|
|
80
|
+
kind TEXT NOT NULL CHECK (kind IN ('commit-release', 'delete-blob', 'promote-release')),
|
|
81
|
+
state TEXT NOT NULL DEFAULT 'pending' CHECK (state IN ('pending', 'done', 'failed')),
|
|
82
|
+
payload TEXT NOT NULL DEFAULT '{}',
|
|
83
|
+
error TEXT,
|
|
84
|
+
created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ', 'now')),
|
|
85
|
+
updated_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ', 'now'))
|
|
86
|
+
);
|
|
87
|
+
CREATE INDEX IF NOT EXISTS intents_pending ON object_intents (state, created_at)
|
|
88
|
+
WHERE state = 'pending';
|
|
89
|
+
|
|
90
|
+
CREATE TABLE IF NOT EXISTS idempotency_keys (
|
|
91
|
+
key TEXT PRIMARY KEY,
|
|
92
|
+
params_hash TEXT NOT NULL,
|
|
93
|
+
result TEXT NOT NULL,
|
|
94
|
+
created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ', 'now'))
|
|
95
|
+
);
|
|
96
|
+
|
|
97
|
+
CREATE TABLE IF NOT EXISTS artifact_access (
|
|
98
|
+
artifact_id TEXT NOT NULL REFERENCES artifacts (id) ON DELETE CASCADE,
|
|
99
|
+
principal_id TEXT NOT NULL,
|
|
100
|
+
permission TEXT NOT NULL CHECK (permission IN ('read', 'source')),
|
|
101
|
+
created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ', 'now')),
|
|
102
|
+
PRIMARY KEY (artifact_id, principal_id)
|
|
103
|
+
);
|
|
104
|
+
|
|
105
|
+
CREATE TABLE IF NOT EXISTS artifact_access_events (
|
|
106
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
107
|
+
artifact_id TEXT NOT NULL REFERENCES artifacts (id) ON DELETE CASCADE,
|
|
108
|
+
actor_id TEXT NOT NULL,
|
|
109
|
+
action TEXT NOT NULL CHECK (action IN ('grant', 'revoke')),
|
|
110
|
+
audience TEXT NOT NULL CHECK (audience IN ('user', 'platform', 'public')),
|
|
111
|
+
principal_id TEXT,
|
|
112
|
+
policy_revision TEXT NOT NULL,
|
|
113
|
+
created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ', 'now'))
|
|
114
|
+
);
|
|
115
|
+
|
|
116
|
+
CREATE INDEX IF NOT EXISTS access_events_by_artifact ON artifact_access_events (artifact_id);
|
|
117
|
+
|
|
118
|
+
CREATE TABLE IF NOT EXISTS artifact_sources (
|
|
119
|
+
artifact_id TEXT PRIMARY KEY REFERENCES artifacts (id) ON DELETE CASCADE,
|
|
120
|
+
kind TEXT NOT NULL CHECK (kind IN ('inline-original', 'base-commit', 'recipe')),
|
|
121
|
+
commit_tx TEXT,
|
|
122
|
+
steps TEXT,
|
|
123
|
+
created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ', 'now'))
|
|
124
|
+
);
|
|
125
|
+
|
|
126
|
+
CREATE TABLE IF NOT EXISTS blob_ref_holders (
|
|
127
|
+
digest TEXT NOT NULL,
|
|
128
|
+
holder TEXT NOT NULL,
|
|
129
|
+
created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ', 'now')),
|
|
130
|
+
PRIMARY KEY (digest, holder)
|
|
131
|
+
);
|
|
132
|
+
CREATE INDEX IF NOT EXISTS ref_holders_by_digest ON blob_ref_holders (digest);
|
|
133
|
+
|
|
134
|
+
CREATE TABLE IF NOT EXISTS blob_pins (
|
|
135
|
+
digest TEXT NOT NULL,
|
|
136
|
+
reason TEXT NOT NULL,
|
|
137
|
+
created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ', 'now')),
|
|
138
|
+
PRIMARY KEY (digest, reason)
|
|
139
|
+
);
|
|
140
|
+
|
|
141
|
+
CREATE TABLE IF NOT EXISTS operation_keys (
|
|
142
|
+
storage_scope_id TEXT NOT NULL,
|
|
143
|
+
internal_key TEXT NOT NULL,
|
|
144
|
+
created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ', 'now')),
|
|
145
|
+
PRIMARY KEY (storage_scope_id, internal_key)
|
|
146
|
+
);
|
|
147
|
+
|
|
148
|
+
CREATE TABLE IF NOT EXISTS operation_receipts (
|
|
149
|
+
storage_scope_id TEXT NOT NULL,
|
|
150
|
+
internal_key TEXT NOT NULL,
|
|
151
|
+
command_codec TEXT NOT NULL,
|
|
152
|
+
command_hash TEXT NOT NULL,
|
|
153
|
+
receipt TEXT NOT NULL,
|
|
154
|
+
created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ', 'now')),
|
|
155
|
+
PRIMARY KEY (storage_scope_id, internal_key)
|
|
156
|
+
);
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
-- U1 — SQLite DDL for the activation host domain, owned by the SQLite
|
|
2
|
+
-- adapter. The Postgres `artifact_host.<table>` names map to plain
|
|
3
|
+
-- `<table>` (SQLite has no schemas); bigint -> INTEGER, jsonb -> TEXT,
|
|
4
|
+
-- generated columns use json_extract, and the regex CHECKs of
|
|
5
|
+
-- sql/0001_activation.sql are enforced in adapter code (SQLite has no
|
|
6
|
+
-- REGEXP without a host function). Immutability triggers are kept.
|
|
7
|
+
-- DB time is CAST((julianday('now') - 2440587.5) * 86400000 AS INTEGER) ms.
|
|
8
|
+
|
|
9
|
+
CREATE TABLE IF NOT EXISTS activation_namespaces (
|
|
10
|
+
namespace TEXT PRIMARY KEY CHECK (length(namespace) BETWEEN 1 AND 256),
|
|
11
|
+
generation INTEGER NOT NULL DEFAULT 1 CHECK (generation > 0)
|
|
12
|
+
);
|
|
13
|
+
|
|
14
|
+
CREATE TABLE IF NOT EXISTS activation_tickets (
|
|
15
|
+
namespace TEXT NOT NULL REFERENCES activation_namespaces (namespace),
|
|
16
|
+
generation INTEGER NOT NULL,
|
|
17
|
+
payload TEXT NOT NULL,
|
|
18
|
+
ticket_id TEXT GENERATED ALWAYS AS (json_extract(payload, '$.ticketId')) STORED NOT NULL,
|
|
19
|
+
subject_id TEXT GENERATED ALWAYS AS (json_extract(payload, '$.subjectId')) STORED NOT NULL,
|
|
20
|
+
artifact_id TEXT GENERATED ALWAYS AS (json_extract(payload, '$.artifactId')) STORED NOT NULL,
|
|
21
|
+
release_id TEXT GENERATED ALWAYS AS (json_extract(payload, '$.releaseId')) STORED NOT NULL,
|
|
22
|
+
channel TEXT GENERATED ALWAYS AS (json_extract(payload, '$.channel')) STORED NOT NULL,
|
|
23
|
+
expires_ms INTEGER GENERATED ALWAYS AS (json_extract(payload, '$.expiresAt')) STORED NOT NULL,
|
|
24
|
+
issued_ms INTEGER NOT NULL DEFAULT (CAST((julianday('now') - 2440587.5) * 86400000 AS INTEGER)),
|
|
25
|
+
-- SQLite forbids generated columns in a PRIMARY KEY; UNIQUE (which creates
|
|
26
|
+
-- the index the FK and lookups need) accepts them.
|
|
27
|
+
UNIQUE (namespace, ticket_id),
|
|
28
|
+
UNIQUE (namespace, generation, ticket_id, subject_id, artifact_id, release_id, channel, expires_ms),
|
|
29
|
+
CHECK (length(ticket_id) BETWEEN 1 AND 256 AND length(subject_id) BETWEEN 1 AND 256),
|
|
30
|
+
CHECK (length(artifact_id) BETWEEN 1 AND 256 AND length(release_id) BETWEEN 1 AND 256),
|
|
31
|
+
CHECK (channel IN ('stable', 'pinned')),
|
|
32
|
+
-- pg jsonb_typeof = 'number' covers all numbers; SQLite splits integer/real.
|
|
33
|
+
CHECK (json_type(payload, '$.expiresAt') IN ('integer', 'real')),
|
|
34
|
+
CHECK (expires_ms > issued_ms AND expires_ms <= issued_ms + 60000)
|
|
35
|
+
);
|
|
36
|
+
CREATE INDEX IF NOT EXISTS activation_tickets_expiry ON activation_tickets (namespace, expires_ms, ticket_id);
|
|
37
|
+
CREATE INDEX IF NOT EXISTS activation_tickets_generation ON activation_tickets (namespace, generation, ticket_id);
|
|
38
|
+
|
|
39
|
+
CREATE TABLE IF NOT EXISTS browser_flows (
|
|
40
|
+
namespace TEXT NOT NULL,
|
|
41
|
+
generation INTEGER NOT NULL,
|
|
42
|
+
payload TEXT NOT NULL,
|
|
43
|
+
flow_id TEXT GENERATED ALWAYS AS (json_extract(payload, '$.flowId')) STORED NOT NULL,
|
|
44
|
+
ticket_id TEXT GENERATED ALWAYS AS (json_extract(payload, '$.ticketId')) STORED NOT NULL,
|
|
45
|
+
subject_id TEXT GENERATED ALWAYS AS (json_extract(payload, '$.subjectId')) STORED NOT NULL,
|
|
46
|
+
artifact_id TEXT GENERATED ALWAYS AS (json_extract(payload, '$.artifactId')) STORED NOT NULL,
|
|
47
|
+
release_id TEXT GENERATED ALWAYS AS (json_extract(payload, '$.releaseId')) STORED NOT NULL,
|
|
48
|
+
channel TEXT GENERATED ALWAYS AS (json_extract(payload, '$.channel')) STORED NOT NULL,
|
|
49
|
+
expires_ms INTEGER GENERATED ALWAYS AS (json_extract(payload, '$.expiresAt')) STORED NOT NULL,
|
|
50
|
+
ticket_expires_ms INTEGER NOT NULL,
|
|
51
|
+
UNIQUE (namespace, flow_id),
|
|
52
|
+
UNIQUE (namespace, ticket_id),
|
|
53
|
+
FOREIGN KEY (namespace, generation, ticket_id, subject_id, artifact_id, release_id, channel, ticket_expires_ms)
|
|
54
|
+
REFERENCES activation_tickets
|
|
55
|
+
(namespace, generation, ticket_id, subject_id, artifact_id, release_id, channel, expires_ms)
|
|
56
|
+
ON DELETE CASCADE,
|
|
57
|
+
CHECK (length(flow_id) BETWEEN 1 AND 256),
|
|
58
|
+
CHECK (expires_ms <= ticket_expires_ms),
|
|
59
|
+
CHECK (json_type(payload, '$.expiresAt') IN ('integer', 'real')),
|
|
60
|
+
CHECK (length(json_extract(payload, '$.sessionId')) BETWEEN 1 AND 256 AND json_extract(payload, '$.sessionId') IS NOT NULL),
|
|
61
|
+
CHECK (length(json_extract(payload, '$.policyRevision')) BETWEEN 1 AND 256 AND json_extract(payload, '$.policyRevision') IS NOT NULL)
|
|
62
|
+
);
|
|
63
|
+
CREATE INDEX IF NOT EXISTS browser_flows_expiry ON browser_flows (namespace, expires_ms, flow_id);
|
|
64
|
+
CREATE INDEX IF NOT EXISTS browser_flows_generation ON browser_flows (namespace, generation, flow_id);
|
|
65
|
+
|
|
66
|
+
CREATE TRIGGER IF NOT EXISTS activation_tickets_immutable BEFORE UPDATE ON activation_tickets
|
|
67
|
+
BEGIN
|
|
68
|
+
SELECT RAISE(ABORT, 'activation records are immutable');
|
|
69
|
+
END;
|
|
70
|
+
CREATE TRIGGER IF NOT EXISTS browser_flows_immutable BEFORE UPDATE ON browser_flows
|
|
71
|
+
BEGIN
|
|
72
|
+
SELECT RAISE(ABORT, 'activation records are immutable');
|
|
73
|
+
END;
|