@sentropic/artifacts 0.2.15 → 0.2.17

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 CHANGED
@@ -1,5 +1,54 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.2.17
4
+
5
+ - Application assets carry the worker's own same-origin/no-eval CSP; HTML inline hashes stay confined to HTML responses.
6
+ - Application content mode (host-configured, owner decision 05/11): the
7
+ generic host offers `safe` (historic strict regime, default, bit-for-bit
8
+ unchanged) and `application` (binding J1.0 policy: same-origin workers,
9
+ runtime-injected styles, history fallback to `index.html` for
10
+ extensionless HTML navigations). Service workers stay refused in both
11
+ modes; a missing asset stays 404, never the fallback. The policy lives in
12
+ one constant so the conductor can relay adjustments.
13
+ - Generic extension to MIME map: `.geojson` → `application/json`,
14
+ `.mjs` → `text/javascript`, `.woff2` → `font/woff2`; `.wasm` →
15
+ `application/wasm` and `.pbf` → `application/x-protobuf` stay mapped as
16
+ the owner asked. No `wasm-unsafe-eval` in any served policy.
17
+ - Generic grant contract (J1.3b): first-party grant route wired to
18
+ `grantWithFreshRights`, neutral host-parameterizable consent screen,
19
+ typed 403 `{ code, scopeId, retryable: false }` with a single prescribed
20
+ screen navigation, scopes and versions host-declared.
21
+ - No MCP tool definition changes (the 17 pre-existing definitions stay
22
+ byte-identical). Stays in `0.2.x` (cluster-mesh peer `>=0.2.0 <0.3.0`).
23
+
24
+ ## 0.2.16
25
+
26
+ - Upload channel integrity, fail-closed (immo preprod, OVH S3 403): the
27
+ presigned PUT no longer announces `x-amz-checksum-sha256`. The digest is
28
+ declared at commit, so the checksum header could never be signed at
29
+ `create_upload` time, and strict S3 implementations refuse presigned PUTs
30
+ carrying an unsigned `x-amz-*` header (`AccessDenied`, headers present but
31
+ not signed). `create_upload` now returns exactly the signed header set
32
+ (`content-type` + exact `content-length`) in `requiredHeaders`, with no
33
+ `checksumHeader` field; the client (agent SDK/CI and the browser upload
34
+ page) sends exactly those headers and nothing else. Signing the checksum
35
+ instead would have required the digest at create time, i.e. a change to the
36
+ frozen `artifacts_create_upload` input schema; it also depends on S3
37
+ checksum support that the repo's minio double does not guarantee, while a
38
+ plain PUT works on OVH and minio alike (immo verified the headerless PUT
39
+ returns 200 on preprod).
40
+ - `commit_upload` no longer trusts the declared digest alone: it re-reads the
41
+ staged bytes and re-verifies size, SHA-256 and MIME server-side, and any
42
+ mismatch now refuses with a typed `UploadVerificationError` (mapped to
43
+ `verification_failed` at the HTTP layer with the same public reasons),
44
+ deletes the staged object, closes the session, and pins nothing — a
45
+ poisoned upload can never be retried into a release. The CAS read-back
46
+ mismatch path deletes the suspect blob too.
47
+ - No MCP tool definition changes (the 17 pre-existing definitions stay
48
+ byte-identical); only the `create_upload` response shape loses the
49
+ `checksumHeader` field. Stays in `0.2.x` (cluster-mesh peer `>=0.2.0
50
+ <0.3.0`).
51
+
3
52
  ## 0.2.15
4
53
 
5
54
  - R1: every model-visible userRef projection emits the opaque `unknown` value
package/README.md CHANGED
@@ -255,20 +255,21 @@ Large or binary files never travel through the model or the MCP payload:
255
255
  `artifacts/<scope>/staging/<uploadId>` (URL expiry ≤ 10 minutes). A SigV4
256
256
  presigned PUT cannot carry a content-length range, so the signature binds the
257
257
  content type and the exact declared `Content-Length` (`maxSize`, itself capped
258
- by the release per-file limit and the 16 MiB server ceiling); the PUT must also
259
- carry `x-amz-checksum-sha256` (base64 SHA-256 of the body), which S3 validates
260
- against the body (`BadDigest` on mismatch). The local agent performs the PUT
261
- with exactly the returned `requiredHeaders`. Open sessions per principal are
262
- capped (server maximum 8); stale sessions are expired by the enforced sweeper
263
- in `gc.ts` (`createUploadSweeper`, driven by `uploads.expires_at`).
264
- `artifacts_commit_upload` then declares `{path, mimeType, digest, size}`; the
265
- server re-reads the staged object once and re-verifies size, SHA-256 digest and
266
- MIME (magic bytes, strict UTF-8, SVG script/handler/href rules) before
267
- promoting the bytes to the digest-addressed blob store
268
- (`artifacts/<scope>/blobs/sha256/<hex>`) through the bounded blob pool with
269
- read-back verification, and pinning them with reason `upload:<uploadId>`.
270
- A wrong size or digest is refused with `verification_failed` (422) and nothing
271
- is pinned; commit alone creates no release. `artifacts_publish_bundle` finally
258
+ by the release per-file limit and the 16 MiB server ceiling), and nothing else:
259
+ no checksum header is signed or announced, because strict S3 implementations
260
+ (OVH) refuse presigned PUTs carrying an unsigned `x-amz-*` header. The local
261
+ agent performs the PUT with exactly the returned `requiredHeaders` and no other
262
+ header. Open sessions per principal are capped (server maximum 8); stale
263
+ sessions are expired by the enforced sweeper in `gc.ts` (`createUploadSweeper`,
264
+ driven by `uploads.expires_at`). `artifacts_commit_upload` then declares
265
+ `{path, mimeType, digest, size}`; the server re-reads the staged object once
266
+ and re-verifies size, SHA-256 digest and MIME (magic bytes, strict UTF-8, SVG
267
+ script/handler/href rules) before promoting the bytes to the digest-addressed
268
+ blob store (`artifacts/<scope>/blobs/sha256/<hex>`) through the bounded blob
269
+ pool with read-back verification, and pinning them with reason
270
+ `upload:<uploadId>`. A wrong size or digest is refused with
271
+ `verification_failed` (422): the staged object is deleted, the session is
272
+ closed, and nothing is pinned; commit alone creates no release. `artifacts_publish_bundle` finally
272
273
  publishes one atomic release from inline `files` and/or `assets` (each asset
273
274
  `{path, uploadId}` or `{path, digest, size, mimeType}` referencing an
274
275
  already-pinned blob of the same scope); `expectedCurrentReleaseId` is always
@@ -7,11 +7,12 @@
7
7
  *
8
8
  * UploadSignerPort over `@aws-sdk/s3-request-presigner`: the signature binds
9
9
  * content-type and the EXACT Content-Length (a SigV4 presigned PUT cannot
10
- * carry a content-length range — review finding 3), plus the checksum header
11
- * when the digest is known at signing time. `x-amz-checksum-sha256` is passed
12
- * as unhoistable so it stays a signed header instead of being hoisted into
13
- * the query string. The client (endpoint, region, credentials, path style) is
14
- * built by the host and injected — this module never reads env or connects.
10
+ * carry a content-length range — review finding 3), and nothing else. No
11
+ * checksum header is signed or announced: the digest is declared at commit
12
+ * and strict S3 implementations (OVH) refuse presigned PUTs carrying unsigned
13
+ * `x-amz-*` headers. The returned headers are exactly the signed set. The
14
+ * client (endpoint, region, credentials, path style) is built by the host and
15
+ * injected — this module never reads env or connects.
15
16
  */
16
17
  import { type S3Client } from '@aws-sdk/client-s3';
17
18
  import { type StagingStore, type UploadSignerPort } from '../server/uploads.js';
@@ -27,7 +28,7 @@ export interface S3UploadSignerOptions {
27
28
  }
28
29
  /**
29
30
  * Create a presigned-PUT signer over an injected client. The signature binds
30
- * content-type + exact content-length (declared size) and, when the digest is
31
- * known, x-amz-checksum-sha256 (kept as a signed header via unhoistableHeaders).
31
+ * content-type + exact content-length (declared size) and nothing else; the
32
+ * returned headers are exactly the signed set (no `x-amz-*` header).
32
33
  */
33
34
  export declare function createS3UploadSigner(options: S3UploadSignerOptions): UploadSignerPort;
@@ -7,15 +7,16 @@
7
7
  *
8
8
  * UploadSignerPort over `@aws-sdk/s3-request-presigner`: the signature binds
9
9
  * content-type and the EXACT Content-Length (a SigV4 presigned PUT cannot
10
- * carry a content-length range — review finding 3), plus the checksum header
11
- * when the digest is known at signing time. `x-amz-checksum-sha256` is passed
12
- * as unhoistable so it stays a signed header instead of being hoisted into
13
- * the query string. The client (endpoint, region, credentials, path style) is
14
- * built by the host and injected — this module never reads env or connects.
10
+ * carry a content-length range — review finding 3), and nothing else. No
11
+ * checksum header is signed or announced: the digest is declared at commit
12
+ * and strict S3 implementations (OVH) refuse presigned PUTs carrying unsigned
13
+ * `x-amz-*` headers. The returned headers are exactly the signed set. The
14
+ * client (endpoint, region, credentials, path style) is built by the host and
15
+ * injected — this module never reads env or connects.
15
16
  */
16
17
  import { DeleteObjectCommand, GetObjectCommand, ListObjectsV2Command, PutObjectCommand, } from '@aws-sdk/client-s3';
17
18
  import { getSignedUrl } from '@aws-sdk/s3-request-presigner';
18
- import { assertStagingKey, assertStagingPrefix, checksumHeaderValue, } from '../server/uploads.js';
19
+ import { assertStagingKey, assertStagingPrefix, } from '../server/uploads.js';
19
20
  /** Create an S3-backed staging store over an injected client (no env reads). */
20
21
  export function createS3StagingStore(options) {
21
22
  return {
@@ -63,8 +64,8 @@ export function createS3StagingStore(options) {
63
64
  }
64
65
  /**
65
66
  * Create a presigned-PUT signer over an injected client. The signature binds
66
- * content-type + exact content-length (declared size) and, when the digest is
67
- * known, x-amz-checksum-sha256 (kept as a signed header via unhoistableHeaders).
67
+ * content-type + exact content-length (declared size) and nothing else; the
68
+ * returned headers are exactly the signed set (no `x-amz-*` header).
68
69
  */
69
70
  export function createS3UploadSigner(options) {
70
71
  return {
@@ -73,22 +74,14 @@ export function createS3UploadSigner(options) {
73
74
  if (!Number.isSafeInteger(input.contentLength) || input.contentLength < 0) {
74
75
  throw new Error('invalid signed content-length');
75
76
  }
76
- const checksumHeader = input.checksumSha256 === undefined
77
- ? undefined
78
- : checksumHeaderValue(input.checksumSha256);
79
77
  const command = new PutObjectCommand({
80
78
  Bucket: options.bucket,
81
79
  Key: input.key,
82
80
  ContentType: input.contentType,
83
81
  ContentLength: input.contentLength,
84
- ...(checksumHeader === undefined ? {} : { ChecksumSHA256: checksumHeader }),
85
82
  });
86
83
  const url = await getSignedUrl(options.client, command, {
87
84
  expiresIn: input.expiresInSeconds,
88
- // keep the checksum a signed header (x-amz-* headers are hoisted to the
89
- // query by default); content-type/content-length are never hoisted and
90
- // are therefore always signed headers the client must send exactly.
91
- unhoistableHeaders: new Set(['x-amz-checksum-sha256']),
92
85
  });
93
86
  return {
94
87
  url,
@@ -96,7 +89,6 @@ export function createS3UploadSigner(options) {
96
89
  headers: {
97
90
  'content-type': input.contentType,
98
91
  'content-length': String(input.contentLength),
99
- ...(checksumHeader === undefined ? {} : { 'x-amz-checksum-sha256': checksumHeader }),
100
92
  },
101
93
  expiresAt: new Date(Date.now() + input.expiresInSeconds * 1000).toISOString(),
102
94
  };
@@ -4,6 +4,7 @@ import type { LifecycleService } from '../server/lifecycle.js';
4
4
  import { type SharingPolicyPort } from '../server/ports.js';
5
5
  import type { PublicationBlobStore, PublicationService } from '../server/publication.js';
6
6
  import { type GrantSigner, type TicketService } from './grants.js';
7
+ import { type ContentMode } from './headers.js';
7
8
  export interface ContentRequest {
8
9
  method: string;
9
10
  host: string;
@@ -14,6 +15,8 @@ export interface ContentRequest {
14
15
  ticket?: string;
15
16
  /** Raw HTTP Range header, mapped by the host; absent ⇒ whole file. */
16
17
  range?: string;
18
+ /** Raw HTTP Accept header, mapped by the host; absent ⇒ navigation fallback allowed. */
19
+ accept?: string;
17
20
  }
18
21
  export interface ContentResponse {
19
22
  status: number;
@@ -37,6 +40,10 @@ export interface ContentHandlerDeps {
37
40
  /** G1 lock 1 (deployment capability), absent ⇒ closed. */
38
41
  allowPublicSharing?: boolean;
39
42
  assetCacheSeconds?: number;
43
+ /** Host-configured mode (owner decision 05/11): `safe` default, `application` for real SPAs. */
44
+ contentMode?: ContentMode;
45
+ /** Per-release inline script hashes for the served HTML file, application mode only. */
46
+ getScriptHashes?: (filePath: string) => readonly string[] | undefined;
40
47
  }
41
48
  /** Create the content handler over injected host ports (no server). */
42
49
  export declare function createContentHandler(deps: ContentHandlerDeps): {
@@ -18,6 +18,21 @@ import { combineSharingPolicy, resolveSharingPolicy } from '../server/ports.js';
18
18
  import { CONTENT_GRANT_TTL_SECONDS } from './grants.js';
19
19
  import { contentHeaders, grantCookie, parseGrantCookie } from './headers.js';
20
20
  import { isServiceWorkerPath, parseContentHost, resolveContentPath } from './routing.js';
21
+ /**
22
+ * History fallback (application mode only): an extensionless HTML navigation
23
+ * serves the release entry instead of 404. Missing assets (extension
24
+ * present), reader protocol paths and non-HTML data fetches stay 404.
25
+ */
26
+ function isHistoryFallback(filePath, accept) {
27
+ if (filePath === '_reader' || filePath.startsWith('_reader/'))
28
+ return false;
29
+ const last = filePath.split('/').pop() ?? '';
30
+ if (last.includes('.'))
31
+ return false;
32
+ if (accept === undefined)
33
+ return true;
34
+ return accept.split(',').some((part) => part.split(';')[0]?.trim() === 'text/html');
35
+ }
21
36
  function jsonResponse(status, body, extra = {}) {
22
37
  return { status, body, headers: {
23
38
  ...contentHeaders({ mimeType: 'application/json', size: Buffer.byteLength(JSON.stringify(body)) }),
@@ -83,16 +98,24 @@ export function createContentHandler(deps) {
83
98
  const bytes = await deps.blobs.getBlob(key);
84
99
  return bytes === undefined ? undefined : bytes.slice(start, end + 1);
85
100
  }
86
- async function serveFile(artifactId, manifest, filePath, rangeHeader) {
101
+ async function serveFile(artifactId, manifest, filePath, rangeHeader, accept) {
87
102
  const acl = await deps.acls.getArtifactAcl(artifactId);
88
103
  if (acl === undefined)
89
104
  return fail(404);
90
105
  if (acl.storageScopeId === undefined)
91
106
  return fail(500);
107
+ const mode = deps.contentMode ?? 'safe';
92
108
  const parsed = JSON.parse(manifest);
93
- const file = (parsed.files ?? []).find((entry) => entry.path === filePath);
109
+ let file = (parsed.files ?? []).find((entry) => entry.path === filePath);
110
+ let servedPath = filePath;
111
+ if ((file === undefined || typeof file.digest !== 'string') &&
112
+ mode === 'application' && isHistoryFallback(filePath, accept)) {
113
+ file = (parsed.files ?? []).find((entry) => entry.path === 'index.html');
114
+ servedPath = 'index.html';
115
+ }
94
116
  if (file === undefined || typeof file.digest !== 'string')
95
117
  return fail(404);
118
+ const scriptHashes = mode === 'application' ? deps.getScriptHashes?.(servedPath) : undefined;
96
119
  const hex = file.digest.startsWith('sha256:') ? file.digest.slice(7) : file.digest;
97
120
  const key = `artifacts/${acl.storageScopeId}/blobs/sha256/${hex}`;
98
121
  const mimeType = typeof file.mimeType === 'string' ? file.mimeType : 'application/octet-stream';
@@ -117,7 +140,7 @@ export function createContentHandler(deps) {
117
140
  return {
118
141
  status: 206,
119
142
  headers: { ...contentHeaders({ mimeType, size: bytes.length,
120
- assetCacheSeconds: deps.assetCacheSeconds }),
143
+ assetCacheSeconds: deps.assetCacheSeconds, mode, scriptHashes }),
121
144
  'content-range': `bytes ${range.start}-${range.end}/${size}`,
122
145
  'accept-ranges': 'bytes' },
123
146
  bytes,
@@ -134,7 +157,7 @@ export function createContentHandler(deps) {
134
157
  return {
135
158
  status: 200,
136
159
  headers: { ...contentHeaders({ mimeType, size: bytes.length,
137
- assetCacheSeconds: deps.assetCacheSeconds }),
160
+ assetCacheSeconds: deps.assetCacheSeconds, mode, scriptHashes }),
138
161
  'accept-ranges': 'bytes' },
139
162
  bytes,
140
163
  };
@@ -211,7 +234,7 @@ export function createContentHandler(deps) {
211
234
  const filePath = resolveContentPath(request.path);
212
235
  if (filePath === undefined || isServiceWorkerPath(filePath))
213
236
  return fail(404);
214
- return serveFile(artifactId, release.manifest, filePath, request.range);
237
+ return serveFile(artifactId, release.manifest, filePath, request.range, request.accept);
215
238
  }
216
239
  return {
217
240
  async handle(request) {
@@ -11,11 +11,24 @@
11
11
  * prefix: Secure, Path=/, no Domain attribute).
12
12
  */
13
13
  export declare const GRANT_COOKIE_NAME = "__Host-artifacts_grant";
14
+ /** Host-configured content mode (owner decision 05/11): safe is the historic strict regime and the default. */
15
+ export type ContentMode = 'safe' | 'application';
16
+ /**
17
+ * Application-mode HTML policy (binding J1.0, measured on the real immo UI
18
+ * build): same-origin module workers, runtime-injected styles, blob media.
19
+ * No `unsafe-eval`, no `wasm-unsafe-eval`, no `blob:` worker. Kept as one
20
+ * constant so the conductor can relay adjustments.
21
+ */
22
+ export declare const APPLICATION_HTML_CSP: string;
14
23
  export interface ContentHeaderInput {
15
24
  mimeType: string;
16
25
  size: number;
17
26
  /** Explicit host opt-in for non-HTML asset caching (seconds). */
18
27
  assetCacheSeconds?: number;
28
+ /** Host-configured mode: `safe` (default, historic strict) or `application` (J1.0 policy). */
29
+ mode?: ContentMode;
30
+ /** Per-release inline script hashes, application mode only. */
31
+ scriptHashes?: readonly string[];
19
32
  }
20
33
  /** Security/cache headers for one served file (declared MIME wins). */
21
34
  export declare function contentHeaders(input: ContentHeaderInput): Record<string, string>;
@@ -11,7 +11,7 @@
11
11
  * prefix: Secure, Path=/, no Domain attribute).
12
12
  */
13
13
  export const GRANT_COOKIE_NAME = '__Host-artifacts_grant';
14
- const HTML_CSP = [
14
+ const SAFE_HTML_CSP = [
15
15
  "default-src 'self'",
16
16
  "script-src 'self' 'unsafe-inline'",
17
17
  "style-src 'self' 'unsafe-inline'",
@@ -23,6 +23,39 @@ const HTML_CSP = [
23
23
  "form-action 'none'",
24
24
  "frame-ancestors 'none'",
25
25
  ].join('; ');
26
+ /**
27
+ * Application-mode HTML policy (binding J1.0, measured on the real immo UI
28
+ * build): same-origin module workers, runtime-injected styles, blob media.
29
+ * No `unsafe-eval`, no `wasm-unsafe-eval`, no `blob:` worker. Kept as one
30
+ * constant so the conductor can relay adjustments.
31
+ */
32
+ export const APPLICATION_HTML_CSP = [
33
+ "default-src 'self'",
34
+ "script-src 'self'",
35
+ "style-src 'self' 'unsafe-inline'",
36
+ "img-src 'self' data: blob:",
37
+ "font-src 'self'",
38
+ "media-src 'self' blob:",
39
+ "connect-src 'self'",
40
+ "worker-src 'self'",
41
+ "child-src 'self'",
42
+ "frame-src 'none'",
43
+ "frame-ancestors 'none'",
44
+ "object-src 'none'",
45
+ "base-uri 'none'",
46
+ "form-action 'none'",
47
+ ].join('; ');
48
+ const SCRIPT_HASH_RE = /^'sha256-[A-Za-z0-9+/=]+'$/;
49
+ /** Application policy with per-release inline script hashes appended to `script-src` only. */
50
+ function applicationCsp(scriptHashes) {
51
+ if (scriptHashes === undefined || scriptHashes.length === 0)
52
+ return APPLICATION_HTML_CSP;
53
+ for (const hash of scriptHashes) {
54
+ if (!SCRIPT_HASH_RE.test(hash))
55
+ throw new Error(`invalid inline script hash: ${hash}`);
56
+ }
57
+ return APPLICATION_HTML_CSP.replace("script-src 'self'", `script-src 'self' ${scriptHashes.join(' ')}`);
58
+ }
26
59
  /**
27
60
  * Active-content types that can script or navigate when navigated to
28
61
  * directly get a sandboxed CSP in addition to `nosniff`: SVG (validated at
@@ -38,6 +71,11 @@ export function contentHeaders(input) {
38
71
  const isHtml = mimeType === 'text/html';
39
72
  const withCharset = mimeType.startsWith('text/') ? `${mimeType}; charset=utf-8` : mimeType;
40
73
  const cacheable = !isHtml && input.assetCacheSeconds !== undefined && input.assetCacheSeconds > 0;
74
+ const mode = input.mode ?? 'safe';
75
+ // Workers enforce the script response's policy, not the document's CSP.
76
+ // Cover every application asset so alternate JavaScript MIME types cannot bypass it.
77
+ const csp = mode === 'application' ? applicationCsp(isHtml ? input.scriptHashes : undefined)
78
+ : isHtml ? SAFE_HTML_CSP : undefined;
41
79
  return {
42
80
  'content-type': withCharset,
43
81
  'content-length': String(input.size),
@@ -46,7 +84,7 @@ export function contentHeaders(input) {
46
84
  'cache-control': cacheable ? `private, max-age=${input.assetCacheSeconds}` : 'no-store',
47
85
  'x-frame-options': 'DENY',
48
86
  'referrer-policy': 'no-referrer',
49
- ...(isHtml ? { 'content-security-policy': HTML_CSP } : {}),
87
+ ...(csp === undefined ? {} : { 'content-security-policy': csp }),
50
88
  ...(SANDBOXED_MIME_TYPES.has(mimeType) ? { 'content-security-policy': SANDBOX_CSP } : {}),
51
89
  };
52
90
  }
package/dist/http.js CHANGED
@@ -9,7 +9,7 @@ import { combineSharingPolicy, maskEmailHint, resolveSharingPolicy, UNKNOWN_USER
9
9
  import { createGuardedPublicationService } from './server/publication.js';
10
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 { commitStagedUpload, createUploadService, STAGED_FILE_TTL_MS, stagedFileExpired } from './server/uploads.js';
12
+ import { commitStagedUpload, createUploadService, STAGED_FILE_TTL_MS, stagedFileExpired, UploadVerificationError } from './server/uploads.js';
13
13
  import { createHmacUploadPageCookieSigner, createMemoryUploadPageStore, createUploadPageService } from './server/upload-page.js';
14
14
  import { accessModeOf, evaluateGrant } from './server/access.js';
15
15
  import { assertConsentScopeId } from './server/consent.js';
@@ -796,7 +796,7 @@ export function createHttpArtifactApp(deps) {
796
796
  return { ok: true, invocationId: invocation.invocationId, commitState: 'not_committed', replayed: false,
797
797
  result: { status: 201, body: { uploadId: created.uploadId, uploadUrl: created.uploadUrl,
798
798
  method: created.method, expiresAt: created.expiresAt, maxSize: created.maxSize,
799
- requiredHeaders: created.requiredHeaders, checksumHeader: created.checksumHeader } } };
799
+ requiredHeaders: created.requiredHeaders } } };
800
800
  }
801
801
  if (capability === 'artifacts_commit_upload') {
802
802
  const artifactId = normalized.artifactId;
@@ -825,8 +825,22 @@ export function createHttpArtifactApp(deps) {
825
825
  throw new ArtifactOperationError('limit_exceeded', { cause,
826
826
  publicDetails: { upload: { reason: 'staged_budget' } } });
827
827
  }
828
+ if (cause instanceof UploadVerificationError) {
829
+ const sessionReasons = ['unknown_upload', 'session_not_open', 'session_expired'];
830
+ if (sessionReasons.includes(cause.reason)) {
831
+ // One response for unknown, foreign-bound, closed or expired sessions (no oracle).
832
+ throw new ArtifactOperationError('verification_failed', { cause,
833
+ publicDetails: { upload: { reason: 'session unknown, bound elsewhere, closed or expired' } } });
834
+ }
835
+ if (cause.reason === 'staged_missing') {
836
+ throw new ArtifactOperationError('verification_failed', { publicDetails: { upload: { reason: 'staged object missing' } } });
837
+ }
838
+ throw new ArtifactOperationError('verification_failed', { cause,
839
+ publicDetails: { upload: { reason: 'size/digest/MIME mismatch' } } });
840
+ }
841
+ // Legacy plain-error fallback (e.g. a session store racing a
842
+ // delete between commit steps): same public reasons as before.
828
843
  if (cause instanceof Error && (/unknown upload/.test(cause.message) || /closed/.test(cause.message))) {
829
- // One response for unknown, foreign-bound, closed or expired sessions (no oracle).
830
844
  throw new ArtifactOperationError('verification_failed', { cause,
831
845
  publicDetails: { upload: { reason: 'session unknown, bound elsewhere, closed or expired' } } });
832
846
  }
@@ -10,7 +10,7 @@ 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.15";
13
+ export declare const ARTIFACTS_PROVIDER_VERSION = "0.2.17";
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 {
package/dist/mcp-core.js CHANGED
@@ -6,7 +6,7 @@ export * from './profile/index.js';
6
6
  export { createRadarKeyDerivation } from './server/command-identity.js';
7
7
  export const ARTIFACTS_PROVIDER_ID = 'sentropic.artifacts';
8
8
  export const ARTIFACTS_APP_ID = 'sentropic-artifacts';
9
- export const ARTIFACTS_PROVIDER_VERSION = '0.2.15';
9
+ export const ARTIFACTS_PROVIDER_VERSION = '0.2.17';
10
10
  export const ARTIFACTS_TOOL_NAMES = ARTIFACT_CAPABILITY_NAMES;
11
11
  // ---------------------------------------------------------------------------
12
12
  // Byte-stable tool definitions (MCP tool-definition stability rule).
@@ -20,6 +20,15 @@ export declare const TEXT_MIME_RE: RegExp;
20
20
  * single-label content origin, and sandbox CSP on SVG/PDF.
21
21
  */
22
22
  export declare const SERVER_MIME_CEILING: readonly string[];
23
+ /**
24
+ * J1.1a — generic extension to MIME map (binding J1.0 relay). `.geojson`
25
+ * serves as `application/json`, `.mjs` as `text/javascript` and `.woff2` as
26
+ * `font/woff2`; `.wasm` and `.pbf` stay mapped as the owner asked. Every
27
+ * value stays inside the server ceiling.
28
+ */
29
+ export declare const EXTENSION_TO_MIME: Readonly<Record<string, string>>;
30
+ /** MIME type for a manifest path by extension, case-insensitive, undefined off-map. */
31
+ export declare function mimeTypeForPath(path: string): string | undefined;
23
32
  /** True when the MIME type is inside the generic ceiling. */
24
33
  export declare function isWithinMimeCeiling(mimeType: string): boolean;
25
34
  /**
@@ -26,7 +26,49 @@ export const SERVER_MIME_CEILING = Object.freeze([
26
26
  'application/pdf',
27
27
  'font/woff', 'font/woff2', 'font/ttf', 'font/otf',
28
28
  'video/mp4', 'video/webm',
29
+ // J1.1a: bound application assets. Served bytes can never compile without
30
+ // `wasm-unsafe-eval`, which no served policy carries.
31
+ 'application/wasm',
32
+ 'application/x-protobuf',
29
33
  ]);
34
+ /**
35
+ * J1.1a — generic extension to MIME map (binding J1.0 relay). `.geojson`
36
+ * serves as `application/json`, `.mjs` as `text/javascript` and `.woff2` as
37
+ * `font/woff2`; `.wasm` and `.pbf` stay mapped as the owner asked. Every
38
+ * value stays inside the server ceiling.
39
+ */
40
+ export const EXTENSION_TO_MIME = Object.freeze({
41
+ '.html': 'text/html',
42
+ '.js': 'text/javascript',
43
+ '.mjs': 'text/javascript',
44
+ '.css': 'text/css',
45
+ '.json': 'application/json',
46
+ '.geojson': 'application/json',
47
+ '.svg': 'image/svg+xml',
48
+ '.png': 'image/png',
49
+ '.jpg': 'image/jpeg',
50
+ '.jpeg': 'image/jpeg',
51
+ '.gif': 'image/gif',
52
+ '.webp': 'image/webp',
53
+ '.avif': 'image/avif',
54
+ '.ico': 'image/x-icon',
55
+ '.pdf': 'application/pdf',
56
+ '.woff': 'font/woff',
57
+ '.woff2': 'font/woff2',
58
+ '.ttf': 'font/ttf',
59
+ '.otf': 'font/otf',
60
+ '.mp4': 'video/mp4',
61
+ '.webm': 'video/webm',
62
+ '.wasm': 'application/wasm',
63
+ '.pbf': 'application/x-protobuf',
64
+ });
65
+ /** MIME type for a manifest path by extension, case-insensitive, undefined off-map. */
66
+ export function mimeTypeForPath(path) {
67
+ const dot = path.lastIndexOf('.');
68
+ if (dot === -1)
69
+ return undefined;
70
+ return EXTENSION_TO_MIME[path.slice(dot).toLowerCase()];
71
+ }
30
72
  /** True when the MIME type is inside the generic ceiling. */
31
73
  export function isWithinMimeCeiling(mimeType) {
32
74
  return SERVER_MIME_CEILING.includes(mimeType);
@@ -42,6 +84,7 @@ const MAGIC_BYTES = Object.freeze({
42
84
  'application/pdf': [[0x25, 0x50, 0x44, 0x46, 0x2d]], // %PDF-
43
85
  'font/woff': [[0x77, 0x4f, 0x46, 0x46]], // wOFF
44
86
  'font/woff2': [[0x77, 0x4f, 0x46, 0x32]], // wOF2
87
+ 'application/wasm': [[0x00, 0x61, 0x73, 0x6d]], // \0asm
45
88
  'font/ttf': [[0x00, 0x01, 0x00, 0x00]],
46
89
  'font/otf': [[0x4f, 0x54, 0x54, 0x4f]], // OTTO
47
90
  'video/mp4': [[0x66, 0x74, 0x79, 0x70]], // ftyp (brand checked loosely: isom/iso2/mp41/mp42/avc1/dash/msdh/m4v...)
@@ -120,6 +163,10 @@ export function validateFileBytes(mimeType, bytes) {
120
163
  throw new Error('mp4 magic bytes mismatch');
121
164
  return;
122
165
  }
166
+ // Opaque protobuf has no magic: any bytes pass (the ceiling allowlist and
167
+ // the serving policy without `wasm-unsafe-eval` stay the guards).
168
+ if (mimeType === 'application/x-protobuf')
169
+ return;
123
170
  const magics = MAGIC_BYTES[mimeType];
124
171
  if (magics === undefined)
125
172
  throw new Error(`no magic-byte rule for ${mimeType}`);
@@ -64,17 +64,18 @@ const GUIDE_V1 = [
64
64
  ' commitState, replayed/output on success, or typed error details on failure.',
65
65
  '- `artifacts_create_upload`: mint a presigned PUT for one staging key',
66
66
  ' (`artifacts/<scope>/staging/<uploadId>`, URL expiry <= 10 minutes). The',
67
- ' signature binds the content type and the exact declared content length;',
68
- ' the PUT must also carry `x-amz-checksum-sha256` (base64 SHA-256 of the',
69
- ' body) and S3 rejects a mismatching body. Perform the PUT yourself (curl,',
70
- ' SDK, CI) with exactly the returned `requiredHeaders` — no MCP call ever',
71
- ' carries file bytes. Open sessions per principal are quota-limited.',
67
+ ' signature binds the content type and the exact declared content length,',
68
+ ' and nothing else: send exactly the returned `requiredHeaders`, no extra',
69
+ ' header (strict S3 implementations refuse unsigned `x-amz-*` headers).',
70
+ ' Perform the PUT yourself (curl, SDK, CI) — no MCP call ever carries file',
71
+ ' bytes. Open sessions per principal are quota-limited.',
72
72
  '- `artifacts_commit_upload`: declare `{path, mimeType, digest, size}` for a',
73
73
  ' staged upload; the server re-reads the staged object once and re-verifies',
74
74
  ' size, SHA-256 digest and MIME (magic bytes / strict UTF-8 / SVG rules)',
75
75
  ' before promoting it to the digest-addressed blob store and pinning it.',
76
- ' A wrong size or digest is refused with `verification_failed` and nothing',
77
- ' is pinned. Commit creates no release by itself.',
76
+ ' A wrong size or digest is refused with `verification_failed`: the staged',
77
+ ' object is deleted, the session is closed, and nothing is pinned.',
78
+ ' Commit creates no release by itself.',
78
79
  '- `artifacts_publish_bundle`: one atomic release from inline `files` and/or',
79
80
  ' `assets` — each asset is `{path, uploadId}` (staged via create_upload +',
80
81
  ' PUT + commit_upload) or `{path, digest, size, mimeType}` (an already-pinned',
@@ -122,8 +123,8 @@ const GUIDE_V1 = [
122
123
  '1. `artifacts_ensure` to resolve the artifact.',
123
124
  '2. Per file: `artifacts_create_upload {artifactId, mimeType, maxSize?}`,',
124
125
  ' then PUT the local file to the returned `uploadUrl` with exactly the',
125
- ' returned `requiredHeaders` plus `x-amz-checksum-sha256` (base64 SHA-256',
126
- ' of the body), then `artifacts_commit_upload {artifactId, uploadId, path,',
126
+ ' returned `requiredHeaders` and no other header, then',
127
+ ' `artifacts_commit_upload {artifactId, uploadId, path,',
127
128
  ' mimeType, digest: "sha256:<hex>", size, idempotencyKey}`.',
128
129
  '3. One `artifacts_publish_bundle {artifactId, idempotencyKey,',
129
130
  ' expectedCurrentReleaseId, assets: [{path, uploadId}, ...]}` — assets-only',
@@ -50,6 +50,13 @@ export declare function buildUploadPageCookie(value: string, maxAgeSeconds: numb
50
50
  export declare function parseUploadPageCookie(header: string | undefined): string | undefined;
51
51
  /** Page CSP (§A.4): no external assets; S3 origins are host-supplied. */
52
52
  export declare function uploadPageCsp(s3Origins: readonly string[]): string;
53
+ /**
54
+ * J1.1a — browser fallback MIME by extension for the upload page, used only
55
+ * when the browser reports no `File.type`: `.geojson` as `application/json`,
56
+ * `.mjs` as `text/javascript`, `.woff2` as `font/woff2`, plus owner-kept
57
+ * `.wasm` and `.pbf`. Rendered into the page as JSON.
58
+ */
59
+ export declare const BROWSER_EXTENSION_FALLBACK_MIME: Readonly<Record<string, string>>;
53
60
  /**
54
61
  * Self-contained static upload page (no external assets). Bytes travel
55
62
  * browser → S3 via raw PUT (FormData is banned: multipart wrapping changes
@@ -137,7 +144,6 @@ export interface UploadPageService {
137
144
  expiresAt: string;
138
145
  maxSize: number;
139
146
  requiredHeaders: Record<string, string>;
140
- checksumHeader: 'x-amz-checksum-sha256';
141
147
  stagingKey: string;
142
148
  }>;
143
149
  commitFile(input: PageCommitInput): Promise<StagedFileRecord>;
@@ -132,6 +132,21 @@ export function uploadPageCsp(s3Origins) {
132
132
  'img-src \'self\' blob:', 'font-src \'self\'', `connect-src 'self' ${s3Origins.join(' ')}`,
133
133
  'base-uri \'none\'', 'form-action \'none\'', 'frame-ancestors \'none\''].join('; ');
134
134
  }
135
+ /**
136
+ * J1.1a — browser fallback MIME by extension for the upload page, used only
137
+ * when the browser reports no `File.type`: `.geojson` as `application/json`,
138
+ * `.mjs` as `text/javascript`, `.woff2` as `font/woff2`, plus owner-kept
139
+ * `.wasm` and `.pbf`. Rendered into the page as JSON.
140
+ */
141
+ export const BROWSER_EXTENSION_FALLBACK_MIME = Object.freeze({
142
+ geojson: 'application/json',
143
+ mjs: 'text/javascript',
144
+ woff2: 'font/woff2',
145
+ wasm: 'application/wasm',
146
+ pbf: 'application/x-protobuf',
147
+ avif: 'image/avif',
148
+ ico: 'image/x-icon',
149
+ });
135
150
  /**
136
151
  * Self-contained static upload page (no external assets). Bytes travel
137
152
  * browser → S3 via raw PUT (FormData is banned: multipart wrapping changes
@@ -181,14 +196,13 @@ const api = async (path, body, method) => {
181
196
  if (!response.ok) throw new Error(path + ' failed: ' + response.status);
182
197
  return response.json();
183
198
  };
184
- const EXT_TYPES = { woff2: 'font/woff', avif: 'image/avif', ico: 'image/x-icon' };
199
+ const EXT_TYPES = ${JSON.stringify(BROWSER_EXTENSION_FALLBACK_MIME)};
185
200
  const chunked = (bytes, f) => {
186
201
  const view = new Uint8Array(bytes);
187
202
  let out = '';
188
203
  for (let i = 0; i < view.length; i += 0x8000) out += f(view.subarray(i, i + 0x8000)));
189
204
  return out;
190
205
  };
191
- const b64 = (bytes) => btoa(chunked(bytes, (part) => String.fromCharCode(...part)));
192
206
  const hex = (bytes) => chunked(bytes, (part) => [...part].map((b) => b.toString(16).padStart(2, '0')).join(''));
193
207
  const row = (path) => {
194
208
  const li = document.createElement('li');
@@ -204,8 +218,7 @@ async function stage(file, relPath) {
204
218
  setStatus('uploading');
205
219
  const buffer = await file.arrayBuffer();
206
220
  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)) } });
221
+ headers: { 'content-type': upload.requiredHeaders['content-type'] } });
209
222
  let upload = created;
210
223
  let response = await put(upload);
211
224
  if (!response.ok) {
@@ -79,17 +79,18 @@ export interface StagingStore {
79
79
  }[]>;
80
80
  }
81
81
  /**
82
- * Presigner port. The signature binds content-type, the EXACT content-length
83
- * (declared size) and, when known at signing time, x-amz-checksum-sha256;
84
- * no content-length range exists in a SigV4 presigned PUT (review finding 3).
82
+ * Presigner port. The signature binds content-type and the EXACT
83
+ * content-length (declared size); no content-length range exists in a SigV4
84
+ * presigned PUT (review finding 3). No checksum header is signed: the digest
85
+ * is declared at commit, and announcing an unsigned `x-amz-*` header makes
86
+ * strict S3 implementations refuse the PUT. The returned headers are the
87
+ * whole contract: the client sends exactly these headers, nothing more.
85
88
  */
86
89
  export interface UploadSignerPort {
87
90
  signPut(input: {
88
91
  key: string;
89
92
  contentType: string;
90
93
  contentLength: number;
91
- /** Canonical `sha256:<hex>` digest, when known at signing time. */
92
- checksumSha256?: string;
93
94
  expiresInSeconds: number;
94
95
  }): Promise<{
95
96
  url: string;
@@ -99,16 +100,21 @@ export interface UploadSignerPort {
99
100
  expiresAt: string;
100
101
  }>;
101
102
  }
103
+ /**
104
+ * Typed verification failure for the upload channel (fail-closed commit).
105
+ * Hosts map this to `verification_failed` without trusting the message text.
106
+ */
107
+ export type UploadVerificationReason = 'unknown_upload' | 'session_not_open' | 'session_expired' | 'staged_missing' | 'size_mismatch' | 'digest_mismatch' | 'mime_mismatch' | 'cas_readback_mismatch';
108
+ export declare class UploadVerificationError extends Error {
109
+ readonly reason: UploadVerificationReason;
110
+ readonly uploadId: string;
111
+ constructor(reason: UploadVerificationReason, uploadId: string, message: string);
112
+ }
102
113
  export declare const STAGING_KEY_PATTERN: RegExp;
103
114
  /** Staging key of one upload session. */
104
115
  export declare function stagingKey(storageScopeId: string, uploadId: string): string;
105
116
  /** Staging prefix of one scope (LOT 2 §D.1 orphan pass enumerates it). */
106
117
  export declare function stagingPrefix(storageScopeId: string): string;
107
- /**
108
- * Value of the `x-amz-checksum-sha256` header for a canonical `sha256:<hex>`
109
- * digest: S3 expects the base64 of the raw digest bytes (no `sha256:` prefix).
110
- */
111
- export declare function checksumHeaderValue(digest: string): string;
112
118
  /** Reject anything but a staging key, before any I/O. */
113
119
  export declare function assertStagingKey(key: string): void;
114
120
  /** Reject empty or escaping staging prefixes before enumeration. */
@@ -128,16 +134,19 @@ export declare function createMemoryUploadSigner(): {
128
134
  key: string;
129
135
  contentType: string;
130
136
  contentLength: number;
131
- checksumSha256?: string | undefined;
132
137
  expiresAt: string;
133
138
  url: string;
134
139
  }[];
135
- /** Simulate the client PUT against "S3": signed headers are enforced exactly. */
140
+ /**
141
+ * Simulate the client PUT against a strict "S3": the signed headers are
142
+ * enforced exactly, and any `x-amz-*` header outside the signed set is
143
+ * refused — mirroring OVH S3, which rejects a presigned PUT carrying an
144
+ * unsigned `x-amz-checksum-sha256` with 403 AccessDenied.
145
+ */
136
146
  put(signedPut: {
137
147
  key: string;
138
148
  contentType: string;
139
149
  contentLength: number;
140
- checksumSha256?: string;
141
150
  }, bytes: Uint8Array, headers: Record<string, string>): void;
142
151
  };
143
152
  export interface CreateUploadInput {
@@ -163,14 +172,13 @@ export interface CreateUploadResult {
163
172
  /** Presigned-URL expiry (≤ 10 minutes). */
164
173
  expiresAt: string;
165
174
  maxSize: number;
166
- /** Headers the client must send with exactly these values (bound by the signature). */
167
- requiredHeaders: Record<string, string>;
168
175
  /**
169
- * The PUT must also carry this header with the base64 SHA-256 of the body;
170
- * S3 validates it against the body (BadDigest on mismatch) and commit
171
- * re-verifies size and digest server-side.
176
+ * Exactly the signed header set (`content-type` + `content-length`): the
177
+ * client sends these headers with exactly these values and nothing else.
178
+ * No `x-amz-*` header is announced, because no `x-amz-*` header is signed
179
+ * and strict S3 implementations refuse unsigned ones.
172
180
  */
173
- checksumHeader: 'x-amz-checksum-sha256';
181
+ requiredHeaders: Record<string, string>;
174
182
  stagingKey: string;
175
183
  }
176
184
  export interface CommitUploadInput {
@@ -8,17 +8,19 @@
8
8
  * `commit_upload` re-reads the staged object once and verifies the declared
9
9
  * size and SHA-256 digest before anything is pinned.
10
10
  *
11
- * SigV4 note (review finding 3): a presigned PUT cannot carry a
12
- * content-length RANGE (that exists only in POST policies), so the signature
13
- * binds an EXACT Content-Length (the declared size) plus the checksum header
14
- * (`x-amz-checksum-sha256`) whenever the digest is known at signing time;
15
- * S3 itself rejects a PUT whose signed headers do not match. The digest is
16
- * declared at commit, so the create-time signature binds content-type +
17
- * exact content-length, the PUT must carry `x-amz-checksum-sha256` (S3
18
- * validates it against the body, BadDigest on mismatch), and commit
19
- * re-verifies size and digest server-side before pinning. Residual exposure
20
- * of a leaked URL is bounded by the declared size (≤ 16 MiB), the
21
- * per-principal open-session quota and the enforced sweeper (gc.ts).
11
+ * SigV4 note (review finding 3, hardened 0.2.16): a presigned PUT cannot
12
+ * carry a content-length RANGE (that exists only in POST policies), so the
13
+ * signature binds an EXACT Content-Length (the declared size) plus
14
+ * content-type — and nothing else. The digest is declared at commit, so no
15
+ * checksum header can be signed at create time; announcing one anyway makes
16
+ * strict S3 implementations (OVH) refuse the PUT with 403 because the header
17
+ * is present but not signed. The client therefore sends exactly the announced
18
+ * headers, and commit re-reads the staged object once and re-verifies size,
19
+ * SHA-256 digest and MIME server-side before pinning (fail-closed: any
20
+ * mismatch refuses with a typed error, deletes the staged object, closes the
21
+ * session, and creates no release). Residual exposure of a leaked URL is
22
+ * bounded by the declared size (≤ 16 MiB), the per-principal open-session
23
+ * quota and the enforced sweeper (gc.ts).
22
24
  *
23
25
  * Sessions are durable rows (migration 0007 ALTERs `artifacts.uploads`);
24
26
  * the byte store, session store and signer are injected ports — the memory
@@ -36,6 +38,16 @@ export const STAGED_FILE_TTL_MS = 24 * 60 * 60 * 1000;
36
38
  export const STAGED_FILE_TTL_MAX_MS = 7 * 24 * 60 * 60 * 1000;
37
39
  export const ORPHAN_STAGING_GRACE_MS = 60 * 60 * 1000;
38
40
  export const ORPHAN_SWEEP_MAX_KEYS = 500;
41
+ export class UploadVerificationError extends Error {
42
+ reason;
43
+ uploadId;
44
+ constructor(reason, uploadId, message) {
45
+ super(message);
46
+ this.name = 'UploadVerificationError';
47
+ this.reason = reason;
48
+ this.uploadId = uploadId;
49
+ }
50
+ }
39
51
  export const STAGING_KEY_PATTERN = /^artifacts\/[A-Za-z0-9_-]+\/staging\/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
40
52
  /** Staging key of one upload session. */
41
53
  export function stagingKey(storageScopeId, uploadId) {
@@ -45,16 +57,6 @@ export function stagingKey(storageScopeId, uploadId) {
45
57
  export function stagingPrefix(storageScopeId) {
46
58
  return `artifacts/${storageScopeId}/staging/`;
47
59
  }
48
- /**
49
- * Value of the `x-amz-checksum-sha256` header for a canonical `sha256:<hex>`
50
- * digest: S3 expects the base64 of the raw digest bytes (no `sha256:` prefix).
51
- */
52
- export function checksumHeaderValue(digest) {
53
- const match = /^sha256:([0-9a-f]{64})$/.exec(digest);
54
- if (match === null)
55
- throw new Error(`invalid sha256 digest: ${digest}`);
56
- return Buffer.from(match[1], 'hex').toString('base64');
57
- }
58
60
  /** Reject anything but a staging key, before any I/O. */
59
61
  export function assertStagingKey(key) {
60
62
  if (!STAGING_KEY_PATTERN.test(key)) {
@@ -200,9 +202,7 @@ export function createMemoryUploadSigner() {
200
202
  }
201
203
  const expiresAt = new Date(Date.now() + input.expiresInSeconds * 1000).toISOString();
202
204
  const url = `https://s3.test/${input.key}?X-Amz-Signature=mem-${signed.length}`;
203
- const checksumHeader = input.checksumSha256 === undefined ? undefined : checksumHeaderValue(input.checksumSha256);
204
205
  signed.push({ key: input.key, contentType: input.contentType, contentLength: input.contentLength,
205
- ...(checksumHeader === undefined ? {} : { checksumSha256: checksumHeader }),
206
206
  expiresAt, url });
207
207
  return Promise.resolve({
208
208
  url,
@@ -210,7 +210,6 @@ export function createMemoryUploadSigner() {
210
210
  headers: {
211
211
  'content-type': input.contentType,
212
212
  'content-length': String(input.contentLength),
213
- ...(checksumHeader === undefined ? {} : { 'x-amz-checksum-sha256': checksumHeader }),
214
213
  },
215
214
  expiresAt,
216
215
  });
@@ -219,7 +218,12 @@ export function createMemoryUploadSigner() {
219
218
  return {
220
219
  signer,
221
220
  signed,
222
- /** Simulate the client PUT against "S3": signed headers are enforced exactly. */
221
+ /**
222
+ * Simulate the client PUT against a strict "S3": the signed headers are
223
+ * enforced exactly, and any `x-amz-*` header outside the signed set is
224
+ * refused — mirroring OVH S3, which rejects a presigned PUT carrying an
225
+ * unsigned `x-amz-checksum-sha256` with 403 AccessDenied.
226
+ */
223
227
  put(signedPut, bytes, headers) {
224
228
  if (String(bytes.length) !== headers['content-length'] || bytes.length !== signedPut.contentLength) {
225
229
  throw new Error(`content-length mismatch: signed ${signedPut.contentLength}, body ${bytes.length}`);
@@ -227,12 +231,10 @@ export function createMemoryUploadSigner() {
227
231
  if (headers['content-type'] !== signedPut.contentType) {
228
232
  throw new Error('content-type mismatch with the signed header');
229
233
  }
230
- if (signedPut.checksumSha256 !== undefined && headers['x-amz-checksum-sha256'] !== signedPut.checksumSha256) {
231
- throw new Error('x-amz-checksum-sha256 mismatch with the signed header');
232
- }
233
- if (headers['x-amz-checksum-sha256'] !== undefined &&
234
- createHash('sha256').update(bytes).digest('base64') !== headers['x-amz-checksum-sha256']) {
235
- throw new Error('BadDigest: body does not match x-amz-checksum-sha256');
234
+ for (const key of Object.keys(headers)) {
235
+ if (key.startsWith('x-amz-')) {
236
+ throw new Error(`x-amz header present but not signed: ${key}`);
237
+ }
236
238
  }
237
239
  },
238
240
  };
@@ -315,14 +317,14 @@ export function createUploadService(deps, options) {
315
317
  emit({ name: 'upload_sessions_created' });
316
318
  // The signature binds content-type and the EXACT declared Content-Length
317
319
  // (a presigned PUT cannot carry a content-length range). The digest is
318
- // declared at commit, so the PUT must also carry x-amz-checksum-sha256,
319
- // which S3 validates against the body; commit re-verifies both.
320
+ // declared at commit, so no checksum header is signed or announced;
321
+ // commit re-verifies size, digest and MIME server-side, fail-closed.
320
322
  const signed = await deps.signer.signPut({
321
323
  key, contentType: input.mimeType, contentLength: maxSize, expiresInSeconds: UPLOAD_URL_TTL_SECONDS,
322
324
  });
323
325
  return {
324
326
  uploadId, uploadUrl: signed.url, method: signed.method, expiresAt: signed.expiresAt, maxSize,
325
- requiredHeaders: signed.headers, checksumHeader: 'x-amz-checksum-sha256',
327
+ requiredHeaders: signed.headers,
326
328
  stagingKey: key,
327
329
  };
328
330
  });
@@ -331,28 +333,34 @@ export function createUploadService(deps, options) {
331
333
  return deps.sessions.get(input.uploadId).then((session) => {
332
334
  if (session === undefined || session.artifactId !== input.artifactId ||
333
335
  session.storageScopeId !== input.storageScopeId || session.ownerId !== input.ownerId) {
334
- throw new Error(`unknown upload for this artifact/owner/scope: ${input.uploadId}`);
336
+ throw new UploadVerificationError('unknown_upload', input.uploadId, `unknown upload for this artifact/owner/scope: ${input.uploadId}`);
337
+ }
338
+ if (session.state !== 'open') {
339
+ throw new UploadVerificationError('session_not_open', input.uploadId, `upload not open (${session.state}): ${input.uploadId}`);
335
340
  }
336
- if (session.state !== 'open')
337
- throw new Error(`upload not open (${session.state}): ${input.uploadId}`);
338
341
  if (new Date(session.expiresAt).getTime() <= now().getTime()) {
339
- throw new Error(`upload session expired: ${input.uploadId}`);
342
+ throw new UploadVerificationError('session_expired', input.uploadId, `upload session expired: ${input.uploadId}`);
340
343
  }
341
344
  return session;
342
345
  });
343
346
  },
344
347
  verifyStaged(session, bytes, expected) {
345
348
  if (bytes.length !== expected.size) {
346
- throw new Error(`upload size mismatch for ${session.uploadId}: staged ${bytes.length}, declared ${expected.size}`);
349
+ throw new UploadVerificationError('size_mismatch', session.uploadId, `upload size mismatch for ${session.uploadId}: staged ${bytes.length}, declared ${expected.size}`);
347
350
  }
348
351
  const actual = `sha256:${createHash('sha256').update(bytes).digest('hex')}`;
349
352
  if (actual !== expected.digest) {
350
- throw new Error(`upload digest mismatch for ${session.uploadId}: staged ${actual}`);
353
+ throw new UploadVerificationError('digest_mismatch', session.uploadId, `upload digest mismatch for ${session.uploadId}: staged ${actual}`);
351
354
  }
352
355
  if (expected.mimeType !== session.mimeType) {
353
- throw new Error(`upload MIME mismatch for ${session.uploadId}: session ${session.mimeType}, declared ${expected.mimeType}`);
356
+ throw new UploadVerificationError('mime_mismatch', session.uploadId, `upload MIME mismatch for ${session.uploadId}: session ${session.mimeType}, declared ${expected.mimeType}`);
357
+ }
358
+ try {
359
+ validateFileBytes(expected.mimeType, bytes);
360
+ }
361
+ catch (error) {
362
+ throw new UploadVerificationError('mime_mismatch', session.uploadId, `upload content mismatch for ${session.uploadId}: ${error instanceof Error ? error.message : String(error)}`);
354
363
  }
355
- validateFileBytes(expected.mimeType, bytes);
356
364
  },
357
365
  async completeCommit(session, record) {
358
366
  const staged = {
@@ -373,20 +381,43 @@ export async function commitStagedUpload(service, deps, input, channel = 'agent'
373
381
  labels: { channel, ...(event.labels ?? {}) } });
374
382
  };
375
383
  const fail = (error) => {
376
- if (!(error instanceof Error) || !/budget exceeded/.test(error.message)) {
384
+ if (error instanceof UploadVerificationError ||
385
+ !(error instanceof Error) || !/budget exceeded/.test(error.message)) {
377
386
  emit({ name: 'upload_commits', labels: { result: 'verification_failed' } });
378
387
  }
379
388
  throw error;
380
389
  };
390
+ // Fail-closed cleanup: a verification failure deletes the staged object and
391
+ // closes the session, so a poisoned upload can never be retried into a
392
+ // release and no declaration oracle survives. Best-effort: the refusal is
393
+ // what matters; cleanup failures never mask it.
394
+ const quarantine = async (uploadId, stagingKeyToDelete) => {
395
+ if (stagingKeyToDelete !== undefined) {
396
+ await deps.staging.delete(stagingKeyToDelete).catch(() => undefined);
397
+ }
398
+ await deps.sessions.markExpired(uploadId).catch(() => undefined);
399
+ };
381
400
  const session = await service.sessionForCommit(input).catch((error) => fail(error));
382
401
  const key = stagingKey(input.storageScopeId, input.uploadId);
383
- const bytes = await deps.staging.get(key) ??
384
- fail(new Error(`staged object missing for ${input.uploadId}`));
402
+ const bytes = await deps.staging.get(key);
403
+ if (bytes === undefined) {
404
+ const error = new UploadVerificationError('staged_missing', input.uploadId, `staged object missing for ${input.uploadId}`);
405
+ emit({ name: 'upload_commits', labels: { result: 'verification_failed' } });
406
+ await quarantine(input.uploadId, undefined);
407
+ throw error;
408
+ }
385
409
  try {
386
410
  service.verifyStaged(session, bytes, { digest: input.digest, size: input.size, mimeType: input.mimeType });
387
411
  }
388
412
  catch (error) {
389
- fail(error);
413
+ if (error instanceof UploadVerificationError) {
414
+ emit({ name: 'upload_commits', labels: { result: 'verification_failed' } });
415
+ await quarantine(input.uploadId, key);
416
+ }
417
+ else {
418
+ fail(error);
419
+ }
420
+ throw error;
390
421
  }
391
422
  // LOT 2 §D.2: per-artifact staged caps, checked at commit for both channels.
392
423
  const existing = await deps.sessions.listStagedFiles(input.artifactId);
@@ -401,7 +432,11 @@ export async function commitStagedUpload(service, deps, input, channel = 'agent'
401
432
  const readBack = await deps.blobs.getBlob(casKey);
402
433
  if (readBack === undefined || readBack.byteLength !== input.size ||
403
434
  `sha256:${createHash('sha256').update(readBack).digest('hex')}` !== input.digest) {
404
- fail(new Error(`CAS read-back mismatch for ${input.uploadId}`));
435
+ const error = new UploadVerificationError('cas_readback_mismatch', input.uploadId, `CAS read-back mismatch for ${input.uploadId}`);
436
+ emit({ name: 'upload_commits', labels: { result: 'verification_failed' } });
437
+ await deps.blobs.deleteBlob(casKey).catch(() => undefined);
438
+ await quarantine(input.uploadId, key);
439
+ throw error;
405
440
  }
406
441
  const pinReason = `upload:${input.uploadId}`;
407
442
  await deps.refs.pin(input.digest, pinReason);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sentropic/artifacts",
3
- "version": "0.2.15",
3
+ "version": "0.2.17",
4
4
  "description": "Generic configurable artifacts MCP and artifact service: StorageScope/Artifact/Binding/Release model, canonical manifests, object authorization, idempotent intents (spec-v8 §9).",
5
5
  "type": "module",
6
6
  "license": "MIT",