@sentropic/artifacts 0.2.9 → 0.2.10

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,36 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.2.10
4
+
5
+ - G1 sharing access model: artifacts carry an explicit `access_mode`
6
+ (`restricted` by default, `platform`, `public`) managed through
7
+ `artifacts_set_access` with sentinel transitions (`grant sentropic:platform`
8
+ degrades public→platform, `revoke sentropic:platform` on public is a no-op).
9
+ `restricted` mode allows at most one nominative `source` (collab) grant, and
10
+ widening the mode while a `source` grant is live is rejected. Migration
11
+ `0006_sharing.sql` is additive: `access_mode` column with CHECK, legacy
12
+ `is_public=true` backfilled to `platform` (zero artifacts become `public`),
13
+ an append-only `artifact_access_events` audit table (UPDATE/DELETE rejected by
14
+ trigger) and the Q1 schema guards (partial unique index, mode/grant triggers).
15
+ - Sharing policy is double-locked: profile rule `allowPublicSharing` (absent ⇒
16
+ false, covered by `profileDigest`) AND a runtime `SharingPolicyPort` resolved
17
+ fail-closed inside the commit transaction; public anonymous reads require the
18
+ policy to allow them. Approval freshness is enforced on read paths (suspension
19
+ cuts the next read, reactivation resumes automatically).
20
+ - D1: `set_access` visibility closes the existence oracle — a non-reader actor
21
+ gets `not_found` unless it is an approved platform admin of the same storage
22
+ scope; the management right itself (owner, or admin-reduce-only) is still
23
+ decided inside the transaction (403 otherwise).
24
+ - D2: `0006_sharing.sql` deterministically dedupes legacy multi-`source` grants
25
+ before the unique index (oldest `created_at`, tie-break `principal_id` stays
26
+ `source`; later duplicates demote to `read`; no row deleted), and
27
+ `putArtifactAcl` demotes a stale `source` grant to `read` when rewriting a
28
+ non-restricted ACL.
29
+ - MCP tool definitions stay byte-identical (new fields only, never edits).
30
+ - 0.2.10 stays inside the existing cluster-mesh `>=0.2.0 <0.3.0` peer range
31
+ (conductor allocation: #896=0.2.9, #901=0.2.10, #891=0.2.11; merge order
32
+ 896 > 901 > 891).
33
+
3
34
  ## 0.2.9
4
35
 
5
36
  - Make every `artifacts_*` MCP tool definition byte-stable across deployments,
@@ -1,5 +1,10 @@
1
+ import { applyModeTransition, PLATFORM_PRINCIPAL, PUBLIC_PRINCIPAL } from '../server/access.js';
1
2
  /** Parent lock serializes ACL inserts, lifecycle changes and publication FKs. */
2
3
  export function createPostgresManagementUnit(client) {
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 }));
7
+ };
3
8
  return {
4
9
  async lock(id) {
5
10
  await client.query('SELECT id FROM artifacts.artifacts WHERE id = $1 FOR UPDATE', [id]);
@@ -7,30 +12,48 @@ export function createPostgresManagementUnit(client) {
7
12
  await client.query('SELECT release_id FROM artifacts.artifact_current WHERE artifact_id = $1 FOR UPDATE', [id]);
8
13
  },
9
14
  async read(id) {
10
- const { rows } = await client.query(`SELECT a.owner_id, a.storage_scope_id, a.lifecycle_state, a.is_public, a.terminal_deleted_at, c.release_id
15
+ const { rows } = await client.query(`SELECT a.owner_id, a.storage_scope_id, a.lifecycle_state, a.is_public, a.access_mode, a.terminal_deleted_at, c.release_id
11
16
  FROM artifacts.artifacts a LEFT JOIN artifacts.artifact_current c ON c.artifact_id = a.id WHERE a.id = $1`, [id]);
12
17
  const row = rows[0];
13
18
  if (!row)
14
19
  return undefined;
20
+ // G1: access_mode is authoritative; is_public is its legacy projection.
21
+ const accessMode = (row.access_mode ?? (row.is_public ? 'platform' : 'restricted'));
15
22
  const acl = { ownerId: row.owner_id, storageScopeId: row.storage_scope_id,
16
- isPublic: row.is_public, withdrawn: row.lifecycle_state === 'withdrawn', grants: [] };
23
+ isPublic: accessMode !== 'restricted', accessMode, withdrawn: row.lifecycle_state === 'withdrawn', grants: [] };
17
24
  return { acl, state: row.lifecycle_state, terminal: row.terminal_deleted_at !== null,
18
25
  currentReleaseId: row.release_id };
19
26
  },
20
27
  async setAccess(id, principalId, action, updatedAt) {
28
+ const modeRow = await client.query('SELECT access_mode, is_public FROM artifacts.artifacts WHERE id = $1', [id]);
29
+ const current = (modeRow.rows[0] === undefined ? 'restricted'
30
+ : (modeRow.rows[0].access_mode ?? (modeRow.rows[0].is_public ? 'platform' : 'restricted')));
31
+ if (principalId === PLATFORM_PRINCIPAL || principalId === PUBLIC_PRINCIPAL) {
32
+ // Wide-audience sentinels move the mode through the normative transitions;
33
+ // is_public follows as projection (never forced to false).
34
+ const transition = applyModeTransition(current, action, principalId);
35
+ if (transition.changed) {
36
+ await client.query(`UPDATE artifacts.artifacts SET access_mode = $2, is_public = ($2 <> 'restricted'), updated_at = $3 WHERE id = $1`, [id, transition.mode, updatedAt]);
37
+ }
38
+ return { grants: await listGrants(id), updatedAt, accessMode: transition.mode, changed: transition.changed };
39
+ }
21
40
  const changed = action === 'grant' ? await client.query(`INSERT INTO artifacts.artifact_access (artifact_id, principal_id, permission) VALUES ($1, $2, 'read')
22
41
  ON CONFLICT (artifact_id, principal_id) DO NOTHING`, [id, principalId])
23
42
  : await client.query('DELETE FROM artifacts.artifact_access WHERE artifact_id = $1 AND principal_id = $2', [id, principalId]);
24
- await client.query(`UPDATE artifacts.artifacts SET is_public = false, updated_at = $2
25
- WHERE id = $1 AND ($3::boolean OR is_public)`, [id, updatedAt, changed.rowCount > 0]);
26
- const result = await client.query('SELECT principal_id, permission FROM artifacts.artifact_access WHERE artifact_id = $1 ORDER BY principal_id', [id]);
43
+ if (changed.rowCount > 0) {
44
+ await client.query('UPDATE artifacts.artifacts SET updated_at = $2 WHERE id = $1', [id, updatedAt]);
45
+ }
27
46
  const stamp = await client.query('SELECT updated_at FROM artifacts.artifacts WHERE id = $1', [id]);
28
- return { grants: result.rows.map((row) => ({ principalId: row.principal_id, grant: row.permission })),
29
- updatedAt: stamp.rows[0]?.updated_at?.toISOString() ?? null };
47
+ return { grants: await listGrants(id), updatedAt: stamp.rows[0]?.updated_at?.toISOString() ?? null,
48
+ accessMode: current, changed: changed.rowCount > 0 };
49
+ },
50
+ async recordEvent(event) {
51
+ await client.query(`INSERT INTO artifacts.artifact_access_events (artifact_id, actor_id, action, audience, principal_id, policy_revision)
52
+ VALUES ($1, $2, $3, $4, $5, $6)`, [event.artifactId, event.actorId, event.action, event.audience, event.principalId, event.policyRevision]);
30
53
  },
31
54
  async delete(id, deletedAt) {
32
55
  await client.query(`UPDATE artifacts.artifacts SET lifecycle_state = 'deleted', terminal_deleted_at = $2,
33
- updated_at = $2, is_public = false WHERE id = $1`, [id, deletedAt]);
56
+ updated_at = $2 WHERE id = $1`, [id, deletedAt]);
34
57
  },
35
58
  };
36
59
  }
@@ -196,7 +196,7 @@ export function createPostgresArtifactStore(pool) {
196
196
  return rows.map((row) => row.digest);
197
197
  },
198
198
  async getArtifactAcl(artifactId) {
199
- const { rows } = await pool.query(`SELECT owner_id, storage_scope_id, is_public, lifecycle_state, binding_name, created_at,
199
+ const { rows } = await pool.query(`SELECT owner_id, storage_scope_id, is_public, access_mode, lifecycle_state, binding_name, created_at,
200
200
  to_jsonb(a)->>'updated_at' AS updated_at, to_jsonb(a)->'metadata' AS metadata
201
201
  FROM artifacts.artifacts a WHERE id = $1`, [artifactId]);
202
202
  const row = rows[0];
@@ -204,12 +204,15 @@ export function createPostgresArtifactStore(pool) {
204
204
  return undefined;
205
205
  const grants = await pool.query(`SELECT principal_id, permission FROM artifacts.artifact_access
206
206
  WHERE artifact_id = $1 ORDER BY principal_id`, [artifactId]);
207
+ // G1: access_mode is authoritative; is_public is its legacy projection.
208
+ const accessMode = (row.access_mode ?? (row.is_public ? 'platform' : 'restricted'));
207
209
  return {
208
210
  bindingName: row.binding_name, createdAt: row.created_at.toISOString(), updatedAt: row.updated_at,
209
211
  ...(row.metadata ?? {}),
210
212
  ownerId: row.owner_id,
211
213
  storageScopeId: row.storage_scope_id,
212
- isPublic: row.is_public,
214
+ isPublic: accessMode !== 'restricted',
215
+ accessMode,
213
216
  withdrawn: row.lifecycle_state === 'withdrawn',
214
217
  grants: grants.rows.map((grant) => ({
215
218
  principalId: grant.principal_id,
@@ -219,17 +222,25 @@ export function createPostgresArtifactStore(pool) {
219
222
  };
220
223
  },
221
224
  async putArtifactAcl(artifactId, acl) {
222
- await pool.query(`UPDATE artifacts.artifacts SET is_public = $2, metadata = $4,
225
+ // G1: write access_mode; is_public stays as its projection (never forced false).
226
+ const accessMode = acl.accessMode ?? (acl.isPublic ? 'platform' : 'restricted');
227
+ await pool.query(`UPDATE artifacts.artifacts SET access_mode = $2, is_public = ($2 <> 'restricted'), metadata = $4,
223
228
  lifecycle_state = CASE WHEN $3 THEN 'withdrawn'
224
229
  WHEN lifecycle_state = 'withdrawn' THEN 'active'
225
230
  ELSE lifecycle_state END
226
- WHERE id = $1`, [artifactId, acl.isPublic, acl.withdrawn, JSON.stringify(acl.metadata ?? {})]);
231
+ WHERE id = $1`, [artifactId, accessMode, acl.withdrawn, JSON.stringify(acl.metadata ?? {})]);
227
232
  await pool.query(`DELETE FROM artifacts.artifact_access WHERE artifact_id = $1`, [
228
233
  artifactId,
229
234
  ]);
230
235
  for (const grant of acl.grants) {
236
+ // Q1 schema invariant: a source grant exists only in restricted mode. A
237
+ // legacy platform/public artifact (migrated by 0006 from is_public=true)
238
+ // may still carry one; rewriting its ACL (e.g. withdraw) must not trip
239
+ // the source guard on re-insert, so the stale source grant is demoted
240
+ // to read — the grant row is kept, never dropped.
241
+ const permission = grant.grant === 'source' && accessMode !== 'restricted' ? 'read' : grant.grant;
231
242
  await pool.query(`INSERT INTO artifacts.artifact_access (artifact_id, principal_id, permission)
232
- VALUES ($1, $2, $3)`, [artifactId, grant.principalId, grant.grant]);
243
+ VALUES ($1, $2, $3)`, [artifactId, grant.principalId, permission]);
233
244
  }
234
245
  },
235
246
  async listArtifactIds() {
@@ -1,5 +1,6 @@
1
1
  import type { AclStore } from '../server/access.js';
2
2
  import type { LifecycleService } from '../server/lifecycle.js';
3
+ import { type SharingPolicyPort } from '../server/ports.js';
3
4
  import type { PublicationBlobStore, PublicationService } from '../server/publication.js';
4
5
  import { type GrantSigner, type TicketService } from './grants.js';
5
6
  export interface ContentRequest {
@@ -25,7 +26,11 @@ export interface ContentHandlerDeps {
25
26
  grants: GrantSigner;
26
27
  tickets: TicketService;
27
28
  baseDomain: string;
28
- isApprovedAccount?: (principalId: string) => boolean;
29
+ isApprovedAccount?: (principalId: string) => boolean | Promise<boolean>;
30
+ /** G1 lock 2 (runtime): sharing policy per scope, fail-closed when absent. */
31
+ sharingPolicy?: SharingPolicyPort;
32
+ /** G1 lock 1 (deployment capability), absent ⇒ closed. */
33
+ allowPublicSharing?: boolean;
29
34
  assetCacheSeconds?: number;
30
35
  }
31
36
  /** Create the content handler over injected host ports (no server). */
@@ -14,6 +14,7 @@
14
14
  * Unknown/unreadable → same 404; bad grants → 401.
15
15
  */
16
16
  import { errorBody } from '../http.js';
17
+ import { combineSharingPolicy, resolveSharingPolicy } from '../server/ports.js';
17
18
  import { CONTENT_GRANT_TTL_SECONDS } from './grants.js';
18
19
  import { contentHeaders, grantCookie, parseGrantCookie } from './headers.js';
19
20
  import { isServiceWorkerPath, parseContentHost, resolveContentPath } from './routing.js';
@@ -29,13 +30,17 @@ function fail(status) {
29
30
  }
30
31
  /** Create the content handler over injected host ports (no server). */
31
32
  export function createContentHandler(deps) {
32
- const isApproved = deps.isApprovedAccount ?? (() => false);
33
33
  async function canReadNow(artifactId, subjectId) {
34
34
  const acl = await deps.acls.getArtifactAcl(artifactId);
35
35
  if (acl === undefined)
36
36
  return false;
37
37
  const state = await deps.lifecycle.stateOf(artifactId);
38
- return deps.lifecycle.canRead({ artifactId, state }, acl, subjectId, 'read', isApproved);
38
+ // G1 double lock, fail-closed: public mode serves anonymous reads only
39
+ // when the profile capability AND the live runtime policy both allow it.
40
+ const policy = acl.storageScopeId === undefined ? undefined : combineSharingPolicy(deps.allowPublicSharing, await resolveSharingPolicy(deps.sharingPolicy, acl.storageScopeId));
41
+ // G1 owner Q2: fresh account approval at every read; the host predicate may be async (live DB check).
42
+ const approved = (await deps.isApprovedAccount?.(subjectId)) ?? false;
43
+ return deps.lifecycle.canRead({ artifactId, state }, acl, subjectId, 'read', () => approved, policy);
39
44
  }
40
45
  async function serveFile(artifactId, manifest, filePath) {
41
46
  const acl = await deps.acls.getArtifactAcl(artifactId);
package/dist/http.d.ts CHANGED
@@ -1,7 +1,7 @@
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 } from './server/ports.js';
4
+ import { type KvPort, type SharingPolicyPort } from './server/ports.js';
5
5
  import { type GuardedPublicationDeps, type PublicationService } from './server/publication.js';
6
6
  import type { AclStore } from './server/access.js';
7
7
  import type { LifecycleService } from './server/lifecycle.js';
@@ -51,6 +51,10 @@ export interface HttpAppDeps {
51
51
  acls: AclStore;
52
52
  lifecycle: Pick<LifecycleService, 'stateOf' | 'canRead' | 'getReleaseState'>;
53
53
  isApprovedAccount?: (principalId: string) => boolean;
54
+ /** G1 lock 2 (runtime, revocable): sharing policy per scope, resolved fail-closed. */
55
+ sharingPolicy?: SharingPolicyPort;
56
+ /** G1: server-resolved platform admin predicate (never a tool argument). */
57
+ actorIsAdmin?: (actorId: string, storageScopeId: string) => boolean | Promise<boolean>;
54
58
  /** One trusted URL policy shared by HTTP and MCP receipts: the artifact page and the exact version page. */
55
59
  publicationUrls?: (artifactId: string, releaseId: string) => {
56
60
  stableUrl: string;
package/dist/http.js CHANGED
@@ -5,6 +5,7 @@ import { assertCompiledArtifactsProfile, ArtifactProfileInputError } from './pro
5
5
  import { createArtifactCommand } from './server/command-identity.js';
6
6
  import { createGuardedEnsureService } from './server/service.js';
7
7
  import { assertArtifactReplayMigration } from './server/idempotency.js';
8
+ import { combineSharingPolicy, resolveSharingPolicy } from './server/ports.js';
8
9
  import { createGuardedPublicationService } from './server/publication.js';
9
10
  import { applyEdits } from './server/edits.js';
10
11
  import { CommitQuarantineError } from './server/commit/types.js';
@@ -70,6 +71,10 @@ export function createHttpArtifactApp(deps) {
70
71
  return receipt;
71
72
  },
72
73
  } });
74
+ /** G1 double lock: profile capability (lock 1) AND runtime port (lock 2), fail-closed. */
75
+ async function sharingPolicyContext(storageScopeId) {
76
+ return combineSharingPolicy(profile.rules.allowPublicSharing, await resolveSharingPolicy(deps.sharingPolicy, storageScopeId));
77
+ }
73
78
  async function visible(artifactId, invocation, action = 'read') {
74
79
  const acl = await deps.acls.getArtifactAcl(artifactId);
75
80
  if (!acl || acl.storageScopeId !== invocation.storageScopeId)
@@ -81,11 +86,39 @@ export function createHttpArtifactApp(deps) {
81
86
  return acl;
82
87
  throw new ArtifactOperationError('gone');
83
88
  }
84
- if (!deps.lifecycle.canRead({ artifactId, state }, acl, invocation.actorId, action === true ? 'read' : action, deps.isApprovedAccount)) {
89
+ const policy = await sharingPolicyContext(invocation.storageScopeId);
90
+ if (!deps.lifecycle.canRead({ artifactId, state }, acl, invocation.actorId, action === true ? 'read' : action, deps.isApprovedAccount, policy)) {
85
91
  throw new ArtifactOperationError('not_found');
86
92
  }
87
93
  return acl;
88
94
  }
95
+ /**
96
+ * G1 management visibility for `set_access` (converged-r2 §2.3 order (2)):
97
+ * readers pass as before; any other actor gets `not_found` unless it is an
98
+ * APPROVED platform admin of the SAME storageScopeId. The predicate is
99
+ * evaluated per call — never inferred from merely being wired — so a
100
+ * non-reader non-admin cannot distinguish an existing artifact (403) from a
101
+ * missing one (404): the existence oracle is closed. The management right
102
+ * itself (owner, or admin-reduce-only) is decided inside the transaction by
103
+ * `canManageAccess` (403 otherwise). The exception never makes the admin a
104
+ * content reader.
105
+ */
106
+ async function visibleForManagement(artifactId, invocation) {
107
+ const acl = await deps.acls.getArtifactAcl(artifactId);
108
+ if (!acl || acl.storageScopeId !== invocation.storageScopeId)
109
+ throw new ArtifactOperationError('not_found');
110
+ const state = await deps.lifecycle.stateOf(artifactId);
111
+ if (acl.ownerId === invocation.actorId && (state === 'deleted' || state === 'purged'))
112
+ return acl;
113
+ const policy = await sharingPolicyContext(invocation.storageScopeId);
114
+ if (deps.lifecycle.canRead({ artifactId, state }, acl, invocation.actorId, 'read', deps.isApprovedAccount, policy)) {
115
+ return acl;
116
+ }
117
+ if (await deps.actorIsAdmin?.(invocation.actorId, invocation.storageScopeId) === true &&
118
+ deps.isApprovedAccount?.(invocation.actorId) === true)
119
+ return acl;
120
+ throw new ArtifactOperationError('not_found');
121
+ }
89
122
  /** Display metadata fields present on validated args (ensure/publish). */
90
123
  function metadataOf(normalized) {
91
124
  const meta = {};
@@ -258,7 +291,8 @@ export function createHttpArtifactApp(deps) {
258
291
  const acl = await visible(artifactId, invocation);
259
292
  const summary = artifactSummary({ artifactId, acl, actorId: invocation.actorId,
260
293
  state: await deps.lifecycle.stateOf(artifactId), current: await deps.publication.getCurrent(artifactId),
261
- urls: deps.publicationUrls, approved: deps.isApprovedAccount });
294
+ urls: deps.publicationUrls, approved: deps.isApprovedAccount,
295
+ policy: await sharingPolicyContext(invocation.storageScopeId) });
262
296
  return { ...outcome, result: { status: 201, body: profile.resultEnvelopeVersion === 2
263
297
  ? { ...summary, ...outcome.result } : { ...outcome.result, ...acl.metadata } } };
264
298
  }
@@ -269,7 +303,7 @@ export function createHttpArtifactApp(deps) {
269
303
  authorize: async () => {
270
304
  const acl = await visible(artifactId, invocation);
271
305
  const state = await deps.lifecycle.stateOf(artifactId);
272
- if (!deps.lifecycle.canRead({ artifactId, state }, acl, invocation.actorId, 'source', deps.isApprovedAccount)) {
306
+ if (!deps.lifecycle.canRead({ artifactId, state }, acl, invocation.actorId, 'source', deps.isApprovedAccount, await sharingPolicyContext(invocation.storageScopeId))) {
273
307
  throw new ArtifactOperationError('access_denied');
274
308
  }
275
309
  }, getCurrent: deps.publication.getCurrent, getRelease: deps.publication.getRelease,
@@ -280,13 +314,20 @@ export function createHttpArtifactApp(deps) {
280
314
  commitState: 'not_committed', replayed: false };
281
315
  }
282
316
  if (capability === 'artifacts_set_access' || capability === 'artifacts_delete') {
283
- const acl = await visible(normalized.artifactId, invocation, true);
284
- if (acl.ownerId !== invocation.actorId)
317
+ const artifactId = normalized.artifactId;
318
+ const acl = capability === 'artifacts_set_access'
319
+ ? await visibleForManagement(artifactId, invocation)
320
+ : await visible(artifactId, invocation, true);
321
+ if (capability === 'artifacts_delete' && acl.ownerId !== invocation.actorId) {
285
322
  throw new ArtifactOperationError('access_denied');
323
+ }
286
324
  const outcome = await manageArtifact({ coordinator: deps.coordinator,
287
325
  createUnit: deps.management?.createUnit ?? createPostgresManagementUnit,
288
326
  confirmation: deps.management?.confirmation, readPolicyRevision: () => deps.ensureHost.readPolicyRevision(),
289
327
  isApprovedPrincipal: deps.isApprovedAccount ?? (() => false),
328
+ sharingPolicy: deps.sharingPolicy,
329
+ profileAllowPublicSharing: profile.rules.allowPublicSharing,
330
+ actorIsAdmin: deps.actorIsAdmin,
290
331
  validateNewCommand: () => { profile.validate(capability, args, request.idempotencyKey); },
291
332
  }, invocation, command, normalized.confirmationRef);
292
333
  return outcome.ok ? { ...outcome, result: { status: 200, body: outcome.result } } : outcome;
@@ -355,7 +396,8 @@ export function createHttpArtifactApp(deps) {
355
396
  const current = await deps.publication.getCurrent(artifactId);
356
397
  return { ok: true, invocationId: invocation.invocationId, commitState: 'not_committed', replayed: false,
357
398
  result: { status: 200, body: { ...artifactSummary({ artifactId, acl, state, current,
358
- actorId: invocation.actorId, urls: deps.publicationUrls, approved: deps.isApprovedAccount }),
399
+ actorId: invocation.actorId, urls: deps.publicationUrls, approved: deps.isApprovedAccount,
400
+ policy: await sharingPolicyContext(invocation.storageScopeId) }),
359
401
  ...(acl.metadata !== undefined ? { metadata: acl.metadata } : {}),
360
402
  ...(acl.ownerId === invocation.actorId ? { grants: acl.grants } : {}) } } };
361
403
  }
@@ -385,14 +427,16 @@ export function createHttpArtifactApp(deps) {
385
427
  result: { status: 200, body: { artifactId, total: releases.length, releases } } };
386
428
  }
387
429
  const visibleArtifacts = [];
430
+ const listPolicy = await sharingPolicyContext(invocation.storageScopeId);
388
431
  for (const artifactId of await deps.acls.listArtifactIds()) {
389
432
  const acl = await deps.acls.getArtifactAcl(artifactId);
390
433
  if (!acl || acl.storageScopeId !== invocation.storageScopeId)
391
434
  continue;
392
435
  const state = await deps.lifecycle.stateOf(artifactId);
393
- if (deps.lifecycle.canRead({ artifactId, state }, acl, invocation.actorId, 'read', deps.isApprovedAccount)) {
436
+ if (deps.lifecycle.canRead({ artifactId, state }, acl, invocation.actorId, 'read', deps.isApprovedAccount, listPolicy)) {
394
437
  visibleArtifacts.push(artifactSummary({ artifactId, acl, state, actorId: invocation.actorId,
395
- current: await deps.publication.getCurrent(artifactId), urls: deps.publicationUrls, approved: deps.isApprovedAccount }));
438
+ current: await deps.publication.getCurrent(artifactId), urls: deps.publicationUrls,
439
+ approved: deps.isApprovedAccount, policy: listPolicy }));
396
440
  }
397
441
  }
398
442
  const offset = normalized.offset;
@@ -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.9";
13
+ export declare const ARTIFACTS_PROVIDER_VERSION = "0.2.10";
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"];
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.9';
9
+ export const ARTIFACTS_PROVIDER_VERSION = '0.2.10';
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,8 @@ export interface ArtifactProfileRules {
20
20
  readonly forbiddenPathPattern: string;
21
21
  readonly reservedFirstSegments: readonly string[];
22
22
  readonly mimeTypes: readonly string[];
23
+ /** G1 lock 1 (deployment): allow the `public` sharing mode; absent ⇒ closed. */
24
+ readonly allowPublicSharing?: boolean;
23
25
  }
24
26
  export interface ArtifactProviderProfile {
25
27
  /** Trusted public contract revision; independent from the host policy revision. */
@@ -66,9 +66,11 @@ export function compileArtifactsProfile(input) {
66
66
  }
67
67
  const rules = profile.rules;
68
68
  const ruleKeys = ['lengthUnit', 'textEncoding', 'callerKeyNormalization', 'rejectLoneSurrogates',
69
- 'provenance', 'keyDerivationAlgorithm', 'pathMaxBytes', 'forbiddenPathPattern', 'reservedFirstSegments', 'mimeTypes'];
69
+ 'provenance', 'keyDerivationAlgorithm', 'pathMaxBytes', 'forbiddenPathPattern', 'reservedFirstSegments', 'mimeTypes',
70
+ 'allowPublicSharing'];
70
71
  if (!rules || rules.lengthUnit !== 'utf16' || rules.textEncoding !== 'utf8' || rules.callerKeyNormalization !== 'none' ||
71
72
  Object.keys(rules).some((key) => !ruleKeys.includes(key)) ||
73
+ (rules.allowPublicSharing !== undefined && typeof rules.allowPublicSharing !== 'boolean') ||
72
74
  rules.rejectLoneSurrogates !== true || rules.provenance !== 'inline-original' ||
73
75
  typeof rules.keyDerivationAlgorithm !== 'string' || !rules.keyDerivationAlgorithm ||
74
76
  !Number.isSafeInteger(rules.pathMaxBytes) || rules.pathMaxBytes < 1 || rules.pathMaxBytes > 1024 ||
@@ -1,16 +1,46 @@
1
1
  /**
2
- * L-5c — access control (spec-v8 §9 5c).
2
+ * L-5c/G1 — access control (spec-v8 §9 5c, converged-r2 §2.1 + owner answers).
3
3
  *
4
- * Pure evaluation over an artifact ACL: the owner reads, exports source and
5
- * manages grants; explicit grants give read or source (source implies read,
6
- * read never implies source); a public flag opens reads to approved accounts
7
- * only — never anonymous, never source. Withdrawal suspends reader grants
8
- * (kept for audit, inactive) while the owner keeps access. Grant management
9
- * is owner-only; duplicate grants are refused. Identity approval comes from
10
- * the host via an injected predicate (memory double in tests).
4
+ * Three-mode sharing model. `restricted` (default): owner + nominative grants.
5
+ * `platform`: every approved account of the scope reads, never anonymous,
6
+ * never source. `public`: anonymous read only while the sharing policy allows
7
+ * it (§2.2 double lock, fail-closed). The legacy `isPublic` flag maps to
8
+ * `platform`, never `public`. Nominative grants coexist orthogonally with the
9
+ * wide mode. Owner Q1: the collab (`source`) right is nominative only — one
10
+ * named colleague, restricted mode only, never a `sentropic:` sentinel; the
11
+ * schema mirrors this. Owner Q2: grants and platform reads require fresh
12
+ * approval at every read — a paused share resumes automatically once the
13
+ * account is approved again and reports `blockedBy:'account_inactive'`
14
+ * meanwhile; the grant row is kept, never deleted. Owner Q3: the ACL is per
15
+ * artifact, so a share covers all retained versions (no version-scoped state
16
+ * exists here). Withdrawal suspends reader grants (kept for audit, inactive)
17
+ * while the owner keeps access. Grant management is owner-only (duplicates
18
+ * refused); `canManageAccess` adds the server-resolved platform admin, which
19
+ * may revoke and degrade only — never widen, never place a nominative grant.
11
20
  */
12
21
  export type AccessGrant = 'read' | 'source';
13
22
  export type AccessAction = 'read' | 'source';
23
+ export type AccessMode = 'restricted' | 'platform' | 'public';
24
+ export type AccessAudience = 'user' | 'platform' | 'public';
25
+ export type ModeAction = 'grant' | 'revoke';
26
+ /** Reserved principal namespace: wide-audience sentinels, never nominative. */
27
+ export declare const RESERVED_PRINCIPAL_PREFIX = "sentropic:";
28
+ export declare const PLATFORM_PRINCIPAL = "sentropic:platform";
29
+ export declare const PUBLIC_PRINCIPAL = "sentropic:public";
30
+ /** Live sharing policy context (fail-closed when absent). */
31
+ export interface SharingPolicyContext {
32
+ allowPublicSharing?: boolean;
33
+ }
34
+ /** Append-only audit event recorded in the same transaction as the mutation. */
35
+ export interface AccessEvent {
36
+ artifactId: string;
37
+ actorId: string;
38
+ action: ModeAction;
39
+ audience: AccessAudience;
40
+ /** Target principal for user audience, null for the wide audiences. */
41
+ principalId: string | null;
42
+ policyRevision: string;
43
+ }
14
44
  export interface GrantRecord {
15
45
  principalId: string;
16
46
  grant: AccessGrant;
@@ -34,6 +64,8 @@ export interface ArtifactAcl {
34
64
  isPublic: boolean;
35
65
  withdrawn: boolean;
36
66
  grants: GrantRecord[];
67
+ /** Wide sharing mode; absent on legacy ACLs, which read as platform when isPublic. */
68
+ accessMode?: AccessMode;
37
69
  /** Display metadata returned by get/list; persisted by the host store. */
38
70
  metadata?: ArtifactMetadata;
39
71
  }
@@ -45,9 +77,37 @@ export interface AclStore {
45
77
  }
46
78
  /** In-memory AclStore double for unit tests. */
47
79
  export declare function createMemoryAclStore(): AclStore;
80
+ /** Effective wide mode; the legacy isPublic flag reads as platform, never public. */
81
+ export declare function accessModeOf(acl: ArtifactAcl): AccessMode;
48
82
  /** True when the actor may perform the action (deny by default). */
49
- export declare function evaluateAccess(acl: ArtifactAcl, actorId: string, action: AccessAction, isApproved?: (principalId: string) => boolean): boolean;
50
- /** Owner-only: add a grant (duplicates refused). */
83
+ export declare function evaluateAccess(acl: ArtifactAcl, actorId: string, action: AccessAction, isApproved?: (principalId: string) => boolean, policy?: SharingPolicyContext): boolean;
84
+ /** Dormancy report for one nominative grant (owner Q2 paused display). */
85
+ export declare function evaluateGrant(acl: ArtifactAcl, principalId: string, isApproved?: (principalId: string) => boolean): {
86
+ effective: boolean;
87
+ blockedBy?: 'account_inactive';
88
+ };
89
+ /** Owner-only: add a grant (duplicates refused; owner Q1 enforced in pure form). */
51
90
  export declare function grantAccess(acl: ArtifactAcl, actorId: string, grant: GrantRecord): ArtifactAcl;
52
91
  /** Owner-only: remove a grant (kept for audit by the caller if needed). */
53
92
  export declare function revokeAccess(acl: ArtifactAcl, actorId: string, principalId: string): ArtifactAcl;
93
+ /** Normative mode transitions (converged-r2 §2.1): sentinels only move the wide mode. */
94
+ export declare function applyModeTransition(mode: AccessMode, action: ModeAction, principalId: string): {
95
+ mode: AccessMode;
96
+ changed: boolean;
97
+ };
98
+ /** Audience class of a principal: the two sentinels are wide, anything else is a user. */
99
+ export declare function audienceOf(principalId: string): AccessAudience;
100
+ /**
101
+ * Management right over one (action, principal) pair. The owner manages every
102
+ * audience; the platform admin — a server-resolved flag only, never a tool
103
+ * argument — may revoke any grant and degrade modes, including the unique
104
+ * `grant sentropic:platform` on a `public` artifact (a strict reduction). The
105
+ * admin never widens a mode and never places a nominative grant.
106
+ */
107
+ export declare function canManageAccess(args: {
108
+ acl: ArtifactAcl;
109
+ actorId: string;
110
+ action: ModeAction;
111
+ principalId: string;
112
+ actorIsAdmin?: boolean;
113
+ }): boolean;
@@ -1,3 +1,7 @@
1
+ /** Reserved principal namespace: wide-audience sentinels, never nominative. */
2
+ export const RESERVED_PRINCIPAL_PREFIX = 'sentropic:';
3
+ export const PLATFORM_PRINCIPAL = 'sentropic:platform';
4
+ export const PUBLIC_PRINCIPAL = 'sentropic:public';
1
5
  /** In-memory AclStore double for unit tests. */
2
6
  export function createMemoryAclStore() {
3
7
  const acls = new Map();
@@ -17,32 +21,65 @@ export function createMemoryAclStore() {
17
21
  },
18
22
  };
19
23
  }
24
+ /** Effective wide mode; the legacy isPublic flag reads as platform, never public. */
25
+ export function accessModeOf(acl) {
26
+ return acl.accessMode ?? (acl.isPublic ? 'platform' : 'restricted');
27
+ }
20
28
  /** True when the actor may perform the action (deny by default). */
21
- export function evaluateAccess(acl, actorId, action, isApproved = () => false) {
22
- if (actorId.length === 0)
23
- return false;
29
+ export function evaluateAccess(acl, actorId, action, isApproved = () => false, policy = {}) {
24
30
  if (actorId === acl.ownerId)
25
31
  return true;
26
32
  if (acl.withdrawn)
27
33
  return false;
34
+ const mode = accessModeOf(acl);
35
+ if (actorId.length === 0) {
36
+ // Anonymous: public mode read only, and only while the policy allows it.
37
+ return mode === 'public' && action === 'read' && policy.allowPublicSharing === true;
38
+ }
28
39
  const grant = acl.grants.find((g) => g.principalId === actorId)?.grant;
40
+ // Fresh approval at every read (owner Q2): suspension pauses, reactivation resumes.
29
41
  if (grant === 'source')
30
- return true;
42
+ return isApproved(actorId);
31
43
  if (grant === 'read' && action === 'read')
32
- return true;
33
- if (action === 'read' && acl.isPublic && isApproved(actorId))
34
- return true;
44
+ return isApproved(actorId);
45
+ if (action === 'read') {
46
+ if (mode === 'platform')
47
+ return isApproved(actorId);
48
+ if (mode === 'public')
49
+ return policy.allowPublicSharing === true;
50
+ }
35
51
  return false;
36
52
  }
37
- /** Owner-only: add a grant (duplicates refused). */
53
+ /** Dormancy report for one nominative grant (owner Q2 paused display). */
54
+ export function evaluateGrant(acl, principalId, isApproved = () => false) {
55
+ const grant = acl.grants.find((g) => g.principalId === principalId);
56
+ if (grant === undefined)
57
+ return { effective: false };
58
+ if (!isApproved(principalId))
59
+ return { effective: false, blockedBy: 'account_inactive' };
60
+ return { effective: true };
61
+ }
62
+ /** Owner-only: add a grant (duplicates refused; owner Q1 enforced in pure form). */
38
63
  export function grantAccess(acl, actorId, grant) {
39
64
  if (actorId !== acl.ownerId)
40
65
  throw new Error('access denied: only the owner manages grants');
41
66
  if (grant.principalId.length === 0)
42
67
  throw new Error('invalid grant: empty principal');
68
+ if (grant.principalId.startsWith(RESERVED_PRINCIPAL_PREFIX)) {
69
+ throw new Error(`reserved principal prefix: ${grant.principalId}`);
70
+ }
43
71
  if (acl.grants.some((g) => g.principalId === grant.principalId)) {
44
72
  throw new Error(`duplicate grant for ${grant.principalId}`);
45
73
  }
74
+ if (grant.grant === 'source') {
75
+ // Owner Q1: collab is one named colleague, restricted mode only — never
76
+ // platform-wide, never public (the schema enforces the same invariant).
77
+ if (accessModeOf(acl) !== 'restricted')
78
+ throw new Error('source grant requires restricted mode');
79
+ if (acl.grants.some((g) => g.grant === 'source')) {
80
+ throw new Error('source grant is limited to one named colleague');
81
+ }
82
+ }
46
83
  return { ...acl, grants: [...acl.grants, grant] };
47
84
  }
48
85
  /** Owner-only: remove a grant (kept for audit by the caller if needed). */
@@ -51,3 +88,49 @@ export function revokeAccess(acl, actorId, principalId) {
51
88
  throw new Error('access denied: only the owner manages grants');
52
89
  return { ...acl, grants: acl.grants.filter((g) => g.principalId !== principalId) };
53
90
  }
91
+ /** Normative mode transitions (converged-r2 §2.1): sentinels only move the wide mode. */
92
+ export function applyModeTransition(mode, action, principalId) {
93
+ if (principalId === PLATFORM_PRINCIPAL) {
94
+ if (action === 'grant')
95
+ return { mode: 'platform', changed: mode !== 'platform' };
96
+ return mode === 'platform' ? { mode: 'restricted', changed: true } : { mode, changed: false };
97
+ }
98
+ if (principalId === PUBLIC_PRINCIPAL) {
99
+ if (action === 'grant')
100
+ return { mode: 'public', changed: mode !== 'public' };
101
+ return mode === 'public' ? { mode: 'restricted', changed: true } : { mode, changed: false };
102
+ }
103
+ // Nominative principals never change the wide mode.
104
+ return { mode, changed: false };
105
+ }
106
+ /** Audience class of a principal: the two sentinels are wide, anything else is a user. */
107
+ export function audienceOf(principalId) {
108
+ if (principalId === PLATFORM_PRINCIPAL)
109
+ return 'platform';
110
+ if (principalId === PUBLIC_PRINCIPAL)
111
+ return 'public';
112
+ return 'user';
113
+ }
114
+ function isManageablePrincipal(principalId) {
115
+ return principalId === PLATFORM_PRINCIPAL || principalId === PUBLIC_PRINCIPAL ||
116
+ !principalId.startsWith(RESERVED_PRINCIPAL_PREFIX);
117
+ }
118
+ /**
119
+ * Management right over one (action, principal) pair. The owner manages every
120
+ * audience; the platform admin — a server-resolved flag only, never a tool
121
+ * argument — may revoke any grant and degrade modes, including the unique
122
+ * `grant sentropic:platform` on a `public` artifact (a strict reduction). The
123
+ * admin never widens a mode and never places a nominative grant.
124
+ */
125
+ export function canManageAccess(args) {
126
+ const { acl, actorId, action, principalId } = args;
127
+ if (!isManageablePrincipal(principalId))
128
+ return false;
129
+ if (actorId === acl.ownerId)
130
+ return true;
131
+ if (args.actorIsAdmin !== true)
132
+ return false;
133
+ if (action === 'revoke')
134
+ return true;
135
+ return action === 'grant' && principalId === PLATFORM_PRINCIPAL && accessModeOf(acl) === 'public';
136
+ }
@@ -1,4 +1,4 @@
1
- import { type AccessAction, type ArtifactAcl } from './access.js';
1
+ import { type AccessAction, type ArtifactAcl, type SharingPolicyContext } from './access.js';
2
2
  import type { DeletionClaimStore } from './gc.js';
3
3
  import type { PublicationStateStore } from './publication.js';
4
4
  /**
@@ -36,7 +36,7 @@ export interface LifecycleService {
36
36
  canRead(artifact: {
37
37
  artifactId: string;
38
38
  state: ArtifactState;
39
- }, acl: ArtifactAcl, actorId: string, action?: AccessAction, isApproved?: (principalId: string) => boolean): boolean;
39
+ }, acl: ArtifactAcl, actorId: string, action?: AccessAction, isApproved?: (principalId: string) => boolean, policy?: SharingPolicyContext): boolean;
40
40
  withdraw(artifactId: string, actorId: string): Promise<void>;
41
41
  restore(artifactId: string, actorId: string): Promise<void>;
42
42
  deleteArtifact(artifactId: string, actorId: string): Promise<void>;
@@ -101,12 +101,12 @@ export function createLifecycleService(store, clock = () => new Date().toISOStri
101
101
  async getReleaseState(releaseId) {
102
102
  return store.getReleaseState(releaseId);
103
103
  },
104
- canRead(artifact, acl, actorId, action = 'read', isApproved = () => false) {
104
+ canRead(artifact, acl, actorId, action = 'read', isApproved = () => false, policy = {}) {
105
105
  if (artifact.state === 'deleted' || artifact.state === 'purged')
106
106
  return false;
107
107
  if (artifact.state === 'withdrawn')
108
108
  return actorId === acl.ownerId;
109
- return evaluateAccess(acl, actorId, action, isApproved);
109
+ return evaluateAccess(acl, actorId, action, isApproved, policy);
110
110
  },
111
111
  async withdraw(artifactId, actorId) {
112
112
  await assertOwner(artifactId, actorId);
@@ -1,4 +1,5 @@
1
- import type { ArtifactAcl } from './access.js';
1
+ import { type AccessEvent, type AccessMode, type ArtifactAcl, type GrantRecord } from './access.js';
2
+ import { type SharingPolicyPort } from './ports.js';
2
3
  import type { ArtifactInvocationContext, ArtifactCommitCoordinator, FinalizeTxClient } from './commit/types.js';
3
4
  import type { EffectiveArtifactCommand } from './command-identity.js';
4
5
  import { ArtifactOperationError, type ArtifactOutcome } from './failures.js';
@@ -8,13 +9,18 @@ export interface ManagementTarget {
8
9
  terminal: boolean;
9
10
  currentReleaseId: string | null;
10
11
  }
12
+ export interface SetAccessOutput {
13
+ grants: GrantRecord[];
14
+ updatedAt: string | null;
15
+ accessMode: AccessMode;
16
+ changed: boolean;
17
+ }
11
18
  export interface ManagementUnit {
12
19
  lock(artifactId: string): Promise<void>;
13
20
  read(artifactId: string): Promise<ManagementTarget | undefined>;
14
- setAccess(artifactId: string, principalId: string, action: 'grant' | 'revoke', updatedAt: string): Promise<{
15
- grants: unknown;
16
- updatedAt: string | null;
17
- }>;
21
+ setAccess(artifactId: string, principalId: string, action: 'grant' | 'revoke', updatedAt: string): Promise<SetAccessOutput>;
22
+ /** Append-only audit event, written in the same transaction as the mutation. */
23
+ recordEvent(event: AccessEvent): Promise<void>;
18
24
  delete(artifactId: string, deletedAt: string): Promise<void>;
19
25
  }
20
26
  export interface DeleteConfirmationContext {
@@ -43,4 +49,10 @@ export declare function manageArtifact(deps: {
43
49
  isApprovedPrincipal(principalId: string): boolean | Promise<boolean>;
44
50
  confirmation?: ArtifactConfirmationPort;
45
51
  validateNewCommand?(): void;
52
+ /** G1: runtime lock 2 of the sharing double lock, resolved inside the commit transaction. */
53
+ sharingPolicy?: SharingPolicyPort;
54
+ /** G1: profile lock 1 (deployment capability), absent ⇒ closed. */
55
+ profileAllowPublicSharing?: boolean;
56
+ /** G1: server-resolved platform admin predicate (never a tool argument). */
57
+ actorIsAdmin?: (actorId: string, storageScopeId: string) => boolean | Promise<boolean>;
46
58
  }, invocation: ArtifactInvocationContext, command: EffectiveArtifactCommand, proof?: string): Promise<ArtifactOutcome<unknown>>;
@@ -1,3 +1,5 @@
1
+ import { audienceOf, canManageAccess, PUBLIC_PRINCIPAL } from './access.js';
2
+ import { combineSharingPolicy, resolveSharingPolicy } from './ports.js';
1
3
  import { ArtifactOperationError } from './failures.js';
2
4
  export function confirmationFailure(code, details) {
3
5
  return new ArtifactOperationError('unauthorized_at_commit', { publicDetails: details,
@@ -9,23 +11,46 @@ function refused(code) {
9
11
  reason: 'denied', status: code === 'gone' ? 410 : code === 'not_found' ? 404 : 403,
10
12
  publicCode: code, retriable: false } });
11
13
  }
14
+ function policyRefused() {
15
+ return new ArtifactOperationError('unauthorized_at_commit', { refusal: { allowed: false,
16
+ reason: 'denied', status: 403, publicCode: 'public_sharing_disabled', retriable: false } });
17
+ }
12
18
  /** Targeted writes and proof consumption share the existing coordinator receipt transaction. */
13
19
  export async function manageArtifact(deps, invocation, command, proof) {
14
20
  const artifactId = command.payload.artifactId;
15
21
  const deleting = command.operation === 'delete';
22
+ const access = deleting ? undefined : { action: command.payload.action, principalId: command.payload.principalId };
16
23
  let unit;
24
+ let adminResolved;
25
+ const resolveAdmin = async () => {
26
+ if (adminResolved === undefined) {
27
+ adminResolved = (await deps.actorIsAdmin?.(invocation.actorId, invocation.storageScopeId) === true) &&
28
+ (await deps.isApprovedPrincipal(invocation.actorId)) === true;
29
+ }
30
+ return adminResolved;
31
+ };
17
32
  const receipt = {};
18
33
  const context = { actorId: invocation.actorId, storageScopeId: invocation.storageScopeId,
19
34
  artifactId, expectedCurrentReleaseId: command.payload.expectedCurrentReleaseId,
20
35
  commandHash: command.identity.commandHash, internalKey: command.identity.internalKey };
21
- const owned = async () => {
36
+ // §2.3 order: visibility happened in the transport; here the management right
37
+ // (owner, or server-resolved admin reduce-only) gates every mutation.
38
+ const manageable = async () => {
22
39
  const target = await unit.read(artifactId);
23
40
  if (!target || target.acl.storageScopeId !== invocation.storageScopeId)
24
41
  throw refused('not_found');
25
- if (target.acl.ownerId !== invocation.actorId)
42
+ if (deleting) {
43
+ if (target.acl.ownerId !== invocation.actorId)
44
+ throw refused('access_denied');
45
+ return target;
46
+ }
47
+ const actorIsAdmin = await resolveAdmin();
48
+ if (!canManageAccess({ acl: target.acl, actorId: invocation.actorId, action: access.action,
49
+ principalId: access.principalId, actorIsAdmin }))
26
50
  throw refused('access_denied');
27
51
  return target;
28
52
  };
53
+ const sharingPolicy = async () => combineSharingPolicy(deps.profileAllowPublicSharing, await resolveSharingPolicy(deps.sharingPolicy, invocation.storageScopeId));
29
54
  const request = {
30
55
  ...command.identity, scopeId: invocation.storageScopeId, actorId: invocation.actorId,
31
56
  invocationId: invocation.invocationId, operation: command.operation, artifactId,
@@ -33,10 +58,10 @@ export async function manageArtifact(deps, invocation, command, proof) {
33
58
  locks: { 'artifact-lifecycle': [async (client) => {
34
59
  unit = deps.createUnit(client);
35
60
  await unit.lock(artifactId);
36
- await owned();
61
+ await manageable();
37
62
  }] },
38
63
  provisional: async (client) => {
39
- const target = await owned();
64
+ const target = await manageable();
40
65
  if (target.terminal || target.state === 'deleted' || target.state === 'purged')
41
66
  throw refused('gone');
42
67
  const now = new Date().toISOString();
@@ -60,19 +85,34 @@ export async function manageArtifact(deps, invocation, command, proof) {
60
85
  Object.assign(receipt, { artifactId, state: 'deleted', terminal: true, deletedAt: now, purgeState: 'pending' });
61
86
  }
62
87
  else {
63
- const principalId = command.payload.principalId;
64
- if (command.payload.action === 'grant' && !await deps.isApprovedPrincipal(principalId))
88
+ const { action, principalId } = access;
89
+ const audience = audienceOf(principalId);
90
+ if (audience === 'user' && action === 'grant' && !await deps.isApprovedPrincipal(principalId))
65
91
  throw refused('access_denied');
66
- const output = await unit.setAccess(artifactId, principalId, command.payload.action, now);
67
- Object.assign(receipt, { artifactId, isPublic: false, ...output });
92
+ // Double lock (profile capability AND runtime port) resolved in the
93
+ // transaction; the revision rides the receipt/audit, never the commandHash.
94
+ const policy = await sharingPolicy();
95
+ if (action === 'grant' && principalId === PUBLIC_PRINCIPAL && !policy.allowPublicSharing)
96
+ throw policyRefused();
97
+ const output = await unit.setAccess(artifactId, principalId, action, now);
98
+ await unit.recordEvent({ artifactId, actorId: invocation.actorId, action, audience,
99
+ principalId: audience === 'user' ? principalId : null, policyRevision: policy.policyRevision });
100
+ Object.assign(receipt, { artifactId, ...output, policyRevision: policy.policyRevision });
68
101
  }
69
102
  },
70
103
  guard: async (ctx, tx) => {
71
- const target = await owned();
104
+ const target = await manageable();
72
105
  if (!deleting && (target.terminal || target.state === 'deleted' || target.state === 'purged'))
73
106
  throw refused('gone');
74
- if (!deleting && command.payload.action === 'grant' && !await deps.isApprovedPrincipal(command.payload.principalId))
75
- throw refused('access_denied');
107
+ if (!deleting) {
108
+ const { action, principalId } = access;
109
+ const audience = audienceOf(principalId);
110
+ if (audience === 'user' && action === 'grant' && !await deps.isApprovedPrincipal(principalId))
111
+ throw refused('access_denied');
112
+ const policy = await sharingPolicy();
113
+ if (action === 'grant' && principalId === PUBLIC_PRINCIPAL && !policy.allowPublicSharing)
114
+ throw policyRefused();
115
+ }
76
116
  return invocation.authorizeCommit(ctx, tx);
77
117
  },
78
118
  validateReplayReceipt: (stored) => stored.receipt?.artifactId === artifactId,
@@ -26,6 +26,33 @@ export declare function createCryptoUuid(): UuidPort;
26
26
  export interface KeyMutex {
27
27
  runSerialized<T>(key: string, fn: () => Promise<T>): Promise<T>;
28
28
  }
29
+ /**
30
+ * G1 sharing policy port (converged-r2 §2.2, lock 2 of the double lock).
31
+ * Resolved by the host per storage scope, inside the commit transaction and
32
+ * at each anonymous read; never derived from tool arguments. Absent, throwing
33
+ * or malformed answers fail closed.
34
+ */
35
+ export interface SharingPolicyPort {
36
+ getSharingPolicy(scope: string): Promise<{
37
+ allowPublicSharing: boolean;
38
+ policyRevision: string;
39
+ }>;
40
+ }
41
+ export interface SharingPolicy {
42
+ allowPublicSharing: boolean;
43
+ policyRevision: string;
44
+ }
45
+ /** Fail-closed policy used whenever no well-formed answer exists. */
46
+ export declare const CLOSED_SHARING_POLICY: SharingPolicy;
47
+ /** Resolve the runtime lock fail-closed: absent port, throw or malformed answer ⇒ closed. */
48
+ export declare function resolveSharingPolicy(port: SharingPolicyPort | undefined, scope: string): Promise<SharingPolicy>;
49
+ /**
50
+ * Combine both locks of the double lock: the profile capability (lock 1,
51
+ * deployment) AND the runtime port (lock 2, revocable). The public mode is
52
+ * effective only when both allow it; the revision stays the runtime one so
53
+ * receipts and audit events carry it (never hashed into the command).
54
+ */
55
+ export declare function combineSharingPolicy(profileAllows: boolean | undefined, runtime: SharingPolicy): SharingPolicy;
29
56
  /**
30
57
  * In-process per-key mutex: concurrent callers for one key serialize so
31
58
  * exactly one creator wins (single-process scope; multi-process fencing
@@ -21,6 +21,34 @@ export function createCryptoUuid() {
21
21
  },
22
22
  };
23
23
  }
24
+ /** Fail-closed policy used whenever no well-formed answer exists. */
25
+ export const CLOSED_SHARING_POLICY = Object.freeze({ allowPublicSharing: false, policyRevision: 'none' });
26
+ /** Resolve the runtime lock fail-closed: absent port, throw or malformed answer ⇒ closed. */
27
+ export async function resolveSharingPolicy(port, scope) {
28
+ if (port === undefined)
29
+ return CLOSED_SHARING_POLICY;
30
+ try {
31
+ const policy = await port.getSharingPolicy(scope);
32
+ if (typeof policy?.allowPublicSharing !== 'boolean' ||
33
+ typeof policy?.policyRevision !== 'string' || policy.policyRevision.length === 0) {
34
+ return CLOSED_SHARING_POLICY;
35
+ }
36
+ return { allowPublicSharing: policy.allowPublicSharing, policyRevision: policy.policyRevision };
37
+ }
38
+ catch {
39
+ return CLOSED_SHARING_POLICY;
40
+ }
41
+ }
42
+ /**
43
+ * Combine both locks of the double lock: the profile capability (lock 1,
44
+ * deployment) AND the runtime port (lock 2, revocable). The public mode is
45
+ * effective only when both allow it; the revision stays the runtime one so
46
+ * receipts and audit events carry it (never hashed into the command).
47
+ */
48
+ export function combineSharingPolicy(profileAllows, runtime) {
49
+ return { allowPublicSharing: profileAllows === true && runtime.allowPublicSharing,
50
+ policyRevision: runtime.policyRevision };
51
+ }
24
52
  /**
25
53
  * In-process per-key mutex: concurrent callers for one key serialize so
26
54
  * exactly one creator wins (single-process scope; multi-process fencing
@@ -6,20 +6,26 @@
6
6
  * digests outside the current manifest never oracle (404); stored bytes
7
7
  * are checked against the manifest size before serving.
8
8
  */
9
- import type { AclStore } from './access.js';
9
+ import type { AclStore, SharingPolicyContext } from './access.js';
10
10
  import type { LifecycleService } from './lifecycle.js';
11
+ import { type SharingPolicyPort } from './ports.js';
11
12
  import type { PublicationBlobStore, PublicationService } from './publication.js';
12
13
  export interface ContentDeps {
13
14
  acls: AclStore;
14
15
  lifecycle: LifecycleService;
15
16
  publication: PublicationService;
16
17
  blobs: PublicationBlobStore;
18
+ /** G1 lock 2 (runtime): sharing policy per scope, fail-closed when absent. */
19
+ sharingPolicy?: SharingPolicyPort;
20
+ /** G1 lock 1 (deployment capability), absent ⇒ closed. */
21
+ allowPublicSharing?: boolean;
17
22
  }
18
23
  export interface ServeFileInput {
19
24
  artifactId: string;
20
25
  digest: string;
21
26
  actorId: string;
22
27
  isApproved?: (principalId: string) => boolean;
28
+ policy?: SharingPolicyContext;
23
29
  }
24
30
  export interface ServedFile {
25
31
  digest: string;
@@ -1,3 +1,4 @@
1
+ import { combineSharingPolicy, resolveSharingPolicy } from './ports.js';
1
2
  /** Create the content runtime over injected host ports. */
2
3
  export function createContentRuntime(deps) {
3
4
  return {
@@ -13,7 +14,7 @@ export function createContentRuntime(deps) {
13
14
  if (state === 'deleted' || state === 'purged') {
14
15
  throw new Error(`cannot serve ${state} artifact: terminal ${input.artifactId}`);
15
16
  }
16
- const readable = deps.lifecycle.canRead({ artifactId: input.artifactId, state }, acl, input.actorId, 'read', isApproved);
17
+ const readable = deps.lifecycle.canRead({ artifactId: input.artifactId, state }, acl, input.actorId, 'read', isApproved, input.policy ?? combineSharingPolicy(deps.allowPublicSharing, await resolveSharingPolicy(deps.sharingPolicy, acl.storageScopeId)));
17
18
  if (!readable) {
18
19
  throw new Error(`access denied: ${input.actorId} cannot read ${input.artifactId}`);
19
20
  }
@@ -1,4 +1,4 @@
1
- import { type ArtifactAcl } from './access.js';
1
+ import { type ArtifactAcl, type SharingPolicyContext } from './access.js';
2
2
  export declare function artifactSummary(input: {
3
3
  artifactId: string;
4
4
  acl: ArtifactAcl;
@@ -13,6 +13,7 @@ export declare function artifactSummary(input: {
13
13
  versionUrl: string;
14
14
  };
15
15
  approved?: (principalId: string) => boolean;
16
+ policy?: SharingPolicyContext;
16
17
  }): {
17
18
  permissions: {
18
19
  read: boolean;
@@ -13,6 +13,6 @@ export function artifactSummary(input) {
13
13
  description: acl.metadata?.description ?? acl.description ?? '',
14
14
  icon: acl.metadata?.icon !== undefined ? acl.metadata.icon : acl.icon ?? null,
15
15
  ...(acl.metadata === undefined ? {} : { metadata: acl.metadata }),
16
- permissions: { read: evaluateAccess(acl, actorId, 'read', input.approved),
17
- source: evaluateAccess(acl, actorId, 'source', input.approved), write: owner, manage: owner } };
16
+ permissions: { read: evaluateAccess(acl, actorId, 'read', input.approved, input.policy),
17
+ source: evaluateAccess(acl, actorId, 'source', input.approved, input.policy), write: owner, manage: owner } };
18
18
  }
@@ -0,0 +1,107 @@
1
+ -- G1 — three-mode sharing ACL (converged-r2 §2.1/§2.2 + owner answers Q1–Q3).
2
+ --
3
+ -- Additive upgrade over 0005: no column is dropped or narrowed, existing rows
4
+ -- keep working. `access_mode` closes the wide audience to the three values;
5
+ -- legacy `is_public = true` maps to 'platform', NEVER 'public' (zero artifacts
6
+ -- become anonymous through the migration). `is_public` stays as a read-only
7
+ -- legacy projection of `access_mode` (`<> 'restricted'`); the adapter writes
8
+ -- both together and the forced `is_public = false` writes are removed in code.
9
+ -- `artifact_access_events` is the append-only audit trail written in the same
10
+ -- transaction as the mutation (actor, action, audience, target principal,
11
+ -- policy revision, timestamp — no tokens, no names).
12
+ -- Owner Q1 is enforced at the schema level: the collab (`source`) right is
13
+ -- nominative only — at most one source grant per artifact, only while the
14
+ -- artifact is `restricted`, and no mode widening while a source grant exists.
15
+ -- Legacy 0002 data may hold several `source` grants on one artifact (direct
16
+ -- writes; MCP could only create `read`): they are deduped deterministically
17
+ -- BEFORE the unique index exists — the oldest source grant per artifact
18
+ -- (created_at, tie-break principal_id) stays `source`, every later duplicate
19
+ -- is demoted to `read`. No grant row is ever deleted (every grantee keeps at
20
+ -- least read access) and the outcome never depends on physical row order.
21
+
22
+ ALTER TABLE artifacts.artifacts
23
+ ADD COLUMN IF NOT EXISTS access_mode TEXT NOT NULL DEFAULT 'restricted'
24
+ CHECK (access_mode IN ('restricted', 'platform', 'public'));
25
+
26
+ -- Legacy public flag reads as platform, never public.
27
+ UPDATE artifacts.artifacts SET access_mode = 'platform' WHERE is_public = true;
28
+
29
+ -- Append-only access audit events (same transaction as the mutation).
30
+ CREATE TABLE IF NOT EXISTS artifacts.artifact_access_events (
31
+ id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
32
+ artifact_id UUID NOT NULL REFERENCES artifacts.artifacts (id) ON DELETE CASCADE,
33
+ actor_id TEXT NOT NULL,
34
+ action TEXT NOT NULL CHECK (action IN ('grant', 'revoke')),
35
+ audience TEXT NOT NULL CHECK (audience IN ('user', 'platform', 'public')),
36
+ principal_id TEXT,
37
+ policy_revision TEXT NOT NULL,
38
+ created_at TIMESTAMPTZ NOT NULL DEFAULT now()
39
+ );
40
+ CREATE INDEX IF NOT EXISTS access_events_by_artifact ON artifacts.artifact_access_events (artifact_id);
41
+
42
+ CREATE OR REPLACE FUNCTION artifacts.reject_access_event_mutation() RETURNS trigger AS $$
43
+ BEGIN
44
+ RAISE EXCEPTION 'append-only: artifact_access_events is immutable';
45
+ END;
46
+ $$ LANGUAGE plpgsql;
47
+
48
+ DROP TRIGGER IF EXISTS artifact_access_events_append_only ON artifacts.artifact_access_events;
49
+ CREATE TRIGGER artifact_access_events_append_only
50
+ BEFORE UPDATE OR DELETE OR TRUNCATE ON artifacts.artifact_access_events
51
+ FOR EACH STATEMENT EXECUTE FUNCTION artifacts.reject_access_event_mutation();
52
+
53
+ -- Deterministic dedupe of legacy multi-source artifacts (see header): the
54
+ -- oldest `source` grant per artifact stays `source`; later duplicates demote
55
+ -- to `read`. No row is deleted; ties on created_at break on principal_id.
56
+ UPDATE artifacts.artifact_access AS dup
57
+ SET permission = 'read'
58
+ WHERE dup.permission = 'source'
59
+ AND EXISTS (
60
+ SELECT 1
61
+ FROM artifacts.artifact_access AS keep
62
+ WHERE keep.artifact_id = dup.artifact_id
63
+ AND keep.permission = 'source'
64
+ AND (keep.created_at, keep.principal_id) < (dup.created_at, dup.principal_id)
65
+ );
66
+
67
+ -- Owner Q1, schema level: at most one collab (source) grant per artifact.
68
+ CREATE UNIQUE INDEX IF NOT EXISTS artifact_access_one_source
69
+ ON artifacts.artifact_access (artifact_id) WHERE permission = 'source';
70
+
71
+ CREATE OR REPLACE FUNCTION artifacts.reject_source_outside_restricted() RETURNS trigger AS $$
72
+ DECLARE
73
+ current_mode TEXT;
74
+ BEGIN
75
+ IF NEW.permission = 'source' THEN
76
+ SELECT access_mode INTO current_mode FROM artifacts.artifacts WHERE id = NEW.artifact_id;
77
+ IF current_mode IS DISTINCT FROM 'restricted' THEN
78
+ RAISE EXCEPTION 'source grant requires restricted mode (artifact % is %)', NEW.artifact_id, current_mode;
79
+ END IF;
80
+ END IF;
81
+ RETURN NEW;
82
+ END;
83
+ $$ LANGUAGE plpgsql;
84
+
85
+ DROP TRIGGER IF EXISTS artifact_access_source_guard ON artifacts.artifact_access;
86
+ CREATE TRIGGER artifact_access_source_guard
87
+ BEFORE INSERT OR UPDATE OF permission ON artifacts.artifact_access
88
+ FOR EACH ROW EXECUTE FUNCTION artifacts.reject_source_outside_restricted();
89
+
90
+ -- Owner Q1, schema level: no mode widening while a collab (source) grant exists.
91
+ CREATE OR REPLACE FUNCTION artifacts.reject_widening_with_source_grant() RETURNS trigger AS $$
92
+ BEGIN
93
+ IF (OLD.access_mode = 'restricted' AND NEW.access_mode IN ('platform', 'public'))
94
+ OR (OLD.access_mode = 'platform' AND NEW.access_mode = 'public') THEN
95
+ IF EXISTS (SELECT 1 FROM artifacts.artifact_access
96
+ WHERE artifact_id = NEW.id AND permission = 'source') THEN
97
+ RAISE EXCEPTION 'cannot widen access_mode of artifact % while a source grant exists', NEW.id;
98
+ END IF;
99
+ END IF;
100
+ RETURN NEW;
101
+ END;
102
+ $$ LANGUAGE plpgsql;
103
+
104
+ DROP TRIGGER IF EXISTS artifacts_widening_source_guard ON artifacts.artifacts;
105
+ CREATE TRIGGER artifacts_widening_source_guard
106
+ BEFORE UPDATE OF access_mode ON artifacts.artifacts
107
+ FOR EACH ROW EXECUTE FUNCTION artifacts.reject_widening_with_source_grant();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sentropic/artifacts",
3
- "version": "0.2.9",
3
+ "version": "0.2.10",
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",