@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
|
@@ -0,0 +1,438 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Files parity LOT 2 §A — browser upload page (signatures; body in Lot 2).
|
|
3
|
+
*
|
|
4
|
+
* A web user provides images, PDF, video, fonts from their own disk. Bytes
|
|
5
|
+
* go browser → S3 directly; the model never produces, reads or relays them.
|
|
6
|
+
* Retrieval is pull: `artifacts_list_assets {pageSessionId}`, then the model
|
|
7
|
+
* publishes with `{path, uploadId}` assets (LOT 1 bundle, unchanged).
|
|
8
|
+
*/
|
|
9
|
+
import { createHash, createHmac, randomBytes, timingSafeEqual } from 'node:crypto';
|
|
10
|
+
import { SERVER_MAX_UPLOAD_SESSIONS_PER_PRINCIPAL } from './publication-limits.js';
|
|
11
|
+
import { commitStagedUpload, createUploadService } from './uploads.js';
|
|
12
|
+
export const UPLOAD_PAGE_TTL_MS = 20 * 60 * 1000;
|
|
13
|
+
export const UPLOAD_PAGE_COOKIE = '__Host-artifacts_upload';
|
|
14
|
+
export const SERVER_MAX_OPEN_UPLOAD_PAGES = 4;
|
|
15
|
+
export function createMemoryUploadPageStore() {
|
|
16
|
+
const rows = new Map();
|
|
17
|
+
const live = (row) => row.state === 'open' || row.state === 'exchanged';
|
|
18
|
+
return {
|
|
19
|
+
create(row) {
|
|
20
|
+
if (rows.has(row.pageSessionId))
|
|
21
|
+
throw new Error(`duplicate upload page: ${row.pageSessionId}`);
|
|
22
|
+
rows.set(row.pageSessionId, row);
|
|
23
|
+
return Promise.resolve();
|
|
24
|
+
},
|
|
25
|
+
get(pageSessionId) {
|
|
26
|
+
return Promise.resolve(rows.get(pageSessionId));
|
|
27
|
+
},
|
|
28
|
+
countActiveByOwner(ownerId) {
|
|
29
|
+
let count = 0;
|
|
30
|
+
for (const row of rows.values()) {
|
|
31
|
+
if (row.ownerId === ownerId && live(row))
|
|
32
|
+
count += 1;
|
|
33
|
+
}
|
|
34
|
+
return Promise.resolve(count);
|
|
35
|
+
},
|
|
36
|
+
listExpiredPages(at) {
|
|
37
|
+
return Promise.resolve([...rows.values()].filter((row) => live(row) && new Date(row.expiresAt).getTime() <= at.getTime()));
|
|
38
|
+
},
|
|
39
|
+
markExchanged(pageSessionId, at) {
|
|
40
|
+
const row = rows.get(pageSessionId);
|
|
41
|
+
if (row === undefined)
|
|
42
|
+
throw new Error(`unknown upload page: ${pageSessionId}`);
|
|
43
|
+
if (row.state !== 'open')
|
|
44
|
+
throw new Error(`upload page not open (${row.state}): ${pageSessionId}`);
|
|
45
|
+
rows.set(pageSessionId, { ...row, state: 'exchanged', exchangedAt: at });
|
|
46
|
+
return Promise.resolve();
|
|
47
|
+
},
|
|
48
|
+
markExpired(pageSessionId) {
|
|
49
|
+
const row = rows.get(pageSessionId);
|
|
50
|
+
if (row === undefined)
|
|
51
|
+
throw new Error(`unknown upload page: ${pageSessionId}`);
|
|
52
|
+
rows.set(pageSessionId, { ...row, state: 'expired' });
|
|
53
|
+
return Promise.resolve();
|
|
54
|
+
},
|
|
55
|
+
};
|
|
56
|
+
}
|
|
57
|
+
/**
|
|
58
|
+
* HMAC cookie signer for one upload page (mirrors `content/grants.ts`).
|
|
59
|
+
* The cookie carries `{sid, exp}`; the page row carries state and expiry, so
|
|
60
|
+
* a stolen cookie is bounded by the row TTL and the owner binding.
|
|
61
|
+
*/
|
|
62
|
+
export function createHmacUploadPageCookieSigner(options) {
|
|
63
|
+
const secret = typeof options.secret === 'string'
|
|
64
|
+
? new TextEncoder().encode(options.secret)
|
|
65
|
+
: options.secret;
|
|
66
|
+
if (secret.length === 0)
|
|
67
|
+
throw new Error('invalid page cookie signer: empty secret');
|
|
68
|
+
const clock = options.clock ?? (() => Date.now());
|
|
69
|
+
const ttlMs = (options.ttlSeconds ?? UPLOAD_PAGE_TTL_MS / 1000) * 1000;
|
|
70
|
+
const encode = (claims) => Buffer.from(JSON.stringify(claims), 'utf8').toString('base64url');
|
|
71
|
+
return {
|
|
72
|
+
sign(pageSessionId) {
|
|
73
|
+
if (pageSessionId.length === 0)
|
|
74
|
+
throw new Error('invalid page cookie: empty session');
|
|
75
|
+
const payload = encode({ sid: pageSessionId, exp: clock() + ttlMs });
|
|
76
|
+
const sig = createHmac('sha256', secret).update(payload, 'utf8').digest('base64url');
|
|
77
|
+
return `${payload}.${sig}`;
|
|
78
|
+
},
|
|
79
|
+
verify(value) {
|
|
80
|
+
const parts = value.split('.');
|
|
81
|
+
if (parts.length !== 2 || parts[0] === undefined || parts[1] === undefined) {
|
|
82
|
+
throw new Error('invalid page cookie: malformed token');
|
|
83
|
+
}
|
|
84
|
+
const expected = Buffer.from(createHmac('sha256', secret).update(parts[0], 'utf8').digest('base64url'), 'utf8');
|
|
85
|
+
const actual = Buffer.from(parts[1], 'utf8');
|
|
86
|
+
if (expected.length !== actual.length || !timingSafeEqual(expected, actual)) {
|
|
87
|
+
throw new Error('invalid page cookie: signature mismatch');
|
|
88
|
+
}
|
|
89
|
+
let claims;
|
|
90
|
+
try {
|
|
91
|
+
claims = JSON.parse(Buffer.from(parts[0], 'base64url').toString('utf8'));
|
|
92
|
+
}
|
|
93
|
+
catch {
|
|
94
|
+
throw new Error('invalid page cookie: malformed claims');
|
|
95
|
+
}
|
|
96
|
+
if (typeof claims.sid !== 'string' || claims.sid.length === 0 ||
|
|
97
|
+
!Number.isFinite(claims.exp) || claims.exp <= clock()) {
|
|
98
|
+
throw new Error('invalid page cookie: expired or malformed claims');
|
|
99
|
+
}
|
|
100
|
+
return claims.sid;
|
|
101
|
+
},
|
|
102
|
+
};
|
|
103
|
+
}
|
|
104
|
+
/**
|
|
105
|
+
* Host-only page cookie value (review finding 1: the `__Host-` prefix
|
|
106
|
+
* requires `Path=/`, exactly like the shipped grant cookie).
|
|
107
|
+
*/
|
|
108
|
+
export function buildUploadPageCookie(value, maxAgeSeconds) {
|
|
109
|
+
if (value.length === 0 || !Number.isSafeInteger(maxAgeSeconds) || maxAgeSeconds < 1) {
|
|
110
|
+
throw new Error('invalid page cookie value');
|
|
111
|
+
}
|
|
112
|
+
return `${UPLOAD_PAGE_COOKIE}=${value}; Path=/; HttpOnly; Secure; SameSite=Strict; Max-Age=${maxAgeSeconds}`;
|
|
113
|
+
}
|
|
114
|
+
export function parseUploadPageCookie(header) {
|
|
115
|
+
if (header === undefined)
|
|
116
|
+
return undefined;
|
|
117
|
+
for (const part of header.split(';')) {
|
|
118
|
+
const trimmed = part.trim();
|
|
119
|
+
if (trimmed.startsWith(`${UPLOAD_PAGE_COOKIE}=`)) {
|
|
120
|
+
const value = trimmed.slice(UPLOAD_PAGE_COOKIE.length + 1);
|
|
121
|
+
return value.length === 0 ? undefined : value;
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
return undefined;
|
|
125
|
+
}
|
|
126
|
+
/** Page CSP (§A.4): no external assets; S3 origins are host-supplied. */
|
|
127
|
+
export function uploadPageCsp(s3Origins) {
|
|
128
|
+
if (s3Origins.length === 0 || s3Origins.some((origin) => !/^https:\/\/[A-Za-z0-9.-]+(?::\d+)?$/.test(origin))) {
|
|
129
|
+
throw new Error('invalid page S3 origins: the page refuses to render without them');
|
|
130
|
+
}
|
|
131
|
+
return ['default-src \'none\'', 'script-src \'self\'', 'style-src \'self\'',
|
|
132
|
+
'img-src \'self\' blob:', 'font-src \'self\'', `connect-src 'self' ${s3Origins.join(' ')}`,
|
|
133
|
+
'base-uri \'none\'', 'form-action \'none\'', 'frame-ancestors \'none\''].join('; ');
|
|
134
|
+
}
|
|
135
|
+
/**
|
|
136
|
+
* Self-contained static upload page (no external assets). Bytes travel
|
|
137
|
+
* browser → S3 via raw PUT (FormData is banned: multipart wrapping changes
|
|
138
|
+
* length and type); one session per file with `size = File.size`; at most 4
|
|
139
|
+
* PUTs in flight; commit each file before opening further sessions.
|
|
140
|
+
*/
|
|
141
|
+
export function renderUploadPage(options) {
|
|
142
|
+
const csp = uploadPageCsp(options.s3Origins);
|
|
143
|
+
const config = JSON.stringify({ s3Origins: [...options.s3Origins] });
|
|
144
|
+
return `<!doctype html>
|
|
145
|
+
<html lang="en">
|
|
146
|
+
<head>
|
|
147
|
+
<meta charset="utf-8">
|
|
148
|
+
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
149
|
+
<meta http-equiv="Content-Security-Policy" content="${csp.replace(/"/g, '"')}">
|
|
150
|
+
<meta name="color-scheme" content="light dark">
|
|
151
|
+
<title>Upload files</title>
|
|
152
|
+
<style>body{font-family:system-ui,sans-serif;max-width:42rem;margin:2rem auto;padding:0 1rem}
|
|
153
|
+
#drop{border:2px dashed #888;border-radius:.5rem;padding:2rem;text-align:center;margin:1rem 0}
|
|
154
|
+
#drop.over{border-color:#06c;background:#06c1}
|
|
155
|
+
li{margin:.25rem 0;font-size:.9rem}pre{white-space:pre-wrap;word-break:break-all;background:#8882;padding:1rem}</style>
|
|
156
|
+
</head>
|
|
157
|
+
<body>
|
|
158
|
+
<h1>Upload files</h1>
|
|
159
|
+
<p>Pick files from your disk. They upload straight to object storage; the assistant never sees the bytes.
|
|
160
|
+
When every file shows <b>staged</b>, go back to the chat and say <b>done</b>.</p>
|
|
161
|
+
<div id="drop">Drop files or folders here, paste an image, or
|
|
162
|
+
<input id="picker" type="file" multiple> <input id="folder" type="file" webkitdirectory></div>
|
|
163
|
+
<ul id="files"></ul>
|
|
164
|
+
<button id="copy" type="button">Copy asset list (chat fallback)</button>
|
|
165
|
+
<pre id="assetJson" hidden></pre>
|
|
166
|
+
<p id="error" role="alert"></p>
|
|
167
|
+
<script>window.__ARTIFACTS_UPLOAD__ = ${config};</script>
|
|
168
|
+
<script>
|
|
169
|
+
'use strict';
|
|
170
|
+
const sessionId = location.pathname.split('/').filter(Boolean).pop();
|
|
171
|
+
let token = (location.hash.match(/#t=([^&]+)/) || [])[1] || '';
|
|
172
|
+
const filesEl = document.getElementById('files');
|
|
173
|
+
const errorEl = document.getElementById('error');
|
|
174
|
+
const fail = (message) => { errorEl.textContent = String(message); };
|
|
175
|
+
if (!sessionId || !token) fail('This upload link is incomplete. Ask the assistant for a fresh one.');
|
|
176
|
+
const base = location.pathname.replace(/\\/+$/, '').replace(/artifacts\\/upload\\/[^/]+$/, 'artifacts/upload/' + sessionId);
|
|
177
|
+
const api = async (path, body, method) => {
|
|
178
|
+
const response = await fetch(base + '/' + path, { method: method || 'POST',
|
|
179
|
+
headers: { 'content-type': 'application/json', 'x-artifact-upload': '1' },
|
|
180
|
+
body: body === undefined ? undefined : JSON.stringify(body), credentials: 'same-origin' });
|
|
181
|
+
if (!response.ok) throw new Error(path + ' failed: ' + response.status);
|
|
182
|
+
return response.json();
|
|
183
|
+
};
|
|
184
|
+
const EXT_TYPES = { woff2: 'font/woff', avif: 'image/avif', ico: 'image/x-icon' };
|
|
185
|
+
const chunked = (bytes, f) => {
|
|
186
|
+
const view = new Uint8Array(bytes);
|
|
187
|
+
let out = '';
|
|
188
|
+
for (let i = 0; i < view.length; i += 0x8000) out += f(view.subarray(i, i + 0x8000)));
|
|
189
|
+
return out;
|
|
190
|
+
};
|
|
191
|
+
const b64 = (bytes) => btoa(chunked(bytes, (part) => String.fromCharCode(...part)));
|
|
192
|
+
const hex = (bytes) => chunked(bytes, (part) => [...part].map((b) => b.toString(16).padStart(2, '0')).join(''));
|
|
193
|
+
const row = (path) => {
|
|
194
|
+
const li = document.createElement('li');
|
|
195
|
+
li.textContent = path + ': queued';
|
|
196
|
+
filesEl.appendChild(li);
|
|
197
|
+
return (text) => { li.textContent = path + ': ' + text; };
|
|
198
|
+
};
|
|
199
|
+
async function stage(file, relPath) {
|
|
200
|
+
const setStatus = row(relPath);
|
|
201
|
+
const ext = (relPath.split('.').pop() || '').toLowerCase();
|
|
202
|
+
const mimeType = file.type || EXT_TYPES[ext] || 'application/octet-stream';
|
|
203
|
+
const created = await api('files', { path: relPath, mimeType, size: file.size });
|
|
204
|
+
setStatus('uploading');
|
|
205
|
+
const buffer = await file.arrayBuffer();
|
|
206
|
+
const put = async (upload) => fetch(upload.uploadUrl, { method: 'PUT', body: file,
|
|
207
|
+
headers: { 'content-type': upload.requiredHeaders['content-type'],
|
|
208
|
+
'x-amz-checksum-sha256': b64(await crypto.subtle.digest('SHA-256', buffer)) } });
|
|
209
|
+
let upload = created;
|
|
210
|
+
let response = await put(upload);
|
|
211
|
+
if (!response.ok) {
|
|
212
|
+
upload = await api('files', { path: relPath, mimeType, size: file.size });
|
|
213
|
+
response = await put(upload);
|
|
214
|
+
}
|
|
215
|
+
if (!response.ok) throw new Error('PUT failed: ' + response.status);
|
|
216
|
+
setStatus('committing');
|
|
217
|
+
const digest = 'sha256:' + hex(await crypto.subtle.digest('SHA-256', buffer));
|
|
218
|
+
try {
|
|
219
|
+
await api('files/' + upload.uploadId + '/commit', { path: relPath, mimeType, digest,
|
|
220
|
+
size: file.size, idempotencyKey: crypto.randomUUID() });
|
|
221
|
+
} catch (error) {
|
|
222
|
+
const renamed = prompt('That path is already staged. Enter a new path, or cancel to skip:', relPath);
|
|
223
|
+
if (!renamed) throw error;
|
|
224
|
+
await api('files/' + upload.uploadId + '/commit', { path: renamed, mimeType, digest,
|
|
225
|
+
size: file.size, idempotencyKey: crypto.randomUUID() });
|
|
226
|
+
}
|
|
227
|
+
setStatus('staged');
|
|
228
|
+
}
|
|
229
|
+
async function runAll(entries) {
|
|
230
|
+
const workers = [];
|
|
231
|
+
const queue = [...entries];
|
|
232
|
+
for (let i = 0; i < 4; i += 1) {
|
|
233
|
+
workers.push((async () => {
|
|
234
|
+
while (queue.length > 0) {
|
|
235
|
+
const next = queue.shift();
|
|
236
|
+
try { await stage(next.file, next.path); }
|
|
237
|
+
catch (error) { row(next.path)(String(error && error.message || error)); }
|
|
238
|
+
}
|
|
239
|
+
})());
|
|
240
|
+
}
|
|
241
|
+
await Promise.all(workers);
|
|
242
|
+
}
|
|
243
|
+
const collect = (list) => [...list].map((file) => ({ file,
|
|
244
|
+
path: file.webkitRelativePath || file.name }));
|
|
245
|
+
document.getElementById('picker').addEventListener('change', (event) => { runAll(collect(event.target.files)); });
|
|
246
|
+
document.getElementById('folder').addEventListener('change', (event) => { runAll(collect(event.target.files)); });
|
|
247
|
+
const drop = document.getElementById('drop');
|
|
248
|
+
drop.addEventListener('dragover', (event) => { event.preventDefault(); drop.classList.add('over'); });
|
|
249
|
+
drop.addEventListener('dragleave', () => drop.classList.remove('over'));
|
|
250
|
+
drop.addEventListener('drop', (event) => {
|
|
251
|
+
event.preventDefault();
|
|
252
|
+
drop.classList.remove('over');
|
|
253
|
+
runAll(collect(event.dataTransfer.files));
|
|
254
|
+
});
|
|
255
|
+
document.addEventListener('paste', (event) => {
|
|
256
|
+
const images = [...(event.clipboardData ? event.clipboardData.files : [])]
|
|
257
|
+
.filter((file) => file.type.startsWith('image/'));
|
|
258
|
+
if (images.length > 0) runAll(collect(images));
|
|
259
|
+
});
|
|
260
|
+
document.getElementById('copy').addEventListener('click', async () => {
|
|
261
|
+
const staged = await api('files', undefined, 'GET');
|
|
262
|
+
const pre = document.getElementById('assetJson');
|
|
263
|
+
pre.hidden = false;
|
|
264
|
+
pre.textContent = JSON.stringify(staged, null, 2);
|
|
265
|
+
});
|
|
266
|
+
api('exchange', { token }).then(() => {
|
|
267
|
+
history.replaceState(null, '', location.pathname);
|
|
268
|
+
token = '';
|
|
269
|
+
}).catch(fail);
|
|
270
|
+
</script>
|
|
271
|
+
</body>
|
|
272
|
+
</html>`;
|
|
273
|
+
}
|
|
274
|
+
export function createUploadPageService(deps, options) {
|
|
275
|
+
const now = options?.now ?? (() => new Date());
|
|
276
|
+
const ids = options?.ids ?? (() => crypto.randomUUID());
|
|
277
|
+
const randomToken = options?.randomToken ?? (() => randomBytes(32).toString('base64url'));
|
|
278
|
+
const pageTtlMs = options?.pageTtlMs ?? UPLOAD_PAGE_TTL_MS;
|
|
279
|
+
const maxOpenPages = options?.maxOpenPages ?? SERVER_MAX_OPEN_UPLOAD_PAGES;
|
|
280
|
+
if (!Number.isSafeInteger(pageTtlMs) || pageTtlMs < 1)
|
|
281
|
+
throw new Error('invalid page TTL');
|
|
282
|
+
if (!Number.isSafeInteger(maxOpenPages) || maxOpenPages < 1)
|
|
283
|
+
throw new Error('invalid page quota');
|
|
284
|
+
if (deps.controlOrigin.length === 0 || deps.pageBaseUrl.length === 0) {
|
|
285
|
+
throw new Error('invalid page host configuration');
|
|
286
|
+
}
|
|
287
|
+
if (!Number.isSafeInteger(deps.budget.filesMax) || deps.budget.filesMax < 1 ||
|
|
288
|
+
!Number.isSafeInteger(deps.budget.totalBytesMax) || deps.budget.totalBytesMax < 1) {
|
|
289
|
+
throw new Error('invalid page staged budget');
|
|
290
|
+
}
|
|
291
|
+
const pathMaxBytes = deps.profile.pathMaxBytes ?? 1024;
|
|
292
|
+
const emit = (event) => {
|
|
293
|
+
if (deps.metrics !== undefined)
|
|
294
|
+
deps.metrics.emit(event);
|
|
295
|
+
};
|
|
296
|
+
// The browser channel shares the session ledger with the agent channel, so
|
|
297
|
+
// the 8-open-session quota and the scope aggregate cover both together.
|
|
298
|
+
const uploads = createUploadService({ sessions: deps.sessions, staging: deps.staging, signer: deps.signer }, { maxUploadBytes: deps.profile.maxFileBytes,
|
|
299
|
+
maxSessionsPerPrincipal: SERVER_MAX_UPLOAD_SESSIONS_PER_PRINCIPAL,
|
|
300
|
+
...(deps.stagingQuotaBytesPerScope === undefined ? {} : {
|
|
301
|
+
stagingQuotaBytesPerScope: deps.stagingQuotaBytesPerScope
|
|
302
|
+
}),
|
|
303
|
+
channel: 'browser', metrics: deps.metrics, now, ids });
|
|
304
|
+
// Per-owner mint serialization (the store check and insert stay paired).
|
|
305
|
+
const mintTails = new Map();
|
|
306
|
+
const serializedMint = (ownerId, action) => {
|
|
307
|
+
const previous = mintTails.get(ownerId) ?? Promise.resolve();
|
|
308
|
+
let release;
|
|
309
|
+
const gate = new Promise((resolve) => { release = resolve; });
|
|
310
|
+
mintTails.set(ownerId, previous.then(() => gate));
|
|
311
|
+
return previous.then(action).finally(release);
|
|
312
|
+
};
|
|
313
|
+
const tokenHashOf = (token) => createHash('sha256').update(token, 'utf8').digest('hex');
|
|
314
|
+
const timedEqualHex = (left, right) => {
|
|
315
|
+
const a = Buffer.from(left, 'hex');
|
|
316
|
+
const b = Buffer.from(right, 'hex');
|
|
317
|
+
return a.length === b.length && timingSafeEqual(a, b);
|
|
318
|
+
};
|
|
319
|
+
const liveRow = async (pageSessionId) => {
|
|
320
|
+
const row = await deps.pages.get(pageSessionId);
|
|
321
|
+
if (row === undefined || (row.state !== 'open' && row.state !== 'exchanged')) {
|
|
322
|
+
throw new Error(`unknown upload page: ${pageSessionId}`);
|
|
323
|
+
}
|
|
324
|
+
if (new Date(row.expiresAt).getTime() <= now().getTime()) {
|
|
325
|
+
await deps.pages.markExpired(pageSessionId).catch(() => undefined);
|
|
326
|
+
throw new Error(`upload page expired: ${pageSessionId}`);
|
|
327
|
+
}
|
|
328
|
+
return row;
|
|
329
|
+
};
|
|
330
|
+
const checkPageRequest = async (input) => {
|
|
331
|
+
// Same simple-request CSRF defence as `apps/artifact-content` `/_reader/activate`.
|
|
332
|
+
if (input.origin !== deps.controlOrigin || input.customHeader !== true) {
|
|
333
|
+
throw new Error('forbidden page request: origin or header mismatch');
|
|
334
|
+
}
|
|
335
|
+
const value = parseUploadPageCookie(input.cookie);
|
|
336
|
+
if (value === undefined)
|
|
337
|
+
throw new Error('forbidden page request: missing page cookie');
|
|
338
|
+
const row = await liveRow(deps.cookieSigner.verify(value));
|
|
339
|
+
if (row.artifactId !== input.artifactId) {
|
|
340
|
+
throw new Error('forbidden page request: page bound to another artifact');
|
|
341
|
+
}
|
|
342
|
+
return row;
|
|
343
|
+
};
|
|
344
|
+
const checkPath = (path) => {
|
|
345
|
+
if (typeof path !== 'string' || path.length === 0 || Buffer.byteLength(path, 'utf8') > pathMaxBytes) {
|
|
346
|
+
throw new Error('invalid page asset path');
|
|
347
|
+
}
|
|
348
|
+
};
|
|
349
|
+
return {
|
|
350
|
+
async mint(input) {
|
|
351
|
+
if (input.artifactId.length === 0 || input.storageScopeId.length === 0 || input.ownerId.length === 0) {
|
|
352
|
+
throw new Error('invalid page mint: empty binding');
|
|
353
|
+
}
|
|
354
|
+
return serializedMint(input.ownerId, async () => {
|
|
355
|
+
const active = await deps.pages.countActiveByOwner(input.ownerId);
|
|
356
|
+
if (active >= maxOpenPages) {
|
|
357
|
+
emit({ name: 'upload_quota_refusals', labels: { reason: 'open_page_quota' } });
|
|
358
|
+
throw new Error(`open upload page quota exceeded for principal (max ${maxOpenPages})`);
|
|
359
|
+
}
|
|
360
|
+
const maxFiles = Math.min(input.maxFiles ?? deps.profile.maxFiles, deps.profile.maxFiles);
|
|
361
|
+
if (!Number.isSafeInteger(maxFiles) || maxFiles < 1)
|
|
362
|
+
throw new Error('invalid page file bound');
|
|
363
|
+
const pageSessionId = ids();
|
|
364
|
+
const token = randomToken();
|
|
365
|
+
const at = now();
|
|
366
|
+
const row = { pageSessionId, artifactId: input.artifactId,
|
|
367
|
+
storageScopeId: input.storageScopeId, ownerId: input.ownerId, tokenHash: tokenHashOf(token),
|
|
368
|
+
state: 'open', maxFiles, createdAt: at.toISOString(),
|
|
369
|
+
expiresAt: new Date(at.getTime() + pageTtlMs).toISOString() };
|
|
370
|
+
await deps.pages.create(row);
|
|
371
|
+
emit({ name: 'upload_pages_minted' });
|
|
372
|
+
return { pageSessionId, token,
|
|
373
|
+
uploadPageUrl: `${deps.pageBaseUrl.replace(/\/$/, '')}/artifacts/upload/${pageSessionId}#t=${token}`,
|
|
374
|
+
expiresAt: row.expiresAt, maxFiles, maxFileBytes: deps.profile.maxFileBytes,
|
|
375
|
+
maxTotalBytes: deps.profile.maxTotalBytes, allowedMimeTypes: [...deps.profile.mimeTypes] };
|
|
376
|
+
});
|
|
377
|
+
},
|
|
378
|
+
async exchange(input) {
|
|
379
|
+
if (input.origin !== deps.controlOrigin)
|
|
380
|
+
throw new Error('forbidden page exchange: origin mismatch');
|
|
381
|
+
const row = await liveRow(input.pageSessionId);
|
|
382
|
+
if (row.state !== 'open')
|
|
383
|
+
throw new Error(`upload page not open (${row.state}): ${input.pageSessionId}`);
|
|
384
|
+
if (!timedEqualHex(tokenHashOf(input.token), row.tokenHash)) {
|
|
385
|
+
throw new Error('forbidden page exchange: token mismatch');
|
|
386
|
+
}
|
|
387
|
+
await deps.pages.markExchanged(input.pageSessionId, now().toISOString());
|
|
388
|
+
emit({ name: 'upload_pages_exchanged' });
|
|
389
|
+
const remainingMs = new Date(row.expiresAt).getTime() - now().getTime();
|
|
390
|
+
const maxAgeSeconds = Math.max(1, Math.floor(remainingMs / 1000));
|
|
391
|
+
return { cookie: buildUploadPageCookie(deps.cookieSigner.sign(input.pageSessionId), maxAgeSeconds),
|
|
392
|
+
maxAgeSeconds };
|
|
393
|
+
},
|
|
394
|
+
async createFile(input) {
|
|
395
|
+
const row = await checkPageRequest(input);
|
|
396
|
+
checkPath(input.path);
|
|
397
|
+
if (!deps.profile.mimeTypes.includes(input.mimeType))
|
|
398
|
+
throw new Error('unsupported page MIME type');
|
|
399
|
+
if (!Number.isSafeInteger(input.size) || input.size < 1 || input.size > deps.profile.maxFileBytes) {
|
|
400
|
+
throw new Error('invalid page file size');
|
|
401
|
+
}
|
|
402
|
+
return uploads.create({ artifactId: row.artifactId, storageScopeId: row.storageScopeId,
|
|
403
|
+
ownerId: row.ownerId, mimeType: input.mimeType, maxSize: input.size,
|
|
404
|
+
pageSessionId: row.pageSessionId, pageFileLimit: row.maxFiles });
|
|
405
|
+
},
|
|
406
|
+
async commitFile(input) {
|
|
407
|
+
const row = await checkPageRequest(input);
|
|
408
|
+
checkPath(input.path);
|
|
409
|
+
if (typeof input.idempotencyKey !== 'string' || input.idempotencyKey.trim().length === 0 ||
|
|
410
|
+
input.idempotencyKey.length > 256) {
|
|
411
|
+
throw new Error('invalid page idempotency key');
|
|
412
|
+
}
|
|
413
|
+
const commit = { uploadId: input.uploadId, artifactId: row.artifactId,
|
|
414
|
+
storageScopeId: row.storageScopeId, ownerId: row.ownerId, path: input.path,
|
|
415
|
+
mimeType: input.mimeType, digest: input.digest, size: input.size };
|
|
416
|
+
const paramsHash = createHash('sha256').update(JSON.stringify(commit), 'utf8').digest('hex');
|
|
417
|
+
const work = () => commitStagedUpload(uploads, { sessions: deps.sessions, staging: deps.staging, blobs: deps.blobs, refs: deps.refs,
|
|
418
|
+
budget: deps.budget, metrics: deps.metrics }, commit, 'browser');
|
|
419
|
+
if (deps.idempotency === undefined)
|
|
420
|
+
return work();
|
|
421
|
+
const storeKey = JSON.stringify(['commit_upload', row.ownerId, input.idempotencyKey]);
|
|
422
|
+
try {
|
|
423
|
+
const { result } = await deps.idempotency.execute(storeKey, paramsHash, work);
|
|
424
|
+
return result;
|
|
425
|
+
}
|
|
426
|
+
catch (cause) {
|
|
427
|
+
if (cause instanceof Error && /idempotency conflict/.test(cause.message))
|
|
428
|
+
throw cause;
|
|
429
|
+
throw cause;
|
|
430
|
+
}
|
|
431
|
+
},
|
|
432
|
+
async listStaged(input) {
|
|
433
|
+
const row = await checkPageRequest(input);
|
|
434
|
+
return (await deps.sessions.listStagedFiles(row.artifactId))
|
|
435
|
+
.filter((record) => record.pageSessionId === row.pageSessionId);
|
|
436
|
+
},
|
|
437
|
+
};
|
|
438
|
+
}
|
package/dist/server/uploads.d.ts
CHANGED
|
@@ -1,5 +1,16 @@
|
|
|
1
|
+
import type { ArtifactsMetrics } from './metrics.js';
|
|
2
|
+
import type { RefcountStore } from './gc.js';
|
|
3
|
+
import type { PublicationBlobStore } from './publication.js';
|
|
1
4
|
export declare const UPLOAD_URL_TTL_SECONDS = 600;
|
|
2
5
|
export declare const UPLOAD_SESSION_TTL_MS: number;
|
|
6
|
+
/**
|
|
7
|
+
* Files parity LOT 2 §D — staged-file TTL (host option, ceiling 7 days),
|
|
8
|
+
* orphan staging-key grace, and the per-run orphan bound.
|
|
9
|
+
*/
|
|
10
|
+
export declare const STAGED_FILE_TTL_MS: number;
|
|
11
|
+
export declare const STAGED_FILE_TTL_MAX_MS: number;
|
|
12
|
+
export declare const ORPHAN_STAGING_GRACE_MS: number;
|
|
13
|
+
export declare const ORPHAN_SWEEP_MAX_KEYS = 500;
|
|
3
14
|
export type UploadSessionState = 'open' | 'committed' | 'discarded' | 'expired';
|
|
4
15
|
export interface UploadSession {
|
|
5
16
|
readonly uploadId: string;
|
|
@@ -11,6 +22,8 @@ export interface UploadSession {
|
|
|
11
22
|
readonly state: UploadSessionState;
|
|
12
23
|
readonly expiresAt: string;
|
|
13
24
|
readonly createdAt: string;
|
|
25
|
+
/** Browser page that minted this session (agent-channel rows stay null). */
|
|
26
|
+
readonly pageSessionId?: string;
|
|
14
27
|
}
|
|
15
28
|
export interface StagedFileRecord {
|
|
16
29
|
readonly uploadId: string;
|
|
@@ -20,6 +33,8 @@ export interface StagedFileRecord {
|
|
|
20
33
|
readonly digest: string;
|
|
21
34
|
readonly size: number;
|
|
22
35
|
readonly createdAt: string;
|
|
36
|
+
/** Browser page the file was committed through (agent-channel rows stay null). */
|
|
37
|
+
readonly pageSessionId?: string;
|
|
23
38
|
}
|
|
24
39
|
/** Durable session ledger (Postgres in the host via migration 0007; memory double in tests). */
|
|
25
40
|
export interface UploadSessionStore {
|
|
@@ -34,6 +49,22 @@ export interface UploadSessionStore {
|
|
|
34
49
|
recordStagedFile(record: StagedFileRecord): Promise<void>;
|
|
35
50
|
getStagedFile(uploadId: string): Promise<StagedFileRecord | undefined>;
|
|
36
51
|
listStagedFiles(artifactId: string): Promise<StagedFileRecord[]>;
|
|
52
|
+
/** LOT 2 §D.2: reserved bytes of open sessions in one scope (quota check). */
|
|
53
|
+
sumOpenMaxSize(storageScopeId: string): Promise<number>;
|
|
54
|
+
/** LOT 2 §D.2: staged bytes in one scope (quota check). */
|
|
55
|
+
sumStagedBytesByScope(storageScopeId: string): Promise<number>;
|
|
56
|
+
/** LOT 2 §A.3: sessions minted through one browser page (file-count bound). */
|
|
57
|
+
listPageSessions(pageSessionId: string): Promise<UploadSession[]>;
|
|
58
|
+
/**
|
|
59
|
+
* LOT 2 §D.2: serialize the quota check and insert per scope (race-proof
|
|
60
|
+
* backstop). The PG store runs `action` on a transaction holding the scope
|
|
61
|
+
* advisory lock; the memory double runs it under a per-scope mutex. The
|
|
62
|
+
* service performs every quota read and the insert through `locked`.
|
|
63
|
+
*/
|
|
64
|
+
withScopeLock<T>(storageScopeId: string, action: (locked: UploadSessionStore) => Promise<T>): Promise<T>;
|
|
65
|
+
/** LOT 2 §D.1: staged rows older than the TTL (sweeper pass 2 input). */
|
|
66
|
+
listExpiredStaged(now: Date, ttlMs: number): Promise<StagedFileRecord[]>;
|
|
67
|
+
deleteStagedFile(uploadId: string): Promise<void>;
|
|
37
68
|
}
|
|
38
69
|
/** Byte store under the staging prefix (S3 in the host; memory double in tests). */
|
|
39
70
|
export interface StagingStore {
|
|
@@ -41,6 +72,11 @@ export interface StagingStore {
|
|
|
41
72
|
get(key: string): Promise<Uint8Array | undefined>;
|
|
42
73
|
delete(key: string): Promise<void>;
|
|
43
74
|
listKeys(prefix: string): Promise<string[]>;
|
|
75
|
+
/** LOT 2 §D.1 orphan pass: keys with last write time (optional; absent ⇒ pass skipped). */
|
|
76
|
+
listEntries?(prefix: string): Promise<{
|
|
77
|
+
key: string;
|
|
78
|
+
lastModified: string;
|
|
79
|
+
}[]>;
|
|
44
80
|
}
|
|
45
81
|
/**
|
|
46
82
|
* Presigner port. The signature binds content-type, the EXACT content-length
|
|
@@ -66,6 +102,8 @@ export interface UploadSignerPort {
|
|
|
66
102
|
export declare const STAGING_KEY_PATTERN: RegExp;
|
|
67
103
|
/** Staging key of one upload session. */
|
|
68
104
|
export declare function stagingKey(storageScopeId: string, uploadId: string): string;
|
|
105
|
+
/** Staging prefix of one scope (LOT 2 §D.1 orphan pass enumerates it). */
|
|
106
|
+
export declare function stagingPrefix(storageScopeId: string): string;
|
|
69
107
|
/**
|
|
70
108
|
* Value of the `x-amz-checksum-sha256` header for a canonical `sha256:<hex>`
|
|
71
109
|
* digest: S3 expects the base64 of the raw digest bytes (no `sha256:` prefix).
|
|
@@ -76,7 +114,7 @@ export declare function assertStagingKey(key: string): void;
|
|
|
76
114
|
/** Reject empty or escaping staging prefixes before enumeration. */
|
|
77
115
|
export declare function assertStagingPrefix(prefix: string): void;
|
|
78
116
|
/** In-memory StagingStore double for unit tests. */
|
|
79
|
-
export declare function createMemoryStaging(): StagingStore;
|
|
117
|
+
export declare function createMemoryStaging(now?: () => Date): StagingStore;
|
|
80
118
|
/** In-memory UploadSessionStore double for unit tests. */
|
|
81
119
|
export declare function createMemoryUploadSessionStore(now?: () => Date): UploadSessionStore;
|
|
82
120
|
/**
|
|
@@ -109,7 +147,15 @@ export interface CreateUploadInput {
|
|
|
109
147
|
mimeType: string;
|
|
110
148
|
/** Declared size; clamped to the host budget. Bound as the exact signed Content-Length. */
|
|
111
149
|
maxSize?: number;
|
|
150
|
+
/** Browser page that mints this session (agent-channel rows stay null). */
|
|
151
|
+
pageSessionId?: string;
|
|
152
|
+
/** Page file bound enforced with the quota check; required when pageSessionId is set. */
|
|
153
|
+
pageFileLimit?: number;
|
|
112
154
|
}
|
|
155
|
+
/** Digest-addressed CAS blob key of one scope and canonical `sha256:<hex>` digest. */
|
|
156
|
+
export declare function casBlobKey(storageScopeId: string, digest: string): string;
|
|
157
|
+
/** LOT 2 §D.1: true when a staged file is older than the staged-file TTL. */
|
|
158
|
+
export declare function stagedFileExpired(record: Pick<StagedFileRecord, 'createdAt'>, nowMs: number, ttlMs: number): boolean;
|
|
113
159
|
export interface CreateUploadResult {
|
|
114
160
|
uploadId: string;
|
|
115
161
|
uploadUrl: string;
|
|
@@ -141,6 +187,13 @@ export interface UploadServiceOptions {
|
|
|
141
187
|
/** Host ceiling for one upload (min of profile releaseFileBytesMax and the server maximum). */
|
|
142
188
|
maxUploadBytes: number;
|
|
143
189
|
maxSessionsPerPrincipal: number;
|
|
190
|
+
/** LOT 2 §D.2: per-scope staging aggregate (reserved open + staged bytes). Absent ⇒ no aggregate bound. */
|
|
191
|
+
stagingQuotaBytesPerScope?: number;
|
|
192
|
+
/** LOT 2 §D.1: staged-file TTL (host option, ceiling 7 days). Absent ⇒ 24 h. */
|
|
193
|
+
stagedFileTtlMs?: number;
|
|
194
|
+
/** Metric channel of sessions minted through this service (`agent` or `browser`). */
|
|
195
|
+
channel?: string;
|
|
196
|
+
metrics?: ArtifactsMetrics;
|
|
144
197
|
now?: () => Date;
|
|
145
198
|
ids?: () => string;
|
|
146
199
|
}
|
|
@@ -166,3 +219,24 @@ export declare function createUploadService(deps: {
|
|
|
166
219
|
staging: StagingStore;
|
|
167
220
|
signer: UploadSignerPort;
|
|
168
221
|
}, options: UploadServiceOptions): UploadService;
|
|
222
|
+
/**
|
|
223
|
+
* Files parity LOT 2 — shared commit core for both channels (agent MCP and
|
|
224
|
+
* browser page). Verification and pin logic live here once: the MCP handler
|
|
225
|
+
* and the page service both call it, so neither duplicates the other.
|
|
226
|
+
*/
|
|
227
|
+
export interface CommitStagedUploadDeps {
|
|
228
|
+
sessions: UploadSessionStore;
|
|
229
|
+
staging: StagingStore;
|
|
230
|
+
blobs: PublicationBlobStore;
|
|
231
|
+
refs: RefcountStore;
|
|
232
|
+
/** Per-artifact staged caps (`releaseFilesMax`/`releaseTotalBytesMax`). */
|
|
233
|
+
budget: {
|
|
234
|
+
filesMax: number;
|
|
235
|
+
totalBytesMax: number;
|
|
236
|
+
};
|
|
237
|
+
metrics?: ArtifactsMetrics;
|
|
238
|
+
}
|
|
239
|
+
export interface CommitStagedUploadInput extends CommitUploadInput {
|
|
240
|
+
pageSessionId?: string;
|
|
241
|
+
}
|
|
242
|
+
export declare function commitStagedUpload(service: UploadService, deps: CommitStagedUploadDeps, input: CommitStagedUploadInput, channel?: string): Promise<StagedFileRecord>;
|