@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.
Files changed (74) hide show
  1. package/CHANGELOG.md +93 -0
  2. package/README.md +45 -10
  3. package/dist/adapters/local-blob.d.ts +3 -0
  4. package/dist/adapters/local-blob.js +93 -0
  5. package/dist/adapters/postgres-management.js +3 -2
  6. package/dist/adapters/postgres-reader-consent.d.ts +11 -0
  7. package/dist/adapters/postgres-reader-consent.js +109 -0
  8. package/dist/adapters/postgres-uploads.d.ts +14 -0
  9. package/dist/adapters/postgres-uploads.js +174 -0
  10. package/dist/adapters/postgres.js +4 -3
  11. package/dist/adapters/s3-uploads.d.ts +33 -0
  12. package/dist/adapters/s3-uploads.js +105 -0
  13. package/dist/adapters/s3.js +23 -0
  14. package/dist/adapters/sqlite-activation.d.ts +20 -0
  15. package/dist/adapters/sqlite-activation.js +205 -0
  16. package/dist/adapters/sqlite-commit.d.ts +15 -0
  17. package/dist/adapters/sqlite-commit.js +89 -0
  18. package/dist/adapters/sqlite-management.d.ts +10 -0
  19. package/dist/adapters/sqlite-management.js +60 -0
  20. package/dist/adapters/sqlite-sql.d.ts +32 -0
  21. package/dist/adapters/sqlite-sql.js +36 -0
  22. package/dist/adapters/sqlite-store.d.ts +12 -0
  23. package/dist/adapters/sqlite-store.js +410 -0
  24. package/dist/adapters/sqlite.d.ts +33 -0
  25. package/dist/adapters/sqlite.js +95 -0
  26. package/dist/content/handler.d.ts +5 -0
  27. package/dist/content/handler.js +80 -9
  28. package/dist/content/headers.js +12 -0
  29. package/dist/http.d.ts +32 -2
  30. package/dist/http.js +615 -13
  31. package/dist/mcp-core.d.ts +3 -3
  32. package/dist/mcp-core.js +90 -4
  33. package/dist/profile/contracts.d.ts +1 -1
  34. package/dist/profile/contracts.js +7 -0
  35. package/dist/profile/index.js +43 -2
  36. package/dist/profile/radar.js +7 -0
  37. package/dist/profile/schemas.js +119 -0
  38. package/dist/profile/validation.d.ts +11 -0
  39. package/dist/profile/validation.js +98 -6
  40. package/dist/server/access.d.ts +2 -0
  41. package/dist/server/command-identity.d.ts +1 -1
  42. package/dist/server/command-identity.js +6 -3
  43. package/dist/server/consent.d.ts +65 -0
  44. package/dist/server/consent.js +42 -0
  45. package/dist/server/gc.d.ts +42 -0
  46. package/dist/server/gc.js +98 -0
  47. package/dist/server/management.d.ts +3 -1
  48. package/dist/server/management.js +48 -7
  49. package/dist/server/metrics.d.ts +21 -0
  50. package/dist/server/metrics.js +6 -0
  51. package/dist/server/mime.d.ts +26 -2
  52. package/dist/server/mime.js +124 -2
  53. package/dist/server/ports.d.ts +29 -0
  54. package/dist/server/ports.js +11 -0
  55. package/dist/server/publication-limits.d.ts +20 -0
  56. package/dist/server/publication-limits.js +27 -1
  57. package/dist/server/publication.d.ts +14 -0
  58. package/dist/server/publication.js +10 -2
  59. package/dist/server/reader-store.d.ts +58 -0
  60. package/dist/server/reader-store.js +109 -0
  61. package/dist/server/source-read.d.ts +12 -9
  62. package/dist/server/source-read.js +17 -5
  63. package/dist/server/templates.js +50 -2
  64. package/dist/server/upload-page.d.ts +157 -0
  65. package/dist/server/upload-page.js +438 -0
  66. package/dist/server/uploads.d.ts +229 -19
  67. package/dist/server/uploads.js +387 -80
  68. package/migrations/0007_uploads.sql +43 -0
  69. package/migrations/0008_reader_consent.sql +48 -0
  70. package/migrations/0009_upload_pages.sql +25 -0
  71. package/package.json +34 -1
  72. package/sql/reader-consent.sql +47 -0
  73. package/sql/sqlite/0001_artifacts.sql +156 -0
  74. package/sql/sqlite/0002_activation.sql +73 -0
@@ -0,0 +1,157 @@
1
+ import type { StagedFileRecord, StagingStore, UploadSessionStore, UploadSignerPort } from './uploads.js';
2
+ import type { PublicationBlobStore } from './publication.js';
3
+ import type { RefcountStore } from './gc.js';
4
+ import type { IdempotencyStore } from './idempotency.js';
5
+ import type { ArtifactsMetrics } from './metrics.js';
6
+ export declare const UPLOAD_PAGE_TTL_MS: number;
7
+ export declare const UPLOAD_PAGE_COOKIE = "__Host-artifacts_upload";
8
+ export declare const SERVER_MAX_OPEN_UPLOAD_PAGES = 4;
9
+ export type UploadPageState = 'open' | 'exchanged' | 'closed' | 'expired';
10
+ export interface UploadPageRow {
11
+ readonly pageSessionId: string;
12
+ readonly artifactId: string;
13
+ readonly storageScopeId: string;
14
+ readonly ownerId: string;
15
+ readonly tokenHash: string;
16
+ readonly state: UploadPageState;
17
+ readonly maxFiles: number;
18
+ readonly createdAt: string;
19
+ readonly expiresAt: string;
20
+ readonly exchangedAt?: string;
21
+ }
22
+ export interface UploadPageStore {
23
+ create(row: UploadPageRow): Promise<void>;
24
+ get(pageSessionId: string): Promise<UploadPageRow | undefined>;
25
+ countActiveByOwner(ownerId: string): Promise<number>;
26
+ listExpiredPages(now: Date): Promise<UploadPageRow[]>;
27
+ markExchanged(pageSessionId: string, at: string): Promise<void>;
28
+ markExpired(pageSessionId: string): Promise<void>;
29
+ }
30
+ export declare function createMemoryUploadPageStore(): UploadPageStore;
31
+ export interface UploadPageCookieSigner {
32
+ sign(pageSessionId: string): string;
33
+ verify(value: string): string;
34
+ }
35
+ /**
36
+ * HMAC cookie signer for one upload page (mirrors `content/grants.ts`).
37
+ * The cookie carries `{sid, exp}`; the page row carries state and expiry, so
38
+ * a stolen cookie is bounded by the row TTL and the owner binding.
39
+ */
40
+ export declare function createHmacUploadPageCookieSigner(options: {
41
+ secret: string | Uint8Array;
42
+ clock?: () => number;
43
+ ttlSeconds?: number;
44
+ }): UploadPageCookieSigner;
45
+ /**
46
+ * Host-only page cookie value (review finding 1: the `__Host-` prefix
47
+ * requires `Path=/`, exactly like the shipped grant cookie).
48
+ */
49
+ export declare function buildUploadPageCookie(value: string, maxAgeSeconds: number): string;
50
+ export declare function parseUploadPageCookie(header: string | undefined): string | undefined;
51
+ /** Page CSP (§A.4): no external assets; S3 origins are host-supplied. */
52
+ export declare function uploadPageCsp(s3Origins: readonly string[]): string;
53
+ /**
54
+ * Self-contained static upload page (no external assets). Bytes travel
55
+ * browser → S3 via raw PUT (FormData is banned: multipart wrapping changes
56
+ * length and type); one session per file with `size = File.size`; at most 4
57
+ * PUTs in flight; commit each file before opening further sessions.
58
+ */
59
+ export declare function renderUploadPage(options: {
60
+ s3Origins: readonly string[];
61
+ }): string;
62
+ export interface UploadPageProfileCaps {
63
+ readonly maxFiles: number;
64
+ readonly maxFileBytes: number;
65
+ readonly maxTotalBytes: number;
66
+ readonly mimeTypes: readonly string[];
67
+ /** Manifest path byte budget (profile `pathMaxBytes`); absent ⇒ 1024. */
68
+ readonly pathMaxBytes?: number;
69
+ }
70
+ export interface UploadPageServiceDeps {
71
+ readonly pages: UploadPageStore;
72
+ readonly sessions: UploadSessionStore;
73
+ readonly staging: StagingStore;
74
+ readonly signer: UploadSignerPort;
75
+ readonly blobs: PublicationBlobStore;
76
+ readonly refs: RefcountStore;
77
+ readonly idempotency?: IdempotencyStore;
78
+ readonly cookieSigner: UploadPageCookieSigner;
79
+ readonly controlOrigin: string;
80
+ readonly pageBaseUrl: string;
81
+ readonly s3Origins: readonly string[];
82
+ readonly profile: UploadPageProfileCaps;
83
+ /** Per-artifact staged caps, enforced at commit for the browser channel. */
84
+ readonly budget: {
85
+ filesMax: number;
86
+ totalBytesMax: number;
87
+ };
88
+ /** Per-scope staging aggregate shared with the agent channel. */
89
+ readonly stagingQuotaBytesPerScope?: number;
90
+ readonly metrics?: ArtifactsMetrics;
91
+ }
92
+ export interface MintUploadPageInput {
93
+ readonly artifactId: string;
94
+ readonly storageScopeId: string;
95
+ readonly ownerId: string;
96
+ readonly maxFiles?: number;
97
+ }
98
+ export interface UploadPageMint {
99
+ readonly pageSessionId: string;
100
+ readonly token: string;
101
+ readonly uploadPageUrl: string;
102
+ readonly expiresAt: string;
103
+ readonly maxFiles: number;
104
+ readonly maxFileBytes: number;
105
+ readonly maxTotalBytes: number;
106
+ readonly allowedMimeTypes: readonly string[];
107
+ }
108
+ export interface UploadPageExchange {
109
+ readonly cookie: string;
110
+ readonly maxAgeSeconds: number;
111
+ }
112
+ export interface PageFileInput {
113
+ readonly cookie: string;
114
+ readonly origin: string;
115
+ readonly customHeader: boolean;
116
+ readonly artifactId: string;
117
+ readonly path: string;
118
+ readonly mimeType: string;
119
+ readonly size: number;
120
+ }
121
+ export interface PageCommitInput extends PageFileInput {
122
+ readonly uploadId: string;
123
+ readonly digest: string;
124
+ readonly idempotencyKey: string;
125
+ }
126
+ export interface UploadPageService {
127
+ mint(input: MintUploadPageInput): Promise<UploadPageMint>;
128
+ exchange(input: {
129
+ pageSessionId: string;
130
+ token: string;
131
+ origin: string;
132
+ }): Promise<UploadPageExchange>;
133
+ createFile(input: PageFileInput): Promise<{
134
+ uploadId: string;
135
+ uploadUrl: string;
136
+ method: 'PUT';
137
+ expiresAt: string;
138
+ maxSize: number;
139
+ requiredHeaders: Record<string, string>;
140
+ checksumHeader: 'x-amz-checksum-sha256';
141
+ stagingKey: string;
142
+ }>;
143
+ commitFile(input: PageCommitInput): Promise<StagedFileRecord>;
144
+ listStaged(input: {
145
+ cookie: string;
146
+ origin: string;
147
+ customHeader: boolean;
148
+ artifactId: string;
149
+ }): Promise<StagedFileRecord[]>;
150
+ }
151
+ export declare function createUploadPageService(deps: UploadPageServiceDeps, options?: {
152
+ now?: () => Date;
153
+ ids?: () => string;
154
+ randomToken?: () => string;
155
+ pageTtlMs?: number;
156
+ maxOpenPages?: number;
157
+ }): UploadPageService;
@@ -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, '&quot;')}">
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
+ }