@sentropic/artifacts 0.2.13 → 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 (49) hide show
  1. package/CHANGELOG.md +26 -0
  2. package/dist/adapters/local-blob.d.ts +3 -0
  3. package/dist/adapters/local-blob.js +93 -0
  4. package/dist/adapters/postgres-uploads.d.ts +14 -0
  5. package/dist/adapters/postgres-uploads.js +174 -0
  6. package/dist/adapters/s3.js +23 -0
  7. package/dist/adapters/sqlite-activation.d.ts +20 -0
  8. package/dist/adapters/sqlite-activation.js +205 -0
  9. package/dist/adapters/sqlite-commit.d.ts +15 -0
  10. package/dist/adapters/sqlite-commit.js +89 -0
  11. package/dist/adapters/sqlite-management.d.ts +10 -0
  12. package/dist/adapters/sqlite-management.js +60 -0
  13. package/dist/adapters/sqlite-sql.d.ts +32 -0
  14. package/dist/adapters/sqlite-sql.js +36 -0
  15. package/dist/adapters/sqlite-store.d.ts +12 -0
  16. package/dist/adapters/sqlite-store.js +410 -0
  17. package/dist/adapters/sqlite.d.ts +33 -0
  18. package/dist/adapters/sqlite.js +95 -0
  19. package/dist/content/handler.d.ts +5 -0
  20. package/dist/content/handler.js +80 -9
  21. package/dist/http.d.ts +16 -0
  22. package/dist/http.js +371 -82
  23. package/dist/mcp-core.d.ts +3 -3
  24. package/dist/mcp-core.js +43 -4
  25. package/dist/profile/contracts.d.ts +1 -1
  26. package/dist/profile/contracts.js +4 -0
  27. package/dist/profile/index.js +12 -2
  28. package/dist/profile/schemas.js +60 -0
  29. package/dist/profile/validation.js +31 -4
  30. package/dist/server/command-identity.d.ts +1 -1
  31. package/dist/server/command-identity.js +4 -3
  32. package/dist/server/gc.d.ts +28 -3
  33. package/dist/server/gc.js +81 -5
  34. package/dist/server/metrics.d.ts +21 -0
  35. package/dist/server/metrics.js +6 -0
  36. package/dist/server/publication-limits.d.ts +8 -0
  37. package/dist/server/publication-limits.js +8 -0
  38. package/dist/server/publication.d.ts +5 -0
  39. package/dist/server/publication.js +6 -0
  40. package/dist/server/source-read.d.ts +12 -9
  41. package/dist/server/source-read.js +17 -5
  42. package/dist/server/upload-page.d.ts +157 -0
  43. package/dist/server/upload-page.js +438 -0
  44. package/dist/server/uploads.d.ts +75 -1
  45. package/dist/server/uploads.js +187 -27
  46. package/migrations/0009_upload_pages.sql +25 -0
  47. package/package.json +13 -1
  48. package/sql/sqlite/0001_artifacts.sql +156 -0
  49. package/sql/sqlite/0002_activation.sql +73 -0
package/dist/http.js CHANGED
@@ -6,10 +6,11 @@ import { createArtifactCommand } from './server/command-identity.js';
6
6
  import { createGuardedEnsureService } from './server/service.js';
7
7
  import { assertArtifactReplayMigration } from './server/idempotency.js';
8
8
  import { combineSharingPolicy, maskEmailHint, resolveSharingPolicy } from './server/ports.js';
9
- import { createGuardedPublicationService, resolveBlobConcurrency, runBlobPool, verifyStagedBlobs } from './server/publication.js';
10
- import { SERVER_MAX_FILE_BYTES, SERVER_MAX_UPLOAD_SESSIONS_PER_PRINCIPAL } from './server/publication-limits.js';
9
+ import { createGuardedPublicationService } from './server/publication.js';
10
+ import { SERVER_MAX_FILE_BYTES, SERVER_MAX_SOURCE_FILES, SERVER_MAX_SOURCE_INLINE_BYTES, SERVER_MAX_SOURCE_TOTAL_BYTES, SERVER_MAX_UPLOAD_SESSIONS_PER_PRINCIPAL } from './server/publication-limits.js';
11
11
  import { releaseBudget } from './profile/validation.js';
12
- import { createUploadService, stagingKey } from './server/uploads.js';
12
+ import { commitStagedUpload, createUploadService, STAGED_FILE_TTL_MS, stagedFileExpired } from './server/uploads.js';
13
+ import { createHmacUploadPageCookieSigner, createMemoryUploadPageStore, createUploadPageService } from './server/upload-page.js';
13
14
  import { accessModeOf, evaluateGrant } from './server/access.js';
14
15
  import { assertConsentScopeId } from './server/consent.js';
15
16
  import { applyEdits } from './server/edits.js';
@@ -27,7 +28,7 @@ export { projectArtifactHttpOutcome } from './server/outcome-projection.js';
27
28
  /** Stable content-route error codes; private driver messages never leave the host. */
28
29
  export function errorBody(status) {
29
30
  return { error: { 400: 'invalid_request', 401: 'anonymous', 403: 'access_denied',
30
- 404: 'not_found', 409: 'conflict', 410: 'gone', 422: 'verification_failed',
31
+ 404: 'not_found', 409: 'conflict', 410: 'gone', 416: 'range_not_satisfiable', 422: 'verification_failed',
31
32
  500: 'internal_error', 503: 'capability_unavailable' }[status] ?? 'internal_error' };
32
33
  }
33
34
  /** Retained for consumers describing canonical textual publication inputs. */
@@ -44,6 +45,7 @@ export function assertArtifactsTransportProfile(value) {
44
45
  'artifacts_list_versions', 'artifacts_get_source', 'artifacts_revert', 'artifacts_set_access', 'artifacts_delete',
45
46
  'artifacts_lookup_people', 'artifacts_list_access',
46
47
  'artifacts_create_upload', 'artifacts_commit_upload', 'artifacts_publish_bundle',
48
+ 'artifacts_create_upload_page', 'artifacts_list_assets', 'artifacts_publish_bundle_v2',
47
49
  'artifacts_revoke_reader_consent'];
48
50
  if (value.selectedCapabilities.some((name) => !supported.includes(name))) {
49
51
  throw new Error('unsupported artifacts transport capability');
@@ -67,13 +69,42 @@ export function createHttpArtifactApp(deps) {
67
69
  throw new Error('artifact delete confirmation port required');
68
70
  }
69
71
  // Files parity LOT 1: upload ports are required as soon as one upload capability is selected.
70
- const uploadCapabilities = ['artifacts_create_upload', 'artifacts_commit_upload', 'artifacts_publish_bundle'];
72
+ // list_assets needs only the session ledger (released listing works without staging/signer).
73
+ const uploadCapabilities = ['artifacts_create_upload', 'artifacts_commit_upload', 'artifacts_publish_bundle',
74
+ 'artifacts_create_upload_page', 'artifacts_publish_bundle_v2'];
71
75
  const needsUploads = uploadCapabilities.some((name) => profile.selectedCapabilities.includes(name));
72
76
  if (needsUploads && !deps.uploads)
73
77
  throw new Error('artifact upload ports required');
74
78
  const budget = releaseBudget(profile);
75
79
  const uploadService = deps.uploads === undefined ? undefined : createUploadService({ sessions: deps.uploads.sessions, staging: deps.uploads.staging, signer: deps.uploads.signer }, { maxUploadBytes: Math.min(budget.fileBytesMax, SERVER_MAX_FILE_BYTES),
76
- maxSessionsPerPrincipal: SERVER_MAX_UPLOAD_SESSIONS_PER_PRINCIPAL });
80
+ maxSessionsPerPrincipal: SERVER_MAX_UPLOAD_SESSIONS_PER_PRINCIPAL,
81
+ ...(deps.uploads.stagedFileTtlMs === undefined ? {} : { stagedFileTtlMs: deps.uploads.stagedFileTtlMs }),
82
+ ...(deps.uploads.stagingQuotaBytesPerScope === undefined ? {}
83
+ : { stagingQuotaBytesPerScope: deps.uploads.stagingQuotaBytesPerScope }),
84
+ ...(deps.uploads.metrics === undefined ? {} : { metrics: deps.uploads.metrics }) });
85
+ // LOT 2 §A: the browser page shares the session ledger, the CAS blobs and
86
+ // the refs with the agent channel, so quotas cover both together.
87
+ if (profile.selectedCapabilities.includes('artifacts_create_upload_page') && deps.uploadPage === undefined) {
88
+ throw new Error('artifacts control plane needs upload page host wiring (uploadPage)');
89
+ }
90
+ const pageService = profile.selectedCapabilities.includes('artifacts_create_upload_page') &&
91
+ uploadService !== undefined ? createUploadPageService({
92
+ pages: deps.uploadPage?.pages ?? createMemoryUploadPageStore(),
93
+ sessions: deps.uploads.sessions, staging: deps.uploads.staging, signer: deps.uploads.signer,
94
+ blobs: deps.publication.blobs, refs: deps.publication.refs,
95
+ ...(deps.uploads.idempotency === undefined ? {} : { idempotency: deps.uploads.idempotency }),
96
+ cookieSigner: createHmacUploadPageCookieSigner({ secret: deps.uploadPage.cookieSecret }),
97
+ controlOrigin: deps.uploadPage.controlOrigin, pageBaseUrl: deps.uploadPage.pageBaseUrl,
98
+ s3Origins: deps.uploadPage.s3Origins,
99
+ profile: { maxFiles: budget.filesMax, maxFileBytes: budget.fileBytesMax,
100
+ maxTotalBytes: budget.totalBytesMax, mimeTypes: profile.rules.mimeTypes,
101
+ pathMaxBytes: profile.rules.pathMaxBytes },
102
+ budget: { filesMax: budget.filesMax, totalBytesMax: budget.totalBytesMax },
103
+ ...(deps.uploads.stagingQuotaBytesPerScope === undefined ? {}
104
+ : { stagingQuotaBytesPerScope: deps.uploads.stagingQuotaBytesPerScope }),
105
+ ...(deps.uploads.metrics === undefined ? {} : { metrics: deps.uploads.metrics }),
106
+ }) : undefined;
107
+ const stagedFileTtlMs = deps.uploads?.stagedFileTtlMs ?? STAGED_FILE_TTL_MS;
77
108
  const ensure = createGuardedEnsureService({ profile, coordinator: deps.coordinator,
78
109
  derivation: deps.derivation, host: {
79
110
  lockBinding: (client, binding) => deps.ensureHost.lockBinding(client, binding),
@@ -108,6 +139,144 @@ export function createHttpArtifactApp(deps) {
108
139
  }
109
140
  return acl;
110
141
  }
142
+ /**
143
+ * Files parity LOT 2 — resolve the files/assets union to bytes BEFORE any
144
+ * commit step. One missing, expired, digest-mismatched or unauthorized asset
145
+ * fails the whole publish and commits nothing. v1 only produces inline,
146
+ * upload and cas forms; v2 additionally resolves copy/carry and the
147
+ * keep-unmodified carry of the expected current release.
148
+ */
149
+ async function resolveBundleAssets(invocation, artifactId, entries, options) {
150
+ const fail = (path, reason) => {
151
+ throw new ArtifactOperationError('verification_failed', { publicDetails: { asset: { path, reason } } });
152
+ };
153
+ const checkBytes = (path, mimeType, bytes) => {
154
+ if (!profile.rules.mimeTypes.includes(mimeType))
155
+ fail(path, 'MIME type not allowed by profile');
156
+ validateFileBytes(mimeType, bytes);
157
+ };
158
+ const readCas = async (path, digest, size) => {
159
+ const bytes = await deps.publication.blobs.getBlob(blobKey(invocation.storageScopeId, digest)) ??
160
+ fail(path, 'blob missing');
161
+ if (bytes.length !== size ||
162
+ `sha256:${createHash('sha256').update(bytes).digest('hex')}` !== digest) {
163
+ fail(path, 'size/digest mismatch');
164
+ }
165
+ return bytes;
166
+ };
167
+ const files = [];
168
+ const origins = {};
169
+ const uploadPins = [];
170
+ for (const file of entries.files) {
171
+ const bytes = Uint8Array.from(file.bytes);
172
+ checkBytes(file.path, file.mimeType, bytes);
173
+ files.push({ path: file.path, mimeType: file.mimeType, bytes });
174
+ origins[file.path] = 'inline';
175
+ }
176
+ for (const asset of entries.assets) {
177
+ const path = asset.path;
178
+ if (Object.hasOwn(asset, 'uploadId')) {
179
+ const staged = await deps.uploads.sessions.getStagedFile(asset.uploadId) ??
180
+ fail(path, 'unknown upload');
181
+ if (staged.artifactId !== artifactId)
182
+ fail(path, 'unknown upload');
183
+ if (stagedFileExpired(staged, Date.now(), stagedFileTtlMs))
184
+ fail(path, 'staged file expired');
185
+ const bytes = await deps.publication.blobs.getBlob(blobKey(invocation.storageScopeId, staged.digest)) ??
186
+ fail(path, 'staged blob missing or digest mismatch');
187
+ if (bytes.length !== staged.size ||
188
+ `sha256:${createHash('sha256').update(bytes).digest('hex')}` !== staged.digest) {
189
+ fail(path, 'staged blob missing or digest mismatch');
190
+ }
191
+ checkBytes(path, staged.mimeType, bytes);
192
+ files.push({ path, mimeType: staged.mimeType, bytes });
193
+ origins[path] = `upload:${staged.uploadId}`;
194
+ uploadPins.push({ digest: staged.digest, uploadId: staged.uploadId });
195
+ }
196
+ else if (Object.hasOwn(asset, 'sourceArtifactId') || Object.hasOwn(asset, 'carryFromReleaseId')) {
197
+ if (!options.allowExtendedForms)
198
+ fail(path, 'extended asset form needs publish_bundle_v2');
199
+ const copy = await resolveCopiedAsset(invocation, artifactId, asset, fail);
200
+ // The copied/carried MIME comes from a manifest, not the caller: it
201
+ // must still be inside the target profile allowlist (v1 forms keep
202
+ // their LOT 1 magic-only check; only the staged TTL is new there).
203
+ if (!profile.rules.mimeTypes.includes(copy.mimeType))
204
+ fail(path, 'MIME type not allowed by profile');
205
+ checkBytes(path, copy.mimeType, copy.bytes);
206
+ files.push({ path, mimeType: copy.mimeType, bytes: copy.bytes });
207
+ origins[path] = copy.origin;
208
+ }
209
+ else {
210
+ const digest = asset.digest;
211
+ const size = asset.size;
212
+ const mimeType = asset.mimeType;
213
+ const bytes = await readCas(path, digest, size);
214
+ checkBytes(path, mimeType, bytes);
215
+ files.push({ path, mimeType, bytes });
216
+ origins[path] = 'cas';
217
+ }
218
+ }
219
+ if (options.keepUnmodifiedPaths && options.expectedCurrentReleaseId !== null) {
220
+ const base = await deps.publication.getRelease(options.expectedCurrentReleaseId) ??
221
+ fail('(base release)', 'unknown release');
222
+ if (base.artifactId !== artifactId)
223
+ fail('(base release)', 'unknown release');
224
+ const manifest = parseManifest(base.manifest);
225
+ for (const file of manifest.files ?? []) {
226
+ if (Object.hasOwn(origins, file.path))
227
+ continue;
228
+ const bytes = await readCas(file.path, file.digest, file.size);
229
+ checkBytes(file.path, file.mimeType, bytes);
230
+ files.push({ path: file.path, mimeType: file.mimeType, bytes });
231
+ origins[file.path] = `carry:${options.expectedCurrentReleaseId}`;
232
+ }
233
+ }
234
+ return { files, origins, uploadPins };
235
+ }
236
+ /** Copy/carry resolution for `artifacts_publish_bundle_v2` (same failure contract). */
237
+ async function resolveCopiedAsset(invocation, artifactId, asset, fail) {
238
+ const path = asset.path;
239
+ const readManifestFile = async (sourceArtifactId, sourceReleaseId, sourcePath) => {
240
+ const sourceAcl = await deps.acls.getArtifactAcl(sourceArtifactId) ??
241
+ fail(path, 'unknown source artifact');
242
+ if (sourceAcl.storageScopeId !== invocation.storageScopeId)
243
+ fail(path, 'cross-scope copy not supported');
244
+ const sourceState = await deps.lifecycle.stateOf(sourceArtifactId);
245
+ if (!deps.lifecycle.canRead({ artifactId: sourceArtifactId, state: sourceState }, sourceAcl, invocation.actorId, 'source', deps.isApprovedAccount, await sharingPolicyContext(invocation.storageScopeId))) {
246
+ throw new ArtifactOperationError('access_denied');
247
+ }
248
+ const release = (sourceReleaseId === undefined ? await deps.publication.getCurrent(sourceArtifactId)
249
+ : deps.publication.getRelease === undefined ? undefined
250
+ : await deps.publication.getRelease(sourceReleaseId)) ?? fail(path, 'unknown source release');
251
+ if (release.artifactId !== sourceArtifactId)
252
+ fail(path, 'unknown source release');
253
+ const manifest = parseManifest(release.manifest);
254
+ const wanted = sourcePath ?? path;
255
+ const entry = (manifest.files ?? []).find((file) => file.path === wanted) ??
256
+ fail(path, 'source path missing');
257
+ const bytes = await deps.publication.blobs.getBlob(blobKey(invocation.storageScopeId, entry.digest)) ??
258
+ fail(path, 'source blob missing or digest mismatch');
259
+ if (bytes.length !== entry.size ||
260
+ `sha256:${createHash('sha256').update(bytes).digest('hex')}` !== entry.digest) {
261
+ fail(path, 'source blob missing or digest mismatch');
262
+ }
263
+ return { mimeType: entry.mimeType, bytes };
264
+ };
265
+ if (Object.hasOwn(asset, 'sourceArtifactId')) {
266
+ const sourceArtifactId = asset.sourceArtifactId;
267
+ const { mimeType, bytes } = await readManifestFile(sourceArtifactId, asset.sourceReleaseId, asset.sourcePath);
268
+ const release = asset.sourceReleaseId ??
269
+ await deps.publication.getCurrent(sourceArtifactId).then((current) => current?.releaseId);
270
+ return { mimeType, bytes, origin: `copy:${sourceArtifactId}:${release ?? 'current'}` };
271
+ }
272
+ const carryFromReleaseId = asset.carryFromReleaseId;
273
+ const release = await deps.publication.getRelease(carryFromReleaseId) ??
274
+ fail(path, 'unknown release');
275
+ if (release.artifactId !== artifactId)
276
+ fail(path, 'unknown release');
277
+ const { mimeType, bytes } = await readManifestFile(artifactId, carryFromReleaseId, asset.sourcePath);
278
+ return { mimeType, bytes, origin: `carry:${carryFromReleaseId}` };
279
+ }
111
280
  /**
112
281
  * G1 management visibility for `set_access` (converged-r2 §2.3 order (2)):
113
282
  * readers pass as before; any other actor gets `not_found` unless it is an
@@ -334,7 +503,7 @@ export function createHttpArtifactApp(deps) {
334
503
  }
335
504
  const normalized = profile.validate(capability, args, request.idempotencyKey, { deferPrecondition: true });
336
505
  const command = ['artifacts_ensure', 'artifacts_publish', 'artifacts_set_access', 'artifacts_delete', 'artifacts_revert',
337
- 'artifacts_commit_upload', 'artifacts_publish_bundle'].includes(capability)
506
+ 'artifacts_commit_upload', 'artifacts_publish_bundle', 'artifacts_publish_bundle_v2'].includes(capability)
338
507
  ? createArtifactCommand(profile, capability, args, invocation, deps.derivation, request.idempotencyKey, { deferPrecondition: true }) : undefined;
339
508
  if (command && ['ensure', 'publish'].includes(command.operation)) {
340
509
  phase = 'migration';
@@ -363,6 +532,9 @@ export function createHttpArtifactApp(deps) {
363
532
  }
364
533
  if (capability === 'artifacts_get_source') {
365
534
  const artifactId = normalized.artifactId;
535
+ // LOT 2 §B.3: profile caps instead of hard-coded ceilings (fail-closed
536
+ // at compile time; defaults stay 32 files / 262 144 B total).
537
+ const sourceOp = profile.operations.find((entry) => entry.operation === 'get_source');
366
538
  const result = await readArtifactSource({
367
539
  storageScopeId: invocation.storageScopeId,
368
540
  authorize: async () => {
@@ -373,11 +545,82 @@ export function createHttpArtifactApp(deps) {
373
545
  }
374
546
  }, getCurrent: deps.publication.getCurrent, getRelease: deps.publication.getRelease,
375
547
  getSource: (id) => deps.sources.getSource(id), getBlob: (key) => deps.publication.blobs.getBlob(key),
376
- urls: deps.publicationUrls, maxFiles: 32, maxTotalBytes: 262144,
548
+ urls: deps.publicationUrls,
549
+ maxFiles: sourceOp?.limits['sourceFilesMax'] ?? SERVER_MAX_SOURCE_FILES,
550
+ maxInlineBytes: sourceOp?.limits['sourceInlineFileBytesMax'] ?? SERVER_MAX_SOURCE_INLINE_BYTES,
551
+ maxTotalBytes: sourceOp?.limits['sourceTotalBytesMax'] ?? SERVER_MAX_SOURCE_TOTAL_BYTES,
377
552
  }, normalized);
378
553
  return { ok: true, result: { status: 200, body: result }, invocationId: invocation.invocationId,
379
554
  commitState: 'not_committed', replayed: false };
380
555
  }
556
+ if (capability === 'artifacts_list_assets') {
557
+ const artifactId = normalized.artifactId;
558
+ const acl = await visible(artifactId, invocation);
559
+ const listState = normalized.state ?? 'all';
560
+ const wantStaged = listState === 'staged' || listState === 'all';
561
+ const wantReleased = listState === 'released' || listState === 'all';
562
+ // Staged rows are owner-only (access_denied, never a filtered empty list);
563
+ // the source read right gates the released branch below.
564
+ if (wantStaged && acl.ownerId !== invocation.actorId) {
565
+ throw new ArtifactOperationError('access_denied');
566
+ }
567
+ const limit = normalized.limit;
568
+ const cursor = normalized.cursor;
569
+ const releaseId = normalized.releaseId;
570
+ const pageSessionId = normalized.pageSessionId;
571
+ const stagedEntries = [];
572
+ if (wantStaged) {
573
+ if (deps.uploads === undefined)
574
+ throw new ArtifactProfileInputError(true);
575
+ const rows = await deps.uploads.sessions.listStagedFiles(artifactId);
576
+ for (const record of rows
577
+ .filter((entry) => pageSessionId === undefined || entry.pageSessionId === pageSessionId)
578
+ .sort((left, right) => (left.path < right.path ? -1 : left.path > right.path ? 1 : 0))) {
579
+ stagedEntries.push({ path: record.path, mimeType: record.mimeType, size: record.size,
580
+ digest: record.digest, state: 'staged', uploadId: record.uploadId,
581
+ ...(record.pageSessionId === undefined ? {} : { pageSessionId: record.pageSessionId }) });
582
+ }
583
+ }
584
+ const releasedEntries = [];
585
+ let listedReleaseId;
586
+ if (wantReleased) {
587
+ const artifactState = await deps.lifecycle.stateOf(artifactId);
588
+ if (!deps.lifecycle.canRead({ artifactId, state: artifactState }, acl, invocation.actorId, 'source', deps.isApprovedAccount, await sharingPolicyContext(invocation.storageScopeId))) {
589
+ throw new ArtifactOperationError('access_denied');
590
+ }
591
+ const current = releaseId === undefined ? await deps.publication.getCurrent(artifactId)
592
+ : deps.publication.getRelease === undefined ? undefined
593
+ : await deps.publication.getRelease(releaseId);
594
+ // A release of another artifact reads as empty (no cross-artifact oracle).
595
+ if (current !== undefined && (releaseId === undefined || current.artifactId === artifactId)) {
596
+ listedReleaseId = current.releaseId;
597
+ const manifest = parseManifest(current.manifest);
598
+ for (const file of manifest.files ?? []) {
599
+ releasedEntries.push({ path: file.path, mimeType: file.mimeType, size: file.size,
600
+ digest: file.digest, state: 'released', releaseId: current.releaseId });
601
+ }
602
+ }
603
+ }
604
+ const stagedPaths = new Set(stagedEntries.map((entry) => entry.path));
605
+ const entries = [...stagedEntries,
606
+ ...releasedEntries.filter((entry) => !stagedPaths.has(entry.path))];
607
+ let offset = 0;
608
+ if (cursor !== undefined) {
609
+ const decoded = Buffer.from(cursor, 'base64url').toString('utf8');
610
+ const match = /^lot2-assets:(\d+)$/.exec(decoded);
611
+ if (match?.[1] === undefined || !Number.isSafeInteger(Number(match[1]))) {
612
+ throw new ArtifactProfileInputError();
613
+ }
614
+ offset = Math.min(Number(match[1]), entries.length);
615
+ }
616
+ const page = entries.slice(offset, offset + limit);
617
+ const nextCursor = offset + limit < entries.length
618
+ ? Buffer.from(`lot2-assets:${offset + limit}`, 'utf8').toString('base64url') : undefined;
619
+ return { ok: true, invocationId: invocation.invocationId, commitState: 'not_committed', replayed: false,
620
+ result: { status: 200, body: { artifactId,
621
+ ...(listedReleaseId === undefined ? {} : { releaseId: listedReleaseId }), assets: page,
622
+ total: entries.length, ...(nextCursor === undefined ? {} : { nextCursor }) } } };
623
+ }
381
624
  if (capability === 'artifacts_set_access' || capability === 'artifacts_delete') {
382
625
  const artifactId = normalized.artifactId;
383
626
  const acl = capability === 'artifacts_set_access'
@@ -501,10 +744,14 @@ export function createHttpArtifactApp(deps) {
501
744
  });
502
745
  }
503
746
  catch (cause) {
504
- if (cause instanceof Error && /quota exceeded/.test(cause.message)) {
747
+ if (cause instanceof Error && /open upload session quota/.test(cause.message)) {
505
748
  throw new ArtifactOperationError('limit_exceeded', { cause,
506
749
  publicDetails: { upload: { reason: 'open_session_quota' } } });
507
750
  }
751
+ if (cause instanceof Error && /scope staging quota/.test(cause.message)) {
752
+ throw new ArtifactOperationError('limit_exceeded', { cause,
753
+ publicDetails: { upload: { reason: 'scope_staging_quota' } } });
754
+ }
508
755
  if (cause instanceof Error && /invalid/.test(cause.message))
509
756
  throw new ArtifactProfileInputError();
510
757
  throw cause;
@@ -526,46 +773,34 @@ export function createHttpArtifactApp(deps) {
526
773
  const path = normalized.path;
527
774
  const commitInput = { uploadId, artifactId, storageScopeId: invocation.storageScopeId,
528
775
  ownerId: acl.ownerId, path, mimeType, digest, size };
776
+ // LOT 2: the shared commit core — same code as the browser page channel.
777
+ const commitDeps = { sessions: deps.uploads.sessions,
778
+ staging: deps.uploads.staging, blobs: deps.publication.blobs, refs: deps.publication.refs,
779
+ budget: { filesMax: budget.filesMax, totalBytesMax: budget.totalBytesMax },
780
+ ...(deps.uploads.metrics === undefined ? {} : { metrics: deps.uploads.metrics }) };
529
781
  const work = async () => {
530
- let session;
531
- try {
532
- session = await uploadService.sessionForCommit(commitInput);
533
- }
534
- catch (cause) {
535
- // One response for unknown, foreign-bound, closed or expired sessions (no oracle).
536
- throw new ArtifactOperationError('verification_failed', { cause,
537
- publicDetails: { upload: { reason: 'session unknown, bound elsewhere, closed or expired' } } });
538
- }
539
- const key = stagingKey(invocation.storageScopeId, uploadId);
540
- const bytes = await deps.uploads.staging.get(key);
541
- if (bytes === undefined) {
542
- throw new ArtifactOperationError('verification_failed', { publicDetails: { upload: { reason: 'staged object missing' } } });
543
- }
544
- // Re-verify declared size + digest + MIME against the staged bytes (review finding 3).
782
+ let staged;
545
783
  try {
546
- uploadService.verifyStaged(session, bytes, { digest, size, mimeType });
784
+ staged = await commitStagedUpload(uploadService, commitDeps, commitInput);
547
785
  }
548
786
  catch (cause) {
787
+ if (cause instanceof Error && /budget exceeded/.test(cause.message)) {
788
+ throw new ArtifactOperationError('limit_exceeded', { cause,
789
+ publicDetails: { upload: { reason: 'staged_budget' } } });
790
+ }
791
+ if (cause instanceof Error && (/unknown upload/.test(cause.message) || /closed/.test(cause.message))) {
792
+ // One response for unknown, foreign-bound, closed or expired sessions (no oracle).
793
+ throw new ArtifactOperationError('verification_failed', { cause,
794
+ publicDetails: { upload: { reason: 'session unknown, bound elsewhere, closed or expired' } } });
795
+ }
796
+ if (cause instanceof Error && /staged object missing/.test(cause.message)) {
797
+ throw new ArtifactOperationError('verification_failed', { publicDetails: { upload: { reason: 'staged object missing' } } });
798
+ }
549
799
  throw new ArtifactOperationError('verification_failed', { cause,
550
800
  publicDetails: { upload: { reason: 'size/digest/MIME mismatch' } } });
551
801
  }
552
- // Promote to the digest-addressed CAS blob via the #907 bounded pool + read-back.
553
- const casKey = blobKey(invocation.storageScopeId, digest);
554
- const concurrency = resolveBlobConcurrency(deps.publication.blobConcurrency);
555
- await runBlobPool([{ key: casKey, bytes }], { concurrency }, async (item) => { await deps.publication.blobs.putBlob(item.key, item.bytes); });
556
- await verifyStagedBlobs(deps.publication.blobs, [{ key: casKey, bytes }], { concurrency });
557
- const pinReason = `upload:${uploadId}`;
558
- await deps.publication.refs.pin(digest, pinReason);
559
- let staged;
560
- try {
561
- staged = await uploadService.completeCommit(session, { path, mimeType, digest, size });
562
- }
563
- catch (cause) {
564
- await deps.publication.refs.unpin(digest, pinReason).catch(() => undefined);
565
- throw cause;
566
- }
567
- await deps.uploads.staging.delete(key);
568
- return { artifactId, uploadId, path, mimeType, digest, size, state: 'staged', stagedAt: staged.createdAt };
802
+ return { artifactId, uploadId, path, mimeType, digest, size,
803
+ state: 'staged', stagedAt: staged.createdAt };
569
804
  };
570
805
  let body;
571
806
  if (deps.uploads.idempotency !== undefined && command !== undefined) {
@@ -588,6 +823,32 @@ export function createHttpArtifactApp(deps) {
588
823
  return { ok: true, invocationId: invocation.invocationId, commitState: 'committed', replayed: false,
589
824
  result: { status: 201, body } };
590
825
  }
826
+ if (capability === 'artifacts_create_upload_page') {
827
+ const artifactId = normalized.artifactId;
828
+ const acl = await visible(artifactId, invocation);
829
+ if (acl.ownerId !== invocation.actorId)
830
+ throw new ArtifactOperationError('access_denied');
831
+ let minted;
832
+ try {
833
+ minted = await pageService.mint({ artifactId, storageScopeId: invocation.storageScopeId,
834
+ ownerId: acl.ownerId,
835
+ ...(normalized.maxFiles === undefined ? {} : { maxFiles: normalized.maxFiles }) });
836
+ }
837
+ catch (cause) {
838
+ if (cause instanceof Error && /quota exceeded/.test(cause.message)) {
839
+ throw new ArtifactOperationError('limit_exceeded', { cause,
840
+ publicDetails: { upload: { reason: 'open_page_quota' } } });
841
+ }
842
+ if (cause instanceof Error && /invalid/.test(cause.message))
843
+ throw new ArtifactProfileInputError();
844
+ throw cause;
845
+ }
846
+ return { ok: true, invocationId: invocation.invocationId, commitState: 'not_committed', replayed: false,
847
+ result: { status: 201, body: { pageSessionId: minted.pageSessionId,
848
+ uploadPageUrl: minted.uploadPageUrl, expiresAt: minted.expiresAt, maxFiles: minted.maxFiles,
849
+ maxFileBytes: minted.maxFileBytes, maxTotalBytes: minted.maxTotalBytes,
850
+ allowedMimeTypes: minted.allowedMimeTypes } } };
851
+ }
591
852
  if (capability === 'artifacts_publish_bundle') {
592
853
  const artifactId = normalized.artifactId;
593
854
  const acl = await visible(artifactId, invocation);
@@ -605,51 +866,65 @@ export function createHttpArtifactApp(deps) {
605
866
  if (replay !== undefined)
606
867
  return commitOutcome(replay, artifactId, meta, state => { commitState = state; });
607
868
  profile.validate(capability, args, request.idempotencyKey);
608
- // Resolve the files/assets union BEFORE any commit step: one missing or
609
- // digest-mismatched asset fails the whole publish and commits nothing.
610
- const files = [];
611
- const origins = {};
612
- for (const file of (normalized.files ?? [])) {
613
- const bytes = Uint8Array.from(file.bytes);
614
- validateFileBytes(file.mimeType, bytes);
615
- files.push({ path: file.path, mimeType: file.mimeType, bytes });
616
- origins[file.path] = 'inline';
617
- }
618
- for (const asset of (normalized.assets ?? [])) {
619
- const path = asset.path;
620
- if (Object.hasOwn(asset, 'uploadId')) {
621
- const staged = await deps.uploads.sessions.getStagedFile(asset.uploadId);
622
- if (staged === undefined || staged.artifactId !== artifactId) {
623
- throw new ArtifactOperationError('verification_failed', { publicDetails: { asset: { path, reason: 'unknown upload' } } });
624
- }
625
- const bytes = await deps.publication.blobs.getBlob(blobKey(invocation.storageScopeId, staged.digest));
626
- if (bytes === undefined || bytes.length !== staged.size ||
627
- `sha256:${createHash('sha256').update(bytes).digest('hex')}` !== staged.digest) {
628
- throw new ArtifactOperationError('verification_failed', { publicDetails: { asset: { path, reason: 'staged blob missing or digest mismatch' } } });
629
- }
630
- validateFileBytes(staged.mimeType, bytes);
631
- files.push({ path, mimeType: staged.mimeType, bytes });
632
- origins[path] = `upload:${staged.uploadId}`;
869
+ // Resolve the files/assets union BEFORE any commit step: one missing,
870
+ // expired or digest-mismatched asset fails the whole publish and commits nothing.
871
+ const { files, origins, uploadPins } = await resolveBundleAssets(invocation, artifactId, {
872
+ files: (normalized.files ?? []),
873
+ assets: (normalized.assets ?? []),
874
+ }, { allowExtendedForms: false, keepUnmodifiedPaths: false, expectedCurrentReleaseId: null });
875
+ const outcome = await publication.publishFinalized({
876
+ ...input, source: { kind: 'inline-original' },
877
+ profile: normalized.profile, files,
878
+ });
879
+ const committed = commitOutcome(outcome, artifactId, meta, (state) => { commitState = state; });
880
+ if (committed.ok) {
881
+ const parsedBundleManifest = parseManifest(committed.result.body.manifest);
882
+ const entries = parsedBundleManifest.files ?? [];
883
+ committed.result.body.files = entries.map((entry) => ({
884
+ path: entry.path, mimeType: entry.mimeType, size: entry.size, digest: entry.digest,
885
+ origin: origins[entry.path] ?? 'inline',
886
+ }));
887
+ // LOT 2 §D.1/D.3: unpin consumed upload pins (sweeper is the
888
+ // backstop) and meter every bundled asset by coarse origin.
889
+ for (const pin of uploadPins) {
890
+ await deps.publication.refs.unpin(pin.digest, `upload:${pin.uploadId}`).catch(() => undefined);
633
891
  }
634
- else {
635
- const digest = asset.digest;
636
- const size = asset.size;
637
- const mimeType = asset.mimeType;
638
- const bytes = await deps.publication.blobs.getBlob(blobKey(invocation.storageScopeId, digest));
639
- if (bytes === undefined) {
640
- throw new ArtifactOperationError('verification_failed', { publicDetails: { asset: { path, reason: 'blob missing' } } });
892
+ if (deps.uploads?.metrics !== undefined) {
893
+ for (const file of files) {
894
+ const origin = origins[file.path] ?? 'inline';
895
+ deps.uploads.metrics.emit({ name: 'bundle_assets',
896
+ labels: { origin: origin.startsWith('upload:') ? 'upload' : origin } });
641
897
  }
642
- if (bytes.length !== size || `sha256:${createHash('sha256').update(bytes).digest('hex')}` !== digest) {
643
- throw new ArtifactOperationError('verification_failed', { publicDetails: { asset: { path, reason: 'size/digest mismatch' } } });
644
- }
645
- validateFileBytes(mimeType, bytes);
646
- files.push({ path, mimeType, bytes });
647
- origins[path] = 'cas';
648
898
  }
649
899
  }
900
+ return committed;
901
+ }
902
+ if (capability === 'artifacts_publish_bundle_v2') {
903
+ const artifactId = normalized.artifactId;
904
+ const acl = await visible(artifactId, invocation);
905
+ if (acl.ownerId !== invocation.actorId)
906
+ throw new ArtifactOperationError('access_denied');
907
+ const publication = createGuardedPublicationService({ ...deps.publication, coordinator: deps.coordinator,
908
+ limits: { maxFiles: budget.filesMax, maxFileBytes: budget.fileBytesMax, maxTotalBytes: budget.totalBytesMax } });
909
+ const meta = metadataOf(normalized);
910
+ const input = { ownerId: acl.ownerId, storageScopeId: invocation.storageScopeId, artifactId,
911
+ identity: command.identity, actorId: invocation.actorId, invocationId: invocation.invocationId,
912
+ attemptId: invocation.invocationId, policyRevision: await deps.ensureHost.readPolicyRevision(),
913
+ authorizeCommit: invocation.authorizeCommit, metadata: meta, operation: 'publish',
914
+ expectedCurrentReleaseId: normalized.expectedCurrentReleaseId };
915
+ const replay = await publication.replayFinalized(input);
916
+ if (replay !== undefined)
917
+ return commitOutcome(replay, artifactId, meta, state => { commitState = state; });
918
+ profile.validate(capability, args, request.idempotencyKey);
919
+ const resolved = await resolveBundleAssets(invocation, artifactId, {
920
+ files: (normalized.files ?? []),
921
+ assets: (normalized.assets ?? []),
922
+ }, { allowExtendedForms: true,
923
+ keepUnmodifiedPaths: normalized.keepUnmodifiedPaths === true,
924
+ expectedCurrentReleaseId: normalized.expectedCurrentReleaseId });
650
925
  const outcome = await publication.publishFinalized({
651
926
  ...input, source: { kind: 'inline-original' },
652
- profile: normalized.profile, files,
927
+ profile: normalized.profile, files: resolved.files,
653
928
  });
654
929
  const committed = commitOutcome(outcome, artifactId, meta, (state) => { commitState = state; });
655
930
  if (committed.ok) {
@@ -657,8 +932,22 @@ export function createHttpArtifactApp(deps) {
657
932
  const entries = parsedBundleManifest.files ?? [];
658
933
  committed.result.body.files = entries.map((entry) => ({
659
934
  path: entry.path, mimeType: entry.mimeType, size: entry.size, digest: entry.digest,
660
- origin: origins[entry.path] ?? 'inline',
935
+ origin: resolved.origins[entry.path] ?? 'inline',
661
936
  }));
937
+ // LOT 2 §D.1: consumed upload pins leave with the bundle; the
938
+ // release ref keeps the blob alive. Best-effort: the sweeper is
939
+ // the backstop and reports what it unpins.
940
+ for (const pin of resolved.uploadPins) {
941
+ await deps.publication.refs.unpin(pin.digest, `upload:${pin.uploadId}`).catch(() => undefined);
942
+ }
943
+ if (deps.uploads?.metrics !== undefined) {
944
+ for (const file of resolved.files) {
945
+ const origin = resolved.origins[file.path] ?? 'inline';
946
+ const coarse = origin.startsWith('copy:') ? 'copy' : origin.startsWith('carry:') ? 'carry'
947
+ : origin.startsWith('upload:') ? 'upload' : origin;
948
+ deps.uploads.metrics.emit({ name: 'bundle_assets', labels: { origin: coarse } });
949
+ }
950
+ }
662
951
  }
663
952
  return committed;
664
953
  }
@@ -10,8 +10,8 @@ export { createRadarKeyDerivation } from './server/command-identity.js';
10
10
  export type { ArtifactKeyDerivationBinding } from './server/command-identity.js';
11
11
  export declare const ARTIFACTS_PROVIDER_ID = "sentropic.artifacts";
12
12
  export declare const ARTIFACTS_APP_ID = "sentropic-artifacts";
13
- export declare const ARTIFACTS_PROVIDER_VERSION = "0.2.13";
14
- export declare const ARTIFACTS_TOOL_NAMES: readonly ["artifacts_get_template", "artifacts_get_api_guide", "artifacts_ensure", "artifacts_publish", "artifacts_create_upload", "artifacts_commit_upload", "artifacts_list", "artifacts_get", "artifacts_get_source", "artifacts_fork", "artifacts_set_access", "artifacts_promote", "artifacts_renew", "artifacts_delete", "artifacts_restore", "artifacts_list_versions", "artifacts_revert", "artifacts_lookup_people", "artifacts_list_access", "artifacts_publish_bundle", "artifacts_revoke_reader_consent"];
13
+ export declare const ARTIFACTS_PROVIDER_VERSION = "0.2.14";
14
+ export declare const ARTIFACTS_TOOL_NAMES: readonly ["artifacts_get_template", "artifacts_get_api_guide", "artifacts_ensure", "artifacts_publish", "artifacts_create_upload", "artifacts_commit_upload", "artifacts_list", "artifacts_get", "artifacts_get_source", "artifacts_fork", "artifacts_set_access", "artifacts_promote", "artifacts_renew", "artifacts_delete", "artifacts_restore", "artifacts_list_versions", "artifacts_revert", "artifacts_lookup_people", "artifacts_list_access", "artifacts_publish_bundle", "artifacts_revoke_reader_consent", "artifacts_create_upload_page", "artifacts_list_assets", "artifacts_publish_bundle_v2"];
15
15
  export type ArtifactsToolName = (typeof ARTIFACTS_TOOL_NAMES)[number];
16
16
  export interface ArtifactsToolDefinition {
17
17
  readonly description: string;
@@ -24,7 +24,7 @@ export interface ArtifactsToolDefinition {
24
24
  /** Static wire definitions for every artifacts tool; identical across deployments and profiles. */
25
25
  export declare const ARTIFACTS_TOOL_DEFINITIONS: Readonly<Record<ArtifactsToolName, ArtifactsToolDefinition>>;
26
26
  export declare const ARTIFACTS_TOOL_SPECS: {
27
- name: "artifacts_get_template" | "artifacts_get_api_guide" | "artifacts_ensure" | "artifacts_publish" | "artifacts_create_upload" | "artifacts_commit_upload" | "artifacts_list" | "artifacts_get" | "artifacts_get_source" | "artifacts_fork" | "artifacts_set_access" | "artifacts_promote" | "artifacts_renew" | "artifacts_delete" | "artifacts_restore" | "artifacts_list_versions" | "artifacts_revert" | "artifacts_lookup_people" | "artifacts_list_access" | "artifacts_publish_bundle" | "artifacts_revoke_reader_consent";
27
+ name: "artifacts_get_template" | "artifacts_get_api_guide" | "artifacts_ensure" | "artifacts_publish" | "artifacts_create_upload" | "artifacts_commit_upload" | "artifacts_list" | "artifacts_get" | "artifacts_get_source" | "artifacts_fork" | "artifacts_set_access" | "artifacts_promote" | "artifacts_renew" | "artifacts_delete" | "artifacts_restore" | "artifacts_list_versions" | "artifacts_revert" | "artifacts_lookup_people" | "artifacts_list_access" | "artifacts_publish_bundle" | "artifacts_revoke_reader_consent" | "artifacts_create_upload_page" | "artifacts_list_assets" | "artifacts_publish_bundle_v2";
28
28
  description: string;
29
29
  mutability: import("@sentropic/mcp-platform").Mutability;
30
30
  }[];