@sentropic/artifacts 0.2.9 → 0.2.12

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.
@@ -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
@@ -62,6 +62,35 @@ export interface PublishResult {
62
62
  releaseId: string;
63
63
  manifest: string;
64
64
  }
65
+ /** Default bounded in-flight blob operations per publish batch. */
66
+ export declare const DEFAULT_BLOB_CONCURRENCY = 6;
67
+ /** Hard ceiling for the configurable blob concurrency: no unbounded parallelism. */
68
+ export declare const MAX_BLOB_CONCURRENCY = 8;
69
+ /** Resolve the bounded blob-operation concurrency: default 6, clamped to 8, never below 1. */
70
+ export declare function resolveBlobConcurrency(value: number | undefined): number;
71
+ export interface BlobPoolOptions {
72
+ /** Resolved max operations in flight (1..MAX_BLOB_CONCURRENCY). */
73
+ readonly concurrency: number;
74
+ /** One deadline (epoch ms) shared by every operation of the batch; no new operation starts after it. */
75
+ readonly deadlineAt?: number;
76
+ /** Checked before each operation starts; a throw becomes the batch's first fatal error. */
77
+ readonly beforeEach?: () => void | Promise<void>;
78
+ }
79
+ /**
80
+ * Run one async operation per item with bounded concurrency. At most
81
+ * `concurrency` operations are in flight at any time; every operation of the
82
+ * batch shares the same `deadlineAt`; the first fatal error stops scheduling
83
+ * (in-flight operations run to completion — the blob-store port has no abort
84
+ * signal) and is rethrown unchanged, so the per-operation error projection is
85
+ * identical to the sequential loop.
86
+ */
87
+ export declare function runBlobPool<T>(items: readonly T[], options: BlobPoolOptions, operation: (item: T) => Promise<void>): Promise<void>;
88
+ export interface VerifyStagedOptions {
89
+ /** Bounded in-flight read-backs; defaults to DEFAULT_BLOB_CONCURRENCY, clamped to MAX_BLOB_CONCURRENCY. */
90
+ readonly concurrency?: number;
91
+ /** Shared deadline (epoch ms) for the whole read-back batch. */
92
+ readonly deadlineAt?: number;
93
+ }
65
94
  export interface PublicationService {
66
95
  readonly limits?: Readonly<PublicationLimits>;
67
96
  /** The host source store participates in the idempotent commit when a source is supplied. */
@@ -78,6 +107,8 @@ export declare function createPublicationService(deps: {
78
107
  intents: IntentStore;
79
108
  idempotency?: IdempotencyStore;
80
109
  limits?: Partial<PublicationLimits>;
110
+ /** Bounded in-flight blob read-backs per publish; default 6, clamped to 8. */
111
+ blobConcurrency?: number;
81
112
  }): PublicationService;
82
113
  /**
83
114
  * L4 (immo #861) — guarded publication through the L3 atomic finalization
@@ -155,6 +186,10 @@ export interface GuardedPublicationDeps {
155
186
  readonly noteAbandoned?: (attemptId: string) => void | Promise<void>;
156
187
  readonly cleanupWindowMs?: number;
157
188
  readonly limits?: Partial<PublicationLimits>;
189
+ /** Bounded in-flight blob PUTs/read-backs per publish; default 6, clamped to 8. */
190
+ readonly blobConcurrency?: number;
191
+ /** Per-publish blob-staging budget in ms; one shared deadline for every concurrent blob operation. */
192
+ readonly blobDeadlineMs?: number;
158
193
  }
159
194
  export interface GuardedPublicationService {
160
195
  replayFinalized(input: Omit<GuardedPublishInput, 'files' | 'source' | 'profile'>): Promise<FinalizeResult | undefined>;
@@ -105,9 +105,68 @@ function preparePublication(input) {
105
105
  const manifest = canonicalManifest({ ...body, digest });
106
106
  return { entries, digest, manifest };
107
107
  }
108
- /** Read-back verification shared by the split and finalized paths. */
109
- async function verifyStagedBlobs(blobs, entries) {
110
- for (const { key, bytes } of entries) {
108
+ /** Default bounded in-flight blob operations per publish batch. */
109
+ export const DEFAULT_BLOB_CONCURRENCY = 6;
110
+ /** Hard ceiling for the configurable blob concurrency: no unbounded parallelism. */
111
+ export const MAX_BLOB_CONCURRENCY = 8;
112
+ /** Resolve the bounded blob-operation concurrency: default 6, clamped to 8, never below 1. */
113
+ export function resolveBlobConcurrency(value) {
114
+ if (value === undefined)
115
+ return DEFAULT_BLOB_CONCURRENCY;
116
+ if (!Number.isSafeInteger(value) || value < 1)
117
+ throw new Error('invalid blob concurrency');
118
+ return Math.min(value, MAX_BLOB_CONCURRENCY);
119
+ }
120
+ /** Deadline expiry is projected exactly like a provider timeout (failures.ts TIMEOUT_NAMES). */
121
+ function blobDeadlineError() {
122
+ const error = new Error('blob staging deadline exceeded');
123
+ error.name = 'TimeoutError';
124
+ return error;
125
+ }
126
+ /**
127
+ * Run one async operation per item with bounded concurrency. At most
128
+ * `concurrency` operations are in flight at any time; every operation of the
129
+ * batch shares the same `deadlineAt`; the first fatal error stops scheduling
130
+ * (in-flight operations run to completion — the blob-store port has no abort
131
+ * signal) and is rethrown unchanged, so the per-operation error projection is
132
+ * identical to the sequential loop.
133
+ */
134
+ export async function runBlobPool(items, options, operation) {
135
+ let next = 0;
136
+ let fatal;
137
+ const worker = async () => {
138
+ for (;;) {
139
+ if (fatal !== undefined)
140
+ return;
141
+ if (options.deadlineAt !== undefined && Date.now() >= options.deadlineAt) {
142
+ fatal = { error: blobDeadlineError() };
143
+ return;
144
+ }
145
+ const index = next++;
146
+ if (index >= items.length)
147
+ return;
148
+ try {
149
+ if (options.beforeEach !== undefined)
150
+ await options.beforeEach();
151
+ await operation(items[index]);
152
+ }
153
+ catch (error) {
154
+ fatal = { error };
155
+ return;
156
+ }
157
+ }
158
+ };
159
+ const workers = Array.from({ length: Math.max(1, Math.min(options.concurrency, items.length)) }, () => worker());
160
+ await Promise.all(workers);
161
+ if (fatal !== undefined)
162
+ throw fatal.error;
163
+ }
164
+ /** Read-back verification shared by the split and finalized paths (bounded concurrency). */
165
+ async function verifyStagedBlobs(blobs, entries, options = {}) {
166
+ await runBlobPool(entries, {
167
+ concurrency: resolveBlobConcurrency(options.concurrency),
168
+ ...(options.deadlineAt === undefined ? {} : { deadlineAt: options.deadlineAt }),
169
+ }, async ({ key, bytes }) => {
111
170
  const stored = await blobs.getBlob(key);
112
171
  if (stored === undefined || shaHex(stored) !== shaHex(bytes)) {
113
172
  throw new Error(`publication digest mismatch for ${key}: read-back failed`);
@@ -115,11 +174,12 @@ async function verifyStagedBlobs(blobs, entries) {
115
174
  if (stored.length !== bytes.length) {
116
175
  throw new Error(`publication size mismatch for ${key}: read-back failed`);
117
176
  }
118
- }
177
+ });
119
178
  }
120
179
  /** Create a publication service over injected stores (no driver imports). */
121
180
  export function createPublicationService(deps) {
122
181
  const limits = publicationLimits(deps.limits);
182
+ const blobConcurrency = resolveBlobConcurrency(deps.blobConcurrency);
123
183
  async function commitOnce(input, prepared, sources) {
124
184
  const releaseId = crypto.randomUUID();
125
185
  const { entries, digest, manifest } = prepared;
@@ -132,7 +192,7 @@ export function createPublicationService(deps) {
132
192
  for (const { key, bytes } of entries) {
133
193
  await deps.blobs.putBlob(key, bytes);
134
194
  }
135
- await verifyStagedBlobs(deps.blobs, entries);
195
+ await verifyStagedBlobs(deps.blobs, entries, { concurrency: blobConcurrency });
136
196
  await deps.state.putRelease({
137
197
  releaseId,
138
198
  artifactId: input.artifactId,
@@ -272,6 +332,11 @@ export function createGuardedPublicationService(deps) {
272
332
  const cleanupWindowMs = deps.cleanupWindowMs ?? DEFAULT_CLEANUP_WINDOW_MS;
273
333
  if (!Number.isSafeInteger(cleanupWindowMs) || cleanupWindowMs < 1)
274
334
  throw new Error('invalid preparation lifetime');
335
+ const blobConcurrency = resolveBlobConcurrency(deps.blobConcurrency);
336
+ const blobDeadlineMs = deps.blobDeadlineMs;
337
+ if (blobDeadlineMs !== undefined && (!Number.isSafeInteger(blobDeadlineMs) || blobDeadlineMs < 1)) {
338
+ throw new Error('invalid blob deadline');
339
+ }
275
340
  const guard = (client, authorizeCommit) => async (context, transaction) => {
276
341
  const { state, acl } = await deps.createUnitWriter(client()).readAuthorization(context.artifactId);
277
342
  const verdict = decidePublishAuthorization({ lifecycleState: state, acl, actorId: context.actorId });
@@ -342,15 +407,27 @@ export function createGuardedPublicationService(deps) {
342
407
  pinned.push(digest);
343
408
  }
344
409
  await deps.coordinator.testObserver?.arrive('before_blob_put', invocationId);
345
- for (const { key, bytes } of prepared.entries) {
346
- if ((await deps.intents.get(intent.intentId))?.state !== 'pending') {
347
- throw new Error('preparation abandoned before blob PUT');
348
- }
410
+ // Bounded concurrency over the staged PUTs: one shared deadline for the
411
+ // whole batch, the intent-pending check before every PUT, and the first
412
+ // fatal error stops scheduling and propagates unchanged.
413
+ const deadlineAt = blobDeadlineMs === undefined ? undefined : nowMs + blobDeadlineMs;
414
+ await runBlobPool(prepared.entries, {
415
+ concurrency: blobConcurrency,
416
+ ...(deadlineAt === undefined ? {} : { deadlineAt }),
417
+ beforeEach: async () => {
418
+ if ((await deps.intents.get(intent.intentId))?.state !== 'pending') {
419
+ throw new Error('preparation abandoned before blob PUT');
420
+ }
421
+ },
422
+ }, async ({ key, bytes }) => {
349
423
  await deps.blobs.putBlob(key, bytes);
350
- }
424
+ });
351
425
  await deps.coordinator.testObserver?.arrive('after_blob_put_before_verify', invocationId);
352
426
  await deps.coordinator.testObserver?.arrive('before_blob_readback', invocationId);
353
- await verifyStagedBlobs(deps.blobs, prepared.entries);
427
+ await verifyStagedBlobs(deps.blobs, prepared.entries, {
428
+ concurrency: blobConcurrency,
429
+ ...(deadlineAt === undefined ? {} : { deadlineAt }),
430
+ });
354
431
  const addedRefs = [];
355
432
  const source = input.source === undefined ? undefined : parseSourceRef(input.source);
356
433
  let finalizationClient;
@@ -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
  }