@sentropic/artifacts 0.2.12 → 0.2.14
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 +93 -0
- package/README.md +45 -10
- package/dist/adapters/local-blob.d.ts +3 -0
- package/dist/adapters/local-blob.js +93 -0
- package/dist/adapters/postgres-management.js +3 -2
- package/dist/adapters/postgres-reader-consent.d.ts +11 -0
- package/dist/adapters/postgres-reader-consent.js +109 -0
- package/dist/adapters/postgres-uploads.d.ts +14 -0
- package/dist/adapters/postgres-uploads.js +174 -0
- package/dist/adapters/postgres.js +4 -3
- package/dist/adapters/s3-uploads.d.ts +33 -0
- package/dist/adapters/s3-uploads.js +105 -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/content/headers.js +12 -0
- package/dist/http.d.ts +32 -2
- package/dist/http.js +615 -13
- package/dist/mcp-core.d.ts +3 -3
- package/dist/mcp-core.js +90 -4
- package/dist/profile/contracts.d.ts +1 -1
- package/dist/profile/contracts.js +7 -0
- package/dist/profile/index.js +43 -2
- package/dist/profile/radar.js +7 -0
- package/dist/profile/schemas.js +119 -0
- package/dist/profile/validation.d.ts +11 -0
- package/dist/profile/validation.js +98 -6
- package/dist/server/access.d.ts +2 -0
- package/dist/server/command-identity.d.ts +1 -1
- package/dist/server/command-identity.js +6 -3
- package/dist/server/consent.d.ts +65 -0
- package/dist/server/consent.js +42 -0
- package/dist/server/gc.d.ts +42 -0
- package/dist/server/gc.js +98 -0
- package/dist/server/management.d.ts +3 -1
- package/dist/server/management.js +48 -7
- package/dist/server/metrics.d.ts +21 -0
- package/dist/server/metrics.js +6 -0
- package/dist/server/mime.d.ts +26 -2
- package/dist/server/mime.js +124 -2
- package/dist/server/ports.d.ts +29 -0
- package/dist/server/ports.js +11 -0
- package/dist/server/publication-limits.d.ts +20 -0
- package/dist/server/publication-limits.js +27 -1
- package/dist/server/publication.d.ts +14 -0
- package/dist/server/publication.js +10 -2
- package/dist/server/reader-store.d.ts +58 -0
- package/dist/server/reader-store.js +109 -0
- package/dist/server/source-read.d.ts +12 -9
- package/dist/server/source-read.js +17 -5
- package/dist/server/templates.js +50 -2
- package/dist/server/upload-page.d.ts +157 -0
- package/dist/server/upload-page.js +438 -0
- package/dist/server/uploads.d.ts +229 -19
- package/dist/server/uploads.js +387 -80
- package/migrations/0007_uploads.sql +43 -0
- package/migrations/0008_reader_consent.sql +48 -0
- package/migrations/0009_upload_pages.sql +25 -0
- package/package.json +34 -1
- package/sql/reader-consent.sql +47 -0
- package/sql/sqlite/0001_artifacts.sql +156 -0
- package/sql/sqlite/0002_activation.sql +73 -0
package/dist/server/uploads.js
CHANGED
|
@@ -1,114 +1,421 @@
|
|
|
1
1
|
/**
|
|
2
|
-
*
|
|
2
|
+
* Files parity LOT 1 — durable upload sessions with a presigned signed PUT
|
|
3
|
+
* (design-r1 §B.3, review finding 3 applied).
|
|
3
4
|
*
|
|
4
|
-
*
|
|
5
|
-
*
|
|
6
|
-
*
|
|
7
|
-
*
|
|
8
|
-
*
|
|
9
|
-
*
|
|
10
|
-
*
|
|
11
|
-
*
|
|
5
|
+
* Bytes never travel through the model or the MCP host: `create_upload`
|
|
6
|
+
* mints a presigned PUT for exactly one staging key
|
|
7
|
+
* `artifacts/<scope>/staging/<uploadId>`; the local agent performs the PUT;
|
|
8
|
+
* `commit_upload` re-reads the staged object once and verifies the declared
|
|
9
|
+
* size and SHA-256 digest before anything is pinned.
|
|
10
|
+
*
|
|
11
|
+
* SigV4 note (review finding 3): a presigned PUT cannot carry a
|
|
12
|
+
* content-length RANGE (that exists only in POST policies), so the signature
|
|
13
|
+
* binds an EXACT Content-Length (the declared size) plus the checksum header
|
|
14
|
+
* (`x-amz-checksum-sha256`) whenever the digest is known at signing time;
|
|
15
|
+
* S3 itself rejects a PUT whose signed headers do not match. The digest is
|
|
16
|
+
* declared at commit, so the create-time signature binds content-type +
|
|
17
|
+
* exact content-length, the PUT must carry `x-amz-checksum-sha256` (S3
|
|
18
|
+
* validates it against the body, BadDigest on mismatch), and commit
|
|
19
|
+
* re-verifies size and digest server-side before pinning. Residual exposure
|
|
20
|
+
* of a leaked URL is bounded by the declared size (≤ 16 MiB), the
|
|
21
|
+
* per-principal open-session quota and the enforced sweeper (gc.ts).
|
|
22
|
+
*
|
|
23
|
+
* Sessions are durable rows (migration 0007 ALTERs `artifacts.uploads`);
|
|
24
|
+
* the byte store, session store and signer are injected ports — the memory
|
|
25
|
+
* doubles serve unit tests, the S3 adapter serves the host.
|
|
12
26
|
*/
|
|
13
27
|
import { createHash } from 'node:crypto';
|
|
28
|
+
import { validateFileBytes } from './mime.js';
|
|
29
|
+
export const UPLOAD_URL_TTL_SECONDS = 600; // presigned URL: ≤ 10 minutes
|
|
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;
|
|
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}$/;
|
|
40
|
+
/** Staging key of one upload session. */
|
|
41
|
+
export function stagingKey(storageScopeId, uploadId) {
|
|
42
|
+
return `artifacts/${storageScopeId}/staging/${uploadId}`;
|
|
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
|
+
}
|
|
48
|
+
/**
|
|
49
|
+
* Value of the `x-amz-checksum-sha256` header for a canonical `sha256:<hex>`
|
|
50
|
+
* digest: S3 expects the base64 of the raw digest bytes (no `sha256:` prefix).
|
|
51
|
+
*/
|
|
52
|
+
export function checksumHeaderValue(digest) {
|
|
53
|
+
const match = /^sha256:([0-9a-f]{64})$/.exec(digest);
|
|
54
|
+
if (match === null)
|
|
55
|
+
throw new Error(`invalid sha256 digest: ${digest}`);
|
|
56
|
+
return Buffer.from(match[1], 'hex').toString('base64');
|
|
57
|
+
}
|
|
58
|
+
/** Reject anything but a staging key, before any I/O. */
|
|
59
|
+
export function assertStagingKey(key) {
|
|
60
|
+
if (!STAGING_KEY_PATTERN.test(key)) {
|
|
61
|
+
throw new Error(`invalid staging key (must be artifacts/<scope>/staging/<uuid>): ${key}`);
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
/** Reject empty or escaping staging prefixes before enumeration. */
|
|
65
|
+
export function assertStagingPrefix(prefix) {
|
|
66
|
+
if (prefix.length === 0 || prefix.includes('..') || !prefix.endsWith('/staging/')) {
|
|
67
|
+
throw new Error(`invalid staging prefix: ${prefix}`);
|
|
68
|
+
}
|
|
69
|
+
}
|
|
14
70
|
/** In-memory StagingStore double for unit tests. */
|
|
15
|
-
export function createMemoryStaging() {
|
|
71
|
+
export function createMemoryStaging(now = () => new Date()) {
|
|
16
72
|
const staged = new Map();
|
|
17
73
|
return {
|
|
18
|
-
|
|
19
|
-
|
|
74
|
+
put(key, bytes) {
|
|
75
|
+
assertStagingKey(key);
|
|
76
|
+
staged.set(key, { bytes: new Uint8Array(bytes), lastModified: now().toISOString() });
|
|
77
|
+
return Promise.resolve();
|
|
78
|
+
},
|
|
79
|
+
get(key) {
|
|
80
|
+
assertStagingKey(key);
|
|
81
|
+
const entry = staged.get(key);
|
|
82
|
+
return Promise.resolve(entry === undefined ? undefined : new Uint8Array(entry.bytes));
|
|
83
|
+
},
|
|
84
|
+
delete(key) {
|
|
85
|
+
assertStagingKey(key);
|
|
86
|
+
staged.delete(key);
|
|
20
87
|
return Promise.resolve();
|
|
21
88
|
},
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
89
|
+
listKeys(prefix) {
|
|
90
|
+
assertStagingPrefix(prefix);
|
|
91
|
+
return Promise.resolve([...staged.keys()].filter((key) => key.startsWith(prefix)).sort());
|
|
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
|
+
},
|
|
99
|
+
};
|
|
100
|
+
}
|
|
101
|
+
/** In-memory UploadSessionStore double for unit tests. */
|
|
102
|
+
export function createMemoryUploadSessionStore(now = () => new Date()) {
|
|
103
|
+
const sessions = new Map();
|
|
104
|
+
const stagedFiles = new Map();
|
|
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 = {
|
|
116
|
+
create(session) {
|
|
117
|
+
sessions.set(session.uploadId, session);
|
|
118
|
+
return Promise.resolve();
|
|
119
|
+
},
|
|
120
|
+
get(uploadId) {
|
|
121
|
+
return Promise.resolve(sessions.get(uploadId));
|
|
122
|
+
},
|
|
123
|
+
countOpen(storageScopeId, ownerId) {
|
|
124
|
+
let count = 0;
|
|
125
|
+
for (const session of sessions.values()) {
|
|
126
|
+
if (session.storageScopeId === storageScopeId && session.ownerId === ownerId && session.state === 'open')
|
|
127
|
+
count += 1;
|
|
128
|
+
}
|
|
129
|
+
return Promise.resolve(count);
|
|
130
|
+
},
|
|
131
|
+
listExpiredOpen(at) {
|
|
132
|
+
return Promise.resolve([...sessions.values()].filter((session) => session.state === 'open' && new Date(session.expiresAt).getTime() <= at.getTime()).sort());
|
|
133
|
+
},
|
|
134
|
+
markCommitted(uploadId) {
|
|
135
|
+
const session = sessions.get(uploadId);
|
|
136
|
+
if (session === undefined)
|
|
137
|
+
throw new Error(`unknown upload: ${uploadId}`);
|
|
138
|
+
sessions.set(uploadId, { ...session, state: 'committed' });
|
|
139
|
+
return Promise.resolve();
|
|
140
|
+
},
|
|
141
|
+
markExpired(uploadId) {
|
|
142
|
+
const session = sessions.get(uploadId);
|
|
143
|
+
if (session === undefined)
|
|
25
144
|
throw new Error(`unknown upload: ${uploadId}`);
|
|
26
|
-
|
|
145
|
+
sessions.set(uploadId, { ...session, state: 'expired' });
|
|
146
|
+
return Promise.resolve();
|
|
147
|
+
},
|
|
148
|
+
recordStagedFile(record) {
|
|
149
|
+
stagedFiles.set(record.uploadId, record);
|
|
150
|
+
return Promise.resolve();
|
|
151
|
+
},
|
|
152
|
+
getStagedFile(uploadId) {
|
|
153
|
+
return Promise.resolve(stagedFiles.get(uploadId));
|
|
154
|
+
},
|
|
155
|
+
listStagedFiles(artifactId) {
|
|
156
|
+
return Promise.resolve([...stagedFiles.values()].filter((record) => record.artifactId === artifactId));
|
|
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));
|
|
27
176
|
},
|
|
28
|
-
|
|
29
|
-
|
|
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);
|
|
30
183
|
return Promise.resolve();
|
|
31
184
|
},
|
|
32
185
|
};
|
|
186
|
+
return store;
|
|
33
187
|
}
|
|
34
|
-
/**
|
|
35
|
-
|
|
188
|
+
/**
|
|
189
|
+
* Memory signer double: records every signed PUT and simulates S3's
|
|
190
|
+
* enforcement of the signed headers (exact content-length equality) and of
|
|
191
|
+
* the checksum header (body must hash to it when present).
|
|
192
|
+
*/
|
|
193
|
+
export function createMemoryUploadSigner() {
|
|
194
|
+
const signed = [];
|
|
195
|
+
const signer = {
|
|
196
|
+
signPut(input) {
|
|
197
|
+
assertStagingKey(input.key);
|
|
198
|
+
if (!Number.isSafeInteger(input.contentLength) || input.contentLength < 0) {
|
|
199
|
+
throw new Error('invalid signed content-length');
|
|
200
|
+
}
|
|
201
|
+
const expiresAt = new Date(Date.now() + input.expiresInSeconds * 1000).toISOString();
|
|
202
|
+
const url = `https://s3.test/${input.key}?X-Amz-Signature=mem-${signed.length}`;
|
|
203
|
+
const checksumHeader = input.checksumSha256 === undefined ? undefined : checksumHeaderValue(input.checksumSha256);
|
|
204
|
+
signed.push({ key: input.key, contentType: input.contentType, contentLength: input.contentLength,
|
|
205
|
+
...(checksumHeader === undefined ? {} : { checksumSha256: checksumHeader }),
|
|
206
|
+
expiresAt, url });
|
|
207
|
+
return Promise.resolve({
|
|
208
|
+
url,
|
|
209
|
+
method: 'PUT',
|
|
210
|
+
headers: {
|
|
211
|
+
'content-type': input.contentType,
|
|
212
|
+
'content-length': String(input.contentLength),
|
|
213
|
+
...(checksumHeader === undefined ? {} : { 'x-amz-checksum-sha256': checksumHeader }),
|
|
214
|
+
},
|
|
215
|
+
expiresAt,
|
|
216
|
+
});
|
|
217
|
+
},
|
|
218
|
+
};
|
|
219
|
+
return {
|
|
220
|
+
signer,
|
|
221
|
+
signed,
|
|
222
|
+
/** Simulate the client PUT against "S3": signed headers are enforced exactly. */
|
|
223
|
+
put(signedPut, bytes, headers) {
|
|
224
|
+
if (String(bytes.length) !== headers['content-length'] || bytes.length !== signedPut.contentLength) {
|
|
225
|
+
throw new Error(`content-length mismatch: signed ${signedPut.contentLength}, body ${bytes.length}`);
|
|
226
|
+
}
|
|
227
|
+
if (headers['content-type'] !== signedPut.contentType) {
|
|
228
|
+
throw new Error('content-type mismatch with the signed header');
|
|
229
|
+
}
|
|
230
|
+
if (signedPut.checksumSha256 !== undefined && headers['x-amz-checksum-sha256'] !== signedPut.checksumSha256) {
|
|
231
|
+
throw new Error('x-amz-checksum-sha256 mismatch with the signed header');
|
|
232
|
+
}
|
|
233
|
+
if (headers['x-amz-checksum-sha256'] !== undefined &&
|
|
234
|
+
createHash('sha256').update(bytes).digest('base64') !== headers['x-amz-checksum-sha256']) {
|
|
235
|
+
throw new Error('BadDigest: body does not match x-amz-checksum-sha256');
|
|
236
|
+
}
|
|
237
|
+
},
|
|
238
|
+
};
|
|
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
|
+
}
|
|
248
|
+
export function createUploadService(deps, options) {
|
|
249
|
+
const now = options.now ?? (() => new Date());
|
|
250
|
+
const ids = options.ids ?? (() => crypto.randomUUID());
|
|
36
251
|
if (!Number.isSafeInteger(options.maxUploadBytes) || options.maxUploadBytes < 1) {
|
|
37
252
|
throw new Error('invalid upload byte budget');
|
|
38
253
|
}
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
const session = sessions.get(uploadId);
|
|
42
|
-
if (session === undefined)
|
|
43
|
-
throw new Error(`unknown upload: ${uploadId}`);
|
|
44
|
-
if (session.committed)
|
|
45
|
-
throw new Error(`upload already committed: ${uploadId}`);
|
|
46
|
-
if (session.busy)
|
|
47
|
-
throw new Error(`upload conflict: operation in progress for ${uploadId}`);
|
|
48
|
-
return session;
|
|
254
|
+
if (!Number.isSafeInteger(options.maxSessionsPerPrincipal) || options.maxSessionsPerPrincipal < 1) {
|
|
255
|
+
throw new Error('invalid upload session quota');
|
|
49
256
|
}
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
try {
|
|
54
|
-
return await run(session);
|
|
55
|
-
}
|
|
56
|
-
finally {
|
|
57
|
-
session.busy = false;
|
|
58
|
-
}
|
|
257
|
+
if (options.stagingQuotaBytesPerScope !== undefined &&
|
|
258
|
+
(!Number.isSafeInteger(options.stagingQuotaBytesPerScope) || options.stagingQuotaBytesPerScope < 1)) {
|
|
259
|
+
throw new Error('invalid scope staging quota');
|
|
59
260
|
}
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
}
|
|
65
|
-
return session.maxSize - session.size;
|
|
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');
|
|
66
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
|
+
};
|
|
67
272
|
return {
|
|
68
|
-
|
|
69
|
-
async begin(input) {
|
|
273
|
+
async create(input) {
|
|
70
274
|
if (input.maxSize !== undefined && (!Number.isSafeInteger(input.maxSize) || input.maxSize < 1)) {
|
|
71
275
|
throw new Error('invalid upload byte budget');
|
|
72
276
|
}
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
return
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
277
|
+
if (input.pageSessionId !== undefined && (input.pageFileLimit === undefined ||
|
|
278
|
+
!Number.isSafeInteger(input.pageFileLimit) || input.pageFileLimit < 1)) {
|
|
279
|
+
throw new Error('invalid page file bound');
|
|
280
|
+
}
|
|
281
|
+
const maxSize = Math.min(input.maxSize ?? options.maxUploadBytes, options.maxUploadBytes);
|
|
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
|
+
}
|
|
88
305
|
}
|
|
89
|
-
const
|
|
90
|
-
const
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
await
|
|
94
|
-
|
|
95
|
-
|
|
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
|
+
};
|
|
96
328
|
});
|
|
97
329
|
},
|
|
98
|
-
|
|
99
|
-
return
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
throw new Error(`upload size mismatch for ${uploadId}: staged ${bytes.length}, declared ${expected.size}`);
|
|
330
|
+
sessionForCommit(input) {
|
|
331
|
+
return deps.sessions.get(input.uploadId).then((session) => {
|
|
332
|
+
if (session === undefined || session.artifactId !== input.artifactId ||
|
|
333
|
+
session.storageScopeId !== input.storageScopeId || session.ownerId !== input.ownerId) {
|
|
334
|
+
throw new Error(`unknown upload for this artifact/owner/scope: ${input.uploadId}`);
|
|
104
335
|
}
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
336
|
+
if (session.state !== 'open')
|
|
337
|
+
throw new Error(`upload not open (${session.state}): ${input.uploadId}`);
|
|
338
|
+
if (new Date(session.expiresAt).getTime() <= now().getTime()) {
|
|
339
|
+
throw new Error(`upload session expired: ${input.uploadId}`);
|
|
108
340
|
}
|
|
109
|
-
session
|
|
110
|
-
return { digest: actual, size: bytes.length };
|
|
341
|
+
return session;
|
|
111
342
|
});
|
|
112
343
|
},
|
|
344
|
+
verifyStaged(session, bytes, expected) {
|
|
345
|
+
if (bytes.length !== expected.size) {
|
|
346
|
+
throw new Error(`upload size mismatch for ${session.uploadId}: staged ${bytes.length}, declared ${expected.size}`);
|
|
347
|
+
}
|
|
348
|
+
const actual = `sha256:${createHash('sha256').update(bytes).digest('hex')}`;
|
|
349
|
+
if (actual !== expected.digest) {
|
|
350
|
+
throw new Error(`upload digest mismatch for ${session.uploadId}: staged ${actual}`);
|
|
351
|
+
}
|
|
352
|
+
if (expected.mimeType !== session.mimeType) {
|
|
353
|
+
throw new Error(`upload MIME mismatch for ${session.uploadId}: session ${session.mimeType}, declared ${expected.mimeType}`);
|
|
354
|
+
}
|
|
355
|
+
validateFileBytes(expected.mimeType, bytes);
|
|
356
|
+
},
|
|
357
|
+
async completeCommit(session, record) {
|
|
358
|
+
const staged = {
|
|
359
|
+
uploadId: session.uploadId, artifactId: session.artifactId, createdAt: now().toISOString(),
|
|
360
|
+
path: record.path, mimeType: record.mimeType, digest: record.digest, size: record.size,
|
|
361
|
+
...(session.pageSessionId === undefined ? {} : { pageSessionId: session.pageSessionId }),
|
|
362
|
+
};
|
|
363
|
+
await deps.sessions.recordStagedFile(staged);
|
|
364
|
+
await deps.sessions.markCommitted(session.uploadId);
|
|
365
|
+
return staged;
|
|
366
|
+
},
|
|
113
367
|
};
|
|
114
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,43 @@
|
|
|
1
|
+
-- Files parity LOT 1 — durable upload sessions (design-r1 §B.3, review
|
|
2
|
+
-- files-design-large4_r1 finding 1: 0001 already creates artifacts.uploads,
|
|
3
|
+
-- so this migration ALTERs it instead of recreating it).
|
|
4
|
+
--
|
|
5
|
+
-- 0001's uploads table was an ephemeral staging ledger (id, max_size, size,
|
|
6
|
+
-- mime_type, state, created_at) with no artifact binding and no expiry. LOT 1
|
|
7
|
+
-- binds every session to its artifact, storage scope and owner, adds
|
|
8
|
+
-- expires_at for the enforced staging sweeper (gc.ts), and adds the
|
|
9
|
+
-- staged-file records that commit_upload writes and publish_bundle
|
|
10
|
+
-- references. Pre-existing rows belong to the never-wired append surface:
|
|
11
|
+
-- they are discarded (not deleted) so no stale session stays open.
|
|
12
|
+
|
|
13
|
+
ALTER TABLE artifacts.uploads
|
|
14
|
+
ADD COLUMN IF NOT EXISTS artifact_id UUID REFERENCES artifacts.artifacts (id) ON DELETE CASCADE,
|
|
15
|
+
ADD COLUMN IF NOT EXISTS storage_scope_id TEXT REFERENCES artifacts.storage_scopes (id),
|
|
16
|
+
ADD COLUMN IF NOT EXISTS owner_id TEXT,
|
|
17
|
+
ADD COLUMN IF NOT EXISTS expires_at TIMESTAMPTZ;
|
|
18
|
+
|
|
19
|
+
-- Pre-existing rows have no artifact binding: close them, keep the audit trail.
|
|
20
|
+
UPDATE artifacts.uploads SET state = 'discarded' WHERE artifact_id IS NULL;
|
|
21
|
+
|
|
22
|
+
-- 'expired' is set by the sweeper when expires_at passes with the session open.
|
|
23
|
+
ALTER TABLE artifacts.uploads DROP CONSTRAINT IF EXISTS uploads_state_check;
|
|
24
|
+
ALTER TABLE artifacts.uploads
|
|
25
|
+
ADD CONSTRAINT uploads_state_check CHECK (state IN ('open', 'committed', 'discarded', 'expired'));
|
|
26
|
+
|
|
27
|
+
CREATE INDEX IF NOT EXISTS uploads_by_expiry ON artifacts.uploads (state, expires_at)
|
|
28
|
+
WHERE state = 'open';
|
|
29
|
+
|
|
30
|
+
-- Staged files: one row per committed upload, referenced by publish_bundle
|
|
31
|
+
-- assets ({path, uploadId}). The blob itself is content-addressed under
|
|
32
|
+
-- artifacts/<scope>/blobs/sha256/<hex>; this row carries the manifest path.
|
|
33
|
+
CREATE TABLE IF NOT EXISTS artifacts.staged_files (
|
|
34
|
+
upload_id UUID PRIMARY KEY REFERENCES artifacts.uploads (id) ON DELETE CASCADE,
|
|
35
|
+
artifact_id UUID NOT NULL REFERENCES artifacts.artifacts (id) ON DELETE CASCADE,
|
|
36
|
+
path TEXT NOT NULL,
|
|
37
|
+
mime_type TEXT NOT NULL,
|
|
38
|
+
digest TEXT NOT NULL CHECK (digest ~ '^sha256:[0-9a-f]{64}$'),
|
|
39
|
+
size INTEGER NOT NULL CHECK (size >= 0),
|
|
40
|
+
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
|
41
|
+
UNIQUE (artifact_id, path)
|
|
42
|
+
);
|
|
43
|
+
CREATE INDEX IF NOT EXISTS staged_files_by_artifact ON artifacts.staged_files (artifact_id);
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
-- Train 2026-11-04 — persistent reader consent, lot 1a (wagon C).
|
|
2
|
+
--
|
|
3
|
+
-- Train-numbered wrapper of packages/artifacts/sql/reader-consent.sql:
|
|
4
|
+
-- wagon lanes never pre-assign migration numbers, so the train assigns the
|
|
5
|
+
-- next additive number at land time. The statements below are identical to
|
|
6
|
+
-- the reviewed lot-1a body (consent rows authorize a data class; they never
|
|
7
|
+
-- record data use: no basket identifier, no query, no page data, no
|
|
8
|
+
-- session/device/network data). Additive only: IF NOT EXISTS guards, no
|
|
9
|
+
-- nullable owner column participates in uniqueness, storage_scope_id is part
|
|
10
|
+
-- of every unique key so isolation is structural.
|
|
11
|
+
|
|
12
|
+
CREATE TABLE IF NOT EXISTS artifacts.reader_consents (
|
|
13
|
+
consent_id UUID PRIMARY KEY,
|
|
14
|
+
storage_scope_id TEXT NOT NULL,
|
|
15
|
+
reader_account_id TEXT NOT NULL,
|
|
16
|
+
artifact_id UUID NOT NULL REFERENCES artifacts.artifacts (id) ON DELETE CASCADE,
|
|
17
|
+
scope_id TEXT NOT NULL,
|
|
18
|
+
scope_version TEXT NOT NULL,
|
|
19
|
+
granted_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
|
20
|
+
granted_via TEXT NOT NULL DEFAULT 'reader_screen' CHECK (granted_via = 'reader_screen'),
|
|
21
|
+
revoked_at TIMESTAMPTZ NULL,
|
|
22
|
+
revoked_by TEXT NULL CHECK (revoked_by IN ('self', 'admin', 'cascade'))
|
|
23
|
+
);
|
|
24
|
+
|
|
25
|
+
-- At most one live row per (scope, reader, artifact, scope, version);
|
|
26
|
+
-- re-grant after revoke mints a new row, history stays auditable.
|
|
27
|
+
CREATE UNIQUE INDEX IF NOT EXISTS reader_consents_live_uniq ON artifacts.reader_consents
|
|
28
|
+
(storage_scope_id, reader_account_id, artifact_id, scope_id, scope_version)
|
|
29
|
+
WHERE revoked_at IS NULL;
|
|
30
|
+
CREATE INDEX IF NOT EXISTS reader_consents_by_reader ON artifacts.reader_consents
|
|
31
|
+
(storage_scope_id, reader_account_id, granted_at, consent_id);
|
|
32
|
+
|
|
33
|
+
-- Append-only audit, no content (actor, surface and version only).
|
|
34
|
+
CREATE TABLE IF NOT EXISTS artifacts.reader_consent_events (
|
|
35
|
+
id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
|
|
36
|
+
consent_id UUID NOT NULL,
|
|
37
|
+
storage_scope_id TEXT NOT NULL,
|
|
38
|
+
reader_account_id TEXT NOT NULL,
|
|
39
|
+
artifact_id UUID NOT NULL,
|
|
40
|
+
scope_id TEXT NOT NULL,
|
|
41
|
+
scope_version TEXT NOT NULL,
|
|
42
|
+
action TEXT NOT NULL CHECK (action IN ('grant', 'revoke')),
|
|
43
|
+
actor TEXT NOT NULL,
|
|
44
|
+
surface TEXT NOT NULL CHECK (surface IN ('screen', 'api', 'mcp', 'cascade')),
|
|
45
|
+
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
|
46
|
+
);
|
|
47
|
+
CREATE INDEX IF NOT EXISTS reader_consent_events_by_artifact ON artifacts.reader_consent_events
|
|
48
|
+
(storage_scope_id, artifact_id, id);
|
|
@@ -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;
|