@sentropic/artifacts 0.2.12 → 0.2.13

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 (46) hide show
  1. package/CHANGELOG.md +67 -0
  2. package/README.md +45 -10
  3. package/dist/adapters/postgres-management.js +3 -2
  4. package/dist/adapters/postgres-reader-consent.d.ts +11 -0
  5. package/dist/adapters/postgres-reader-consent.js +109 -0
  6. package/dist/adapters/postgres.js +4 -3
  7. package/dist/adapters/s3-uploads.d.ts +33 -0
  8. package/dist/adapters/s3-uploads.js +105 -0
  9. package/dist/content/headers.js +12 -0
  10. package/dist/http.d.ts +16 -2
  11. package/dist/http.js +325 -12
  12. package/dist/mcp-core.d.ts +3 -3
  13. package/dist/mcp-core.js +51 -4
  14. package/dist/profile/contracts.d.ts +1 -1
  15. package/dist/profile/contracts.js +3 -0
  16. package/dist/profile/index.js +33 -2
  17. package/dist/profile/radar.js +7 -0
  18. package/dist/profile/schemas.js +59 -0
  19. package/dist/profile/validation.d.ts +11 -0
  20. package/dist/profile/validation.js +71 -6
  21. package/dist/server/access.d.ts +2 -0
  22. package/dist/server/command-identity.d.ts +1 -1
  23. package/dist/server/command-identity.js +5 -3
  24. package/dist/server/consent.d.ts +65 -0
  25. package/dist/server/consent.js +42 -0
  26. package/dist/server/gc.d.ts +17 -0
  27. package/dist/server/gc.js +22 -0
  28. package/dist/server/management.d.ts +3 -1
  29. package/dist/server/management.js +48 -7
  30. package/dist/server/mime.d.ts +26 -2
  31. package/dist/server/mime.js +124 -2
  32. package/dist/server/ports.d.ts +29 -0
  33. package/dist/server/ports.js +11 -0
  34. package/dist/server/publication-limits.d.ts +12 -0
  35. package/dist/server/publication-limits.js +19 -1
  36. package/dist/server/publication.d.ts +9 -0
  37. package/dist/server/publication.js +4 -2
  38. package/dist/server/reader-store.d.ts +58 -0
  39. package/dist/server/reader-store.js +109 -0
  40. package/dist/server/templates.js +50 -2
  41. package/dist/server/uploads.d.ts +154 -18
  42. package/dist/server/uploads.js +227 -80
  43. package/migrations/0007_uploads.sql +43 -0
  44. package/migrations/0008_reader_consent.sql +48 -0
  45. package/package.json +22 -1
  46. package/sql/reader-consent.sql +47 -0
package/CHANGELOG.md CHANGED
@@ -1,5 +1,72 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.2.13
4
+
5
+ - G2 MCP sharing tools: new read-only tools `artifacts_lookup_people`
6
+ (approved-caller guard, directory search returning opaque `userRef`s with
7
+ masked `emailHint`s, homonyms never silently resolved) and
8
+ `artifacts_list_access` (mode, owner, grant list; readers see only their own
9
+ entry; admin management visibility exception). Both ship with static,
10
+ frozen-at-publication definitions; every pre-existing tool definition keeps
11
+ its exact bytes (CI tools/list snapshot extended to the new tools).
12
+ - New `PrincipalDirectoryPort` (search, `userRef` → internal resolution,
13
+ inverse projection). `artifacts_set_access` accepts opaque `userRef`s in
14
+ `principalId` alongside the `sentropic:` sentinels; resolution happens inside
15
+ the commit transaction after visibility and the management right, so the
16
+ `commandHash` (computed on the payload as provided) never leaks a resolution.
17
+ - Every model-visible output is projected through the directory: `ownerId` and
18
+ `grants[].principalId` of `artifacts_get`/`artifacts_list`/`artifacts_ensure`,
19
+ the `artifacts_set_access` receipt, and both new tools — no internal
20
+ principal id or full email reaches a model payload. Without a port, the new
21
+ tools answer `capability_unavailable` (sentinels keep working).
22
+ - Single `person_not_shareable` 422 error merging the four non-shareable
23
+ causes (unknown, inactive, unapproved, out-of-scope), evaluated at §2.3 step
24
+ 4 after visibility and the management right; grant rows gain `createdAt`
25
+ (read from the existing `artifact_access.created_at`, no new migration).
26
+ - Shipped radar profile gains the `set_access`, `lookup_people` and
27
+ `list_access` operation profiles (the four-tool radar selection itself is
28
+ unchanged).
29
+ - Files parity LOT 1: a local agent can publish large dossiers with the bytes
30
+ outside the model. New tools `artifacts_create_upload`,
31
+ `artifacts_commit_upload` and `artifacts_publish_bundle` (static
32
+ definitions, frozen at birth; the 17 pre-existing tool definitions are
33
+ byte-identical, pinned by sha256 in the tests).
34
+ - Upload sessions are durable rows (migration `0007_uploads.sql` ALTERs the
35
+ existing `artifacts.uploads` table: artifact/scope/owner binding,
36
+ `expires_at`, `staged_files`) with a presigned signed PUT per session. A
37
+ SigV4 presigned PUT cannot carry a content-length range, so the signature
38
+ binds the EXACT declared Content-Length plus `content-type`, the PUT must
39
+ carry `x-amz-checksum-sha256` (S3 validates the body, BadDigest on
40
+ mismatch), and `commit_upload` re-verifies size, SHA-256 digest and MIME
41
+ server-side before pinning. Open sessions per principal are quota-bounded
42
+ (8) and an enforced sweeper (gc.ts) expires stale sessions and deletes their
43
+ staging objects.
44
+ - Server maxima are hard ceilings: 255 files per release, 16 MiB per file,
45
+ 64 MiB per release; profile limit keys (`releaseFilesMax`,
46
+ `releaseFileBytesMax`, `releaseTotalBytesMax` on the publish operation) may
47
+ only move below them and default to the inline values. The MIME ceiling
48
+ (17 types) is enforced at profile compile time, and every file — inline or
49
+ uploaded — is validated at commit: magic bytes for binary types, strict
50
+ UTF-8 for text, script/handler/external-reference-free SVG.
51
+ - `artifacts_publish_bundle` publishes one atomic release from the union of
52
+ inline files, `{path, uploadId}` assets and `{path, digest, size, mimeType}`
53
+ CAS assets, reusing the 0.2.12 bounded blob pool and `verifyStagedBlobs`;
54
+ one missing or digest-mismatched asset fails the whole publish and commits
55
+ nothing. The strict-profile writer ban does not cover the upload tools (they
56
+ mutate no release pointer). `artifacts_get_source` keeps its frozen
57
+ maxItems 32 ceiling; server-side caps only move below the frozen schema.
58
+ - Persistent reader consent (lot 1a): consent rows per (reader account,
59
+ artifact, scope, scope version) with a pure evaluator and Gate B helper;
60
+ the reader screen is skipped only when a live consent at the current scope
61
+ version meets fresh rights, suspension or withdrawn share refuses despite
62
+ consent. One new MCP tool `artifacts_revoke_reader_consent`
63
+ (self-revocation only, static definition frozen at birth; the 17
64
+ pre-existing tool definitions are byte-identical) plus control-origin
65
+ list/revoke API routes; revocation takes effect on the next call. Host
66
+ migration `0008_reader_consent.sql` (additive, train-numbered from the
67
+ reviewed `sql/reader-consent.sql` body); immo screen binding and silent
68
+ renew land in lot 1b.
69
+
3
70
  ## 0.2.12
4
71
 
5
72
  - Bounded concurrency in multi-file publication blob staging (#art-conc, P1):
package/README.md CHANGED
@@ -227,21 +227,53 @@ Keys are isolated by operation and
227
227
  principal. A changed payload under the same key returns an explicit conflict.
228
228
  Persisted unscoped replay keys are no longer consulted after upgrading.
229
229
 
230
- Publication defaults to 128 files, 16 MiB per file and 64 MiB total. Hosts can
230
+ Publication defaults to 255 files, 16 MiB per file and 64 MiB total. Hosts can
231
231
  override these positive integer limits through `createPublicationService({
232
232
  limits: { maxFiles, maxFileBytes, maxTotalBytes } })`; the HTTP decoder uses the
233
- same byte budgets before allocating bytes. Paths must be unique canonical
233
+ same byte budgets before allocating bytes. These profile values are bounded by
234
+ generic server maxima — 255 files per release, 16 MiB per file, 64 MiB per
235
+ release — enforced both when a profile is compiled and again in
236
+ `publicationLimits`, so a profile can only narrow them, never exceed them.
237
+ Paths must be unique canonical
234
238
  relative paths, at most 1024 UTF-8 bytes: empty/dot segments, backslashes,
235
239
  percent escapes, URL delimiters, colons and control characters are rejected.
236
240
  Existing integrations using larger bundles or noncanonical paths must adjust
237
241
  their limits or filenames. Invalid publications fail before object-store effects.
238
- Upload sessions cap client `maxSize` by the host `maxUploadBytes` and publication
239
- file/total limits. Every append checks remaining cumulative capacity before
240
- decoding bytes or writing staging. Upload publication metadata is validated
241
- before the session is consumed; a rejected path or MIME type can be corrected
242
- and committed using the same staged bytes. Finalization validates, hashes and
243
- publishes one copied snapshot. Overlapping append/commit operations return 409;
244
- failed verification or metadata validation leaves the session retryable.
242
+
243
+ Two budgets exist because inline MCP bytes cost model tokens while uploaded
244
+ bytes do not: the inline keys (`publishFilesMax`, `maxDecodedFileBytes`,
245
+ `maxDecodedTotalBytes`) bound what travels inside `artifacts_publish` and the
246
+ inline `files` of `artifacts_publish_bundle`, while the release keys
247
+ (`releaseFilesMax`, `releaseFileBytesMax`, `releaseTotalBytesMax` on the same
248
+ publish operation) bound the final release however its files arrived; absent
249
+ release keys default to the inline values.
250
+
251
+ ## Uploading files outside the model (signed PUT)
252
+
253
+ Large or binary files never travel through the model or the MCP payload:
254
+ `artifacts_create_upload` mints a presigned PUT for exactly one staging key
255
+ `artifacts/<scope>/staging/<uploadId>` (URL expiry ≤ 10 minutes). A SigV4
256
+ presigned PUT cannot carry a content-length range, so the signature binds the
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
272
+ publishes one atomic release from inline `files` and/or `assets` (each asset
273
+ `{path, uploadId}` or `{path, digest, size, mimeType}` referencing an
274
+ already-pinned blob of the same scope); `expectedCurrentReleaseId` is always
275
+ required, the release budget applies to the union, and one missing or
276
+ mismatched asset fails the whole publish before anything commits.
245
277
 
246
278
  Content `HEAD` responses have the corresponding GET headers and no body,
247
279
  including errors and activation. Errors and activation responses include the
@@ -457,7 +489,10 @@ Size and digest are verified on the raw bytes, then each file is encoded for the
457
489
  wire: text mime types as `text` with `encoding: "utf8"`, all other files as
458
490
  `base64` with `encoding: "base64"` — never an integer array. The result carries
459
491
  a `guideRef` (`{tool, version}`) instead of the guide body. The snapshot is
460
- limited to 32 files and 262144 decoded bytes. Hosts must qualify
492
+ limited to 32 files and 262144 decoded bytes: that ceiling is part of the
493
+ frozen `artifacts_get_source` tool definition and does not move; server-side
494
+ caps may only go below it, and larger listings belong to dedicated listing
495
+ tools. Hosts must qualify
461
496
  a 2 MiB serialized MCP result budget before selecting this capability.
462
497
 
463
498
  `POST /set_access` grants or revokes a named principal's read access, requires a
@@ -2,8 +2,9 @@ import { applyModeTransition, PLATFORM_PRINCIPAL, PUBLIC_PRINCIPAL } from '../se
2
2
  /** Parent lock serializes ACL inserts, lifecycle changes and publication FKs. */
3
3
  export function createPostgresManagementUnit(client) {
4
4
  const listGrants = async (id) => {
5
- const { rows } = await client.query('SELECT principal_id, permission FROM artifacts.artifact_access WHERE artifact_id = $1 ORDER BY principal_id', [id]);
6
- return rows.map((row) => ({ principalId: row.principal_id, grant: row.permission }));
5
+ const { rows } = await client.query('SELECT principal_id, permission, created_at FROM artifacts.artifact_access WHERE artifact_id = $1 ORDER BY principal_id', [id]);
6
+ return rows.map((row) => ({ principalId: row.principal_id, grant: row.permission,
7
+ createdAt: row.created_at.toISOString() }));
7
8
  };
8
9
  return {
9
10
  async lock(id) {
@@ -0,0 +1,11 @@
1
+ /**
2
+ * Lot 1a — reference Postgres adapter for the reader consent slice
3
+ * (design-merged §1.2, §3.1). Over an injected pg Pool, no DDL at runtime
4
+ * (the train numbers `sql/reader-consent.sql` at land time). Every mutation
5
+ * runs with its audit event in one transaction: a rollback removes the grant
6
+ * plus the event.
7
+ */
8
+ import type { Pool } from 'pg';
9
+ import type { ArtifactReaderStore } from '../server/reader-store.js';
10
+ /** Reference adapter; the tables come from the train-numbered migration. */
11
+ export declare function createPostgresReaderConsentStore(pool: Pool): ArtifactReaderStore;
@@ -0,0 +1,109 @@
1
+ import { assertConsentScopeId, assertConsentScopeVersion } from '../server/consent.js';
2
+ const toRecord = (row) => ({ consentId: row.consent_id,
3
+ storageScopeId: row.storage_scope_id, readerAccountId: row.reader_account_id, artifactId: row.artifact_id,
4
+ scopeId: row.scope_id, scopeVersion: row.scope_version, grantedAt: row.granted_at.toISOString(),
5
+ grantedVia: row.granted_via, ...(row.revoked_at === null ? {} : { revokedAt: row.revoked_at.toISOString() }),
6
+ ...(row.revoked_by === null ? {} : { revokedBy: row.revoked_by }) });
7
+ const LIVE_WHERE = `storage_scope_id = $1 AND reader_account_id = $2 AND artifact_id = $3
8
+ AND scope_id = $4 AND scope_version = $5 AND revoked_at IS NULL`;
9
+ async function tx(pool, work) {
10
+ const client = await pool.connect();
11
+ try {
12
+ await client.query('BEGIN');
13
+ try {
14
+ const result = await work(client);
15
+ await client.query('COMMIT');
16
+ return result;
17
+ }
18
+ catch (error) {
19
+ await client.query('ROLLBACK').catch(() => undefined);
20
+ throw error;
21
+ }
22
+ }
23
+ finally {
24
+ client.release();
25
+ }
26
+ }
27
+ const INSERT_EVENT = `INSERT INTO artifacts.reader_consent_events (consent_id, storage_scope_id,
28
+ reader_account_id, artifact_id, scope_id, scope_version, action, actor, surface, created_at)
29
+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)`;
30
+ /** Reference adapter; the tables come from the train-numbered migration. */
31
+ export function createPostgresReaderConsentStore(pool) {
32
+ return {
33
+ async findLiveConsent(key) {
34
+ const { rows } = await pool.query(`SELECT * FROM artifacts.reader_consents WHERE ${LIVE_WHERE}`, [key.storageScopeId, key.readerAccountId, key.artifactId, key.scopeId, key.scopeVersion]);
35
+ return rows[0] === undefined ? undefined : toRecord(rows[0]);
36
+ },
37
+ async grantConsent(record) {
38
+ assertConsentScopeId(record.scopeId);
39
+ assertConsentScopeVersion(record.scopeVersion);
40
+ return tx(pool, async (client) => {
41
+ const live = await client.query(`SELECT * FROM artifacts.reader_consents WHERE ${LIVE_WHERE} FOR UPDATE`, [record.storageScopeId, record.readerAccountId, record.artifactId, record.scopeId, record.scopeVersion]);
42
+ if (live.rows[0] !== undefined)
43
+ return toRecord(live.rows[0]);
44
+ await client.query(`INSERT INTO artifacts.reader_consents (consent_id, storage_scope_id, reader_account_id,
45
+ artifact_id, scope_id, scope_version, granted_at, granted_via)
46
+ VALUES ($1, $2, $3, $4, $5, $6, $7, 'reader_screen')`, [record.consentId, record.storageScopeId, record.readerAccountId, record.artifactId,
47
+ record.scopeId, record.scopeVersion, record.grantedAt]);
48
+ await client.query(INSERT_EVENT, [record.consentId, record.storageScopeId, record.readerAccountId,
49
+ record.artifactId, record.scopeId, record.scopeVersion, 'grant', record.readerAccountId, 'screen', record.grantedAt]);
50
+ return { ...record };
51
+ });
52
+ },
53
+ async revokeConsent(key, by, at, audit) {
54
+ return tx(pool, async (client) => {
55
+ const live = await client.query(`SELECT * FROM artifacts.reader_consents WHERE ${LIVE_WHERE} FOR UPDATE`, [key.storageScopeId, key.readerAccountId, key.artifactId, key.scopeId, key.scopeVersion]);
56
+ if (live.rows[0] === undefined)
57
+ return { changed: false };
58
+ await client.query(`UPDATE artifacts.reader_consents SET revoked_at = $1, revoked_by = $2 WHERE consent_id = $3`, [at, by, live.rows[0].consent_id]);
59
+ await client.query(INSERT_EVENT, [live.rows[0].consent_id, key.storageScopeId, key.readerAccountId,
60
+ key.artifactId, key.scopeId, key.scopeVersion, 'revoke', audit.actor, audit.surface, at]);
61
+ return { changed: true, revokedAt: at };
62
+ });
63
+ },
64
+ async revokeAllConsents(key, by, at, audit) {
65
+ return tx(pool, async (client) => {
66
+ const { rows } = await client.query(`SELECT * FROM artifacts.reader_consents
67
+ WHERE storage_scope_id = $1 AND reader_account_id = $2 AND artifact_id = $3
68
+ AND ($4::text IS NULL OR scope_id = $4) AND revoked_at IS NULL FOR UPDATE`, [key.storageScopeId, key.readerAccountId, key.artifactId, key.scopeId ?? null]);
69
+ for (const row of rows) {
70
+ await client.query(`UPDATE artifacts.reader_consents SET revoked_at = $1, revoked_by = $2 WHERE consent_id = $3`, [at, by, row.consent_id]);
71
+ await client.query(INSERT_EVENT, [row.consent_id, row.storage_scope_id, row.reader_account_id,
72
+ row.artifact_id, row.scope_id, row.scope_version, 'revoke', audit.actor, audit.surface, at]);
73
+ }
74
+ return { changed: rows.length > 0, revoked: rows.length };
75
+ });
76
+ },
77
+ async listConsentsForReader(scope, reader) {
78
+ const { rows } = await pool.query(`SELECT * FROM artifacts.reader_consents
79
+ WHERE storage_scope_id = $1 AND reader_account_id = $2 ORDER BY granted_at, consent_id`, [scope, reader]);
80
+ return rows.map(toRecord);
81
+ },
82
+ async listConsentEvents(scope, artifactId) {
83
+ const { rows } = await pool.query(`SELECT consent_id AS "consentId", storage_scope_id AS "storageScopeId",
84
+ reader_account_id AS "readerAccountId", artifact_id AS "artifactId", scope_id AS "scopeId",
85
+ scope_version AS "scopeVersion", action, actor, surface, created_at FROM artifacts.reader_consent_events
86
+ WHERE storage_scope_id = $1 AND artifact_id = $2 ORDER BY id`, [scope, artifactId]);
87
+ return rows.map((row) => ({ consentId: row.consentId, storageScopeId: row.storageScopeId,
88
+ readerAccountId: row.readerAccountId, artifactId: row.artifactId, scopeId: row.scopeId,
89
+ scopeVersion: row.scopeVersion, action: row.action,
90
+ actor: row.actor, surface: row.surface, at: row.created_at.toISOString() }));
91
+ },
92
+ async purgeForArtifact(scope, artifactId) {
93
+ await tx(pool, async (client) => {
94
+ await client.query(`DELETE FROM artifacts.reader_consent_events WHERE storage_scope_id = $1 AND artifact_id = $2`, [scope, artifactId]);
95
+ await client.query(`DELETE FROM artifacts.reader_consents WHERE storage_scope_id = $1 AND artifact_id = $2`, [scope, artifactId]);
96
+ });
97
+ },
98
+ async purgeByPrincipal(scope, principalId) {
99
+ return tx(pool, async (client) => {
100
+ await client.query(`DELETE FROM artifacts.reader_consent_events WHERE storage_scope_id = $1 AND reader_account_id = $2`, [scope, principalId]);
101
+ const removed = await client.query(`DELETE FROM artifacts.reader_consents WHERE storage_scope_id = $1 AND reader_account_id = $2`, [scope, principalId]);
102
+ return { consents: removed.rowCount ?? 0, kv: 0, docs: 0 };
103
+ });
104
+ },
105
+ async exportByPrincipal(scope, principalId) {
106
+ return { consents: await this.listConsentsForReader(scope, principalId), kv: [], meDocs: [], sharedWriteRefs: [] };
107
+ },
108
+ };
109
+ }
@@ -202,7 +202,7 @@ export function createPostgresArtifactStore(pool) {
202
202
  const row = rows[0];
203
203
  if (row === undefined)
204
204
  return undefined;
205
- const grants = await pool.query(`SELECT principal_id, permission FROM artifacts.artifact_access
205
+ const grants = await pool.query(`SELECT principal_id, permission, created_at FROM artifacts.artifact_access
206
206
  WHERE artifact_id = $1 ORDER BY principal_id`, [artifactId]);
207
207
  // G1: access_mode is authoritative; is_public is its legacy projection.
208
208
  const accessMode = (row.access_mode ?? (row.is_public ? 'platform' : 'restricted'));
@@ -217,6 +217,7 @@ export function createPostgresArtifactStore(pool) {
217
217
  grants: grants.rows.map((grant) => ({
218
218
  principalId: grant.principal_id,
219
219
  grant: grant.permission,
220
+ createdAt: grant.created_at.toISOString(),
220
221
  })),
221
222
  ...(row.metadata === null || Object.keys(row.metadata).length === 0 ? {} : { metadata: row.metadata }),
222
223
  };
@@ -239,8 +240,8 @@ export function createPostgresArtifactStore(pool) {
239
240
  // the source guard on re-insert, so the stale source grant is demoted
240
241
  // to read — the grant row is kept, never dropped.
241
242
  const permission = grant.grant === 'source' && accessMode !== 'restricted' ? 'read' : grant.grant;
242
- await pool.query(`INSERT INTO artifacts.artifact_access (artifact_id, principal_id, permission)
243
- VALUES ($1, $2, $3)`, [artifactId, grant.principalId, permission]);
243
+ await pool.query(`INSERT INTO artifacts.artifact_access (artifact_id, principal_id, permission, created_at)
244
+ VALUES ($1, $2, $3, COALESCE($4::timestamptz, now()))`, [artifactId, grant.principalId, permission, grant.createdAt ?? null]);
244
245
  }
245
246
  },
246
247
  async listArtifactIds() {
@@ -0,0 +1,33 @@
1
+ /**
2
+ * Files parity LOT 1 — S3 adapter for upload staging + presigned PUT signer.
3
+ *
4
+ * StagingStore over an injected S3 client and bucket: only keys under
5
+ * `artifacts/<scope>/staging/<uuid>` are accepted (assertStagingKey/assertStagingPrefix
6
+ * refuse anything else before any network call), mirroring adapters/s3.ts.
7
+ *
8
+ * UploadSignerPort over `@aws-sdk/s3-request-presigner`: the signature binds
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.
15
+ */
16
+ import { type S3Client } from '@aws-sdk/client-s3';
17
+ import { type StagingStore, type UploadSignerPort } from '../server/uploads.js';
18
+ export interface S3StagingStoreOptions {
19
+ client: S3Client;
20
+ bucket: string;
21
+ }
22
+ /** Create an S3-backed staging store over an injected client (no env reads). */
23
+ export declare function createS3StagingStore(options: S3StagingStoreOptions): StagingStore;
24
+ export interface S3UploadSignerOptions {
25
+ client: S3Client;
26
+ bucket: string;
27
+ }
28
+ /**
29
+ * 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).
32
+ */
33
+ export declare function createS3UploadSigner(options: S3UploadSignerOptions): UploadSignerPort;
@@ -0,0 +1,105 @@
1
+ /**
2
+ * Files parity LOT 1 — S3 adapter for upload staging + presigned PUT signer.
3
+ *
4
+ * StagingStore over an injected S3 client and bucket: only keys under
5
+ * `artifacts/<scope>/staging/<uuid>` are accepted (assertStagingKey/assertStagingPrefix
6
+ * refuse anything else before any network call), mirroring adapters/s3.ts.
7
+ *
8
+ * UploadSignerPort over `@aws-sdk/s3-request-presigner`: the signature binds
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.
15
+ */
16
+ import { DeleteObjectCommand, GetObjectCommand, ListObjectsV2Command, PutObjectCommand, } from '@aws-sdk/client-s3';
17
+ import { getSignedUrl } from '@aws-sdk/s3-request-presigner';
18
+ import { assertStagingKey, assertStagingPrefix, checksumHeaderValue, } from '../server/uploads.js';
19
+ /** Create an S3-backed staging store over an injected client (no env reads). */
20
+ export function createS3StagingStore(options) {
21
+ return {
22
+ async put(key, bytes) {
23
+ assertStagingKey(key);
24
+ await options.client.send(new PutObjectCommand({ Bucket: options.bucket, Key: key, Body: bytes }));
25
+ },
26
+ async get(key) {
27
+ assertStagingKey(key);
28
+ try {
29
+ const out = await options.client.send(new GetObjectCommand({ Bucket: options.bucket, Key: key }));
30
+ if (out.Body === undefined)
31
+ return undefined;
32
+ const collected = await out.Body.transformToByteArray();
33
+ return new Uint8Array(collected);
34
+ }
35
+ catch (error) {
36
+ if (typeof error === 'object' && error !== null && 'name' in error) {
37
+ const name = error.name;
38
+ if (name === 'NoSuchKey' || name === 'NotFound')
39
+ return undefined;
40
+ }
41
+ throw error;
42
+ }
43
+ },
44
+ async delete(key) {
45
+ assertStagingKey(key);
46
+ await options.client.send(new DeleteObjectCommand({ Bucket: options.bucket, Key: key }));
47
+ },
48
+ async listKeys(prefix) {
49
+ assertStagingPrefix(prefix);
50
+ const keys = [];
51
+ let token;
52
+ do {
53
+ const out = await options.client.send(new ListObjectsV2Command({ Bucket: options.bucket, Prefix: prefix, ContinuationToken: token }));
54
+ for (const entry of out.Contents ?? []) {
55
+ if (entry.Key !== undefined)
56
+ keys.push(entry.Key);
57
+ }
58
+ token = out.IsTruncated === true ? out.NextContinuationToken : undefined;
59
+ } while (token !== undefined);
60
+ return keys.sort();
61
+ },
62
+ };
63
+ }
64
+ /**
65
+ * 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).
68
+ */
69
+ export function createS3UploadSigner(options) {
70
+ return {
71
+ async signPut(input) {
72
+ assertStagingKey(input.key);
73
+ if (!Number.isSafeInteger(input.contentLength) || input.contentLength < 0) {
74
+ throw new Error('invalid signed content-length');
75
+ }
76
+ const checksumHeader = input.checksumSha256 === undefined
77
+ ? undefined
78
+ : checksumHeaderValue(input.checksumSha256);
79
+ const command = new PutObjectCommand({
80
+ Bucket: options.bucket,
81
+ Key: input.key,
82
+ ContentType: input.contentType,
83
+ ContentLength: input.contentLength,
84
+ ...(checksumHeader === undefined ? {} : { ChecksumSHA256: checksumHeader }),
85
+ });
86
+ const url = await getSignedUrl(options.client, command, {
87
+ 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
+ });
93
+ return {
94
+ url,
95
+ method: 'PUT',
96
+ headers: {
97
+ 'content-type': input.contentType,
98
+ 'content-length': String(input.contentLength),
99
+ ...(checksumHeader === undefined ? {} : { 'x-amz-checksum-sha256': checksumHeader }),
100
+ },
101
+ expiresAt: new Date(Date.now() + input.expiresInSeconds * 1000).toISOString(),
102
+ };
103
+ },
104
+ };
105
+ }
@@ -17,10 +17,21 @@ const HTML_CSP = [
17
17
  "style-src 'self' 'unsafe-inline'",
18
18
  "img-src 'self' data:",
19
19
  "connect-src 'self'",
20
+ "font-src 'self'",
21
+ "media-src 'self'",
20
22
  "base-uri 'none'",
21
23
  "form-action 'none'",
22
24
  "frame-ancestors 'none'",
23
25
  ].join('; ');
26
+ /**
27
+ * Active-content types that can script or navigate when navigated to
28
+ * directly get a sandboxed CSP in addition to `nosniff`: SVG (validated at
29
+ * commit against scripts/handlers/external references, sandboxed at serve
30
+ * time so direct navigation cannot script even if a construct slips
31
+ * through) and PDF.
32
+ */
33
+ const SANDBOX_CSP = "sandbox";
34
+ const SANDBOXED_MIME_TYPES = new Set(['image/svg+xml', 'application/pdf']);
24
35
  /** Security/cache headers for one served file (declared MIME wins). */
25
36
  export function contentHeaders(input) {
26
37
  const mimeType = input.mimeType.length === 0 ? 'application/octet-stream' : input.mimeType;
@@ -36,6 +47,7 @@ export function contentHeaders(input) {
36
47
  'x-frame-options': 'DENY',
37
48
  'referrer-policy': 'no-referrer',
38
49
  ...(isHtml ? { 'content-security-policy': HTML_CSP } : {}),
50
+ ...(SANDBOXED_MIME_TYPES.has(mimeType) ? { 'content-security-policy': SANDBOX_CSP } : {}),
39
51
  };
40
52
  }
41
53
  /** Host-only grant cookie header value (no Domain attribute, ever). */
package/dist/http.d.ts CHANGED
@@ -1,9 +1,12 @@
1
1
  import { type CompiledArtifactsProfile } from './profile/index.js';
2
2
  import { type ArtifactKeyDerivationBinding } from './server/command-identity.js';
3
3
  import { type GuardedEnsureHost } from './server/service.js';
4
- import { type KvPort, type SharingPolicyPort } from './server/ports.js';
4
+ import { type IdempotencyStore } from './server/idempotency.js';
5
+ import { type KvPort, type PrincipalDirectoryPort, type SharingPolicyPort } from './server/ports.js';
5
6
  import { type GuardedPublicationDeps, type PublicationService } from './server/publication.js';
6
- import type { AclStore } from './server/access.js';
7
+ import { type StagingStore, type UploadSessionStore, type UploadSignerPort } from './server/uploads.js';
8
+ import { type AclStore } from './server/access.js';
9
+ import type { ArtifactReaderStore } from './server/reader-store.js';
7
10
  import type { LifecycleService } from './server/lifecycle.js';
8
11
  import { type ArtifactInvocationContext, type ArtifactCommitCoordinator } from './server/commit/types.js';
9
12
  import { type ArtifactOutcome, type ArtifactHostFailureMapper } from './server/failures.js';
@@ -55,11 +58,22 @@ export interface HttpAppDeps {
55
58
  sharingPolicy?: SharingPolicyPort;
56
59
  /** G1: server-resolved platform admin predicate (never a tool argument). */
57
60
  actorIsAdmin?: (actorId: string, storageScopeId: string) => boolean | Promise<boolean>;
61
+ /** G2: host principal directory; required for userRef resolution and output projection. */
62
+ directory?: PrincipalDirectoryPort;
63
+ /** Lot 1a: reader consent store; absent ⇒ consent routes fail closed with `capability_unavailable`. */
64
+ readerConsent?: ArtifactReaderStore;
58
65
  /** One trusted URL policy shared by HTTP and MCP receipts: the artifact page and the exact version page. */
59
66
  publicationUrls?: (artifactId: string, releaseId: string) => {
60
67
  stableUrl: string;
61
68
  versionUrl: string;
62
69
  };
70
+ /** Files parity LOT 1: upload session ports, required when an upload capability is selected. */
71
+ uploads?: {
72
+ sessions: UploadSessionStore;
73
+ staging: StagingStore;
74
+ signer: UploadSignerPort;
75
+ idempotency?: IdempotencyStore;
76
+ };
63
77
  }
64
78
  export interface ArtifactApp {
65
79
  readonly selectedCapabilities: CompiledArtifactsProfile['selectedCapabilities'];