@sentropic/artifacts 0.2.10 → 0.2.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/CHANGELOG.md +88 -0
  2. package/README.md +45 -10
  3. package/dist/adapters/postgres-management.js +3 -2
  4. package/dist/adapters/postgres-reader-consent.d.ts +11 -0
  5. package/dist/adapters/postgres-reader-consent.js +109 -0
  6. package/dist/adapters/postgres.js +4 -3
  7. package/dist/adapters/s3-uploads.d.ts +33 -0
  8. package/dist/adapters/s3-uploads.js +105 -0
  9. package/dist/content/headers.js +12 -0
  10. package/dist/http.d.ts +16 -2
  11. package/dist/http.js +325 -12
  12. package/dist/mcp-core.d.ts +3 -3
  13. package/dist/mcp-core.js +51 -4
  14. package/dist/profile/contracts.d.ts +1 -1
  15. package/dist/profile/contracts.js +3 -0
  16. package/dist/profile/index.js +33 -2
  17. package/dist/profile/radar.js +7 -0
  18. package/dist/profile/schemas.js +59 -0
  19. package/dist/profile/validation.d.ts +11 -0
  20. package/dist/profile/validation.js +71 -6
  21. package/dist/server/access.d.ts +2 -0
  22. package/dist/server/command-identity.d.ts +1 -1
  23. package/dist/server/command-identity.js +5 -3
  24. package/dist/server/consent.d.ts +65 -0
  25. package/dist/server/consent.js +42 -0
  26. package/dist/server/gc.d.ts +17 -0
  27. package/dist/server/gc.js +22 -0
  28. package/dist/server/management.d.ts +3 -1
  29. package/dist/server/management.js +48 -7
  30. package/dist/server/mime.d.ts +26 -2
  31. package/dist/server/mime.js +124 -2
  32. package/dist/server/ports.d.ts +29 -0
  33. package/dist/server/ports.js +11 -0
  34. package/dist/server/publication-limits.d.ts +12 -0
  35. package/dist/server/publication-limits.js +19 -1
  36. package/dist/server/publication.d.ts +44 -0
  37. package/dist/server/publication.js +90 -11
  38. package/dist/server/reader-store.d.ts +58 -0
  39. package/dist/server/reader-store.js +109 -0
  40. package/dist/server/templates.js +50 -2
  41. package/dist/server/uploads.d.ts +154 -18
  42. package/dist/server/uploads.js +227 -80
  43. package/migrations/0007_uploads.sql +43 -0
  44. package/migrations/0008_reader_consent.sql +48 -0
  45. package/package.json +22 -1
  46. package/sql/reader-consent.sql +47 -0
@@ -15,6 +15,11 @@ function policyRefused() {
15
15
  return new ArtifactOperationError('unauthorized_at_commit', { refusal: { allowed: false,
16
16
  reason: 'denied', status: 403, publicCode: 'public_sharing_disabled', retriable: false } });
17
17
  }
18
+ /** G2 §2.3 step (4): the single merged non-shareable refusal (422), like the policy refusal above. */
19
+ function shareableRefused() {
20
+ return new ArtifactOperationError('unauthorized_at_commit', { refusal: { allowed: false,
21
+ reason: 'denied', status: 422, publicCode: 'person_not_shareable', retriable: false } });
22
+ }
18
23
  /** Targeted writes and proof consumption share the existing coordinator receipt transaction. */
19
24
  export async function manageArtifact(deps, invocation, command, proof) {
20
25
  const artifactId = command.payload.artifactId;
@@ -51,6 +56,38 @@ export async function manageArtifact(deps, invocation, command, proof) {
51
56
  return target;
52
57
  };
53
58
  const sharingPolicy = async () => combineSharingPolicy(deps.profileAllowPublicSharing, await resolveSharingPolicy(deps.sharingPolicy, invocation.storageScopeId));
59
+ // G2 §2.3 step (4): resolve the opaque userRef to the internal principal
60
+ // inside the transaction, after visibility and the management right — the
61
+ // commandHash was computed on the payload as provided (userRef), so no
62
+ // resolution can leak to a non-reader. Without a directory port, legacy
63
+ // trusted callers keep passing internal principals directly (G1 behaviour).
64
+ const resolveTarget = async (principalId) => {
65
+ if (deps.directory === undefined)
66
+ return principalId;
67
+ return await deps.directory.resolvePrincipal(invocation.storageScopeId, principalId) ?? principalId;
68
+ };
69
+ // Unknown, inactive, unapproved and out-of-scope targets merge into the
70
+ // single `person_not_shareable` so no account status can be probed.
71
+ const assertShareable = async (internal, action) => {
72
+ if (deps.directory === undefined) {
73
+ if (action === 'grant' && !await deps.isApprovedPrincipal(internal))
74
+ throw refused('access_denied');
75
+ return;
76
+ }
77
+ if (!await deps.isApprovedPrincipal(internal))
78
+ throw shareableRefused();
79
+ };
80
+ // The receipt is model-visible: project internal principals to userRefs
81
+ // (audit events keep the internal form).
82
+ const projectGrants = async (grants) => {
83
+ if (deps.directory === undefined)
84
+ return grants;
85
+ return Promise.all(grants.map(async (grant) => ({
86
+ ...grant,
87
+ principalId: (await deps.directory.describePrincipal(invocation.storageScopeId, grant.principalId))?.userRef
88
+ ?? grant.principalId,
89
+ })));
90
+ };
54
91
  const request = {
55
92
  ...command.identity, scopeId: invocation.storageScopeId, actorId: invocation.actorId,
56
93
  invocationId: invocation.invocationId, operation: command.operation, artifactId,
@@ -87,17 +124,19 @@ export async function manageArtifact(deps, invocation, command, proof) {
87
124
  else {
88
125
  const { action, principalId } = access;
89
126
  const audience = audienceOf(principalId);
90
- if (audience === 'user' && action === 'grant' && !await deps.isApprovedPrincipal(principalId))
91
- throw refused('access_denied');
127
+ const internal = audience === 'user' ? await resolveTarget(principalId) : principalId;
128
+ if (audience === 'user')
129
+ await assertShareable(internal, action);
92
130
  // Double lock (profile capability AND runtime port) resolved in the
93
131
  // transaction; the revision rides the receipt/audit, never the commandHash.
94
132
  const policy = await sharingPolicy();
95
133
  if (action === 'grant' && principalId === PUBLIC_PRINCIPAL && !policy.allowPublicSharing)
96
134
  throw policyRefused();
97
- const output = await unit.setAccess(artifactId, principalId, action, now);
135
+ const output = await unit.setAccess(artifactId, internal, action, now);
98
136
  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 });
137
+ principalId: audience === 'user' ? internal : null, policyRevision: policy.policyRevision });
138
+ Object.assign(receipt, { artifactId, ...output, grants: await projectGrants(output.grants),
139
+ policyRevision: policy.policyRevision });
101
140
  }
102
141
  },
103
142
  guard: async (ctx, tx) => {
@@ -107,8 +146,10 @@ export async function manageArtifact(deps, invocation, command, proof) {
107
146
  if (!deleting) {
108
147
  const { action, principalId } = access;
109
148
  const audience = audienceOf(principalId);
110
- if (audience === 'user' && action === 'grant' && !await deps.isApprovedPrincipal(principalId))
111
- throw refused('access_denied');
149
+ if (audience === 'user') {
150
+ const internal = await resolveTarget(principalId);
151
+ await assertShareable(internal, action);
152
+ }
112
153
  const policy = await sharingPolicy();
113
154
  if (action === 'grant' && principalId === PUBLIC_PRINCIPAL && !policy.allowPublicSharing)
114
155
  throw policyRefused();
@@ -1,7 +1,31 @@
1
1
  /**
2
2
  * Canonical text-mime pattern shared by publication input rules and source
3
- * reads. Leaf module: both `http.ts` and `server/source-read.ts` import it
4
- * without an import cycle.
3
+ * reads, plus the generic MIME ceiling and byte validation (files parity
4
+ * LOT 1). Leaf module: `http.ts`, `server/source-read.ts`, `server/uploads.ts`
5
+ * and `profile/index.ts` import it without an import cycle.
6
+ *
7
+ * The ceiling is the generic server maximum: a profile `mimeTypes` list must
8
+ * be a subset of it (checked at profile compile time). Validation at commit
9
+ * (upload commit and inline publish alike): magic bytes for binary types,
10
+ * strict UTF-8 for text types, and a script/handler/external-reference-free
11
+ * SVG. Declared type stays authoritative at serve time because it was
12
+ * verified against the bytes at commit (sniffing stays banned).
5
13
  */
6
14
  export declare const TEXT_MIME_PATTERN = "^(?:text/[a-z0-9!#$&^_.+-]+|application/(?:javascript|ecmascript|json|xml|[a-z0-9!#$&^_.+-]+\\+(?:json|xml))|image/svg\\+xml)(?![\\s\\S])";
7
15
  export declare const TEXT_MIME_RE: RegExp;
16
+ /**
17
+ * Generic MIME ceiling (server maximum). Profiles may only narrow it.
18
+ * No executables, no archives: the posture rests on this closed allowlist
19
+ * plus magic-byte verification, declared-type serving with `nosniff` on the
20
+ * single-label content origin, and sandbox CSP on SVG/PDF.
21
+ */
22
+ export declare const SERVER_MIME_CEILING: readonly string[];
23
+ /** True when the MIME type is inside the generic ceiling. */
24
+ export declare function isWithinMimeCeiling(mimeType: string): boolean;
25
+ /**
26
+ * Validate file bytes against the declared MIME type. Throws on mismatch;
27
+ * callers map the failure to `verification_failed` (422) with no pin and no
28
+ * release. Text types must decode as strict UTF-8; SVG must be XML text
29
+ * without scripts, event handlers or external references.
30
+ */
31
+ export declare function validateFileBytes(mimeType: string, bytes: Uint8Array): void;
@@ -1,7 +1,129 @@
1
1
  /**
2
2
  * Canonical text-mime pattern shared by publication input rules and source
3
- * reads. Leaf module: both `http.ts` and `server/source-read.ts` import it
4
- * without an import cycle.
3
+ * reads, plus the generic MIME ceiling and byte validation (files parity
4
+ * LOT 1). Leaf module: `http.ts`, `server/source-read.ts`, `server/uploads.ts`
5
+ * and `profile/index.ts` import it without an import cycle.
6
+ *
7
+ * The ceiling is the generic server maximum: a profile `mimeTypes` list must
8
+ * be a subset of it (checked at profile compile time). Validation at commit
9
+ * (upload commit and inline publish alike): magic bytes for binary types,
10
+ * strict UTF-8 for text types, and a script/handler/external-reference-free
11
+ * SVG. Declared type stays authoritative at serve time because it was
12
+ * verified against the bytes at commit (sniffing stays banned).
5
13
  */
6
14
  export const TEXT_MIME_PATTERN = '^(?:text/[a-z0-9!#$&^_.+-]+|application/(?:javascript|ecmascript|json|xml|[a-z0-9!#$&^_.+-]+\\+(?:json|xml))|image/svg\\+xml)(?![\\s\\S])';
7
15
  export const TEXT_MIME_RE = new RegExp(TEXT_MIME_PATTERN);
16
+ /**
17
+ * Generic MIME ceiling (server maximum). Profiles may only narrow it.
18
+ * No executables, no archives: the posture rests on this closed allowlist
19
+ * plus magic-byte verification, declared-type serving with `nosniff` on the
20
+ * single-label content origin, and sandbox CSP on SVG/PDF.
21
+ */
22
+ export const SERVER_MIME_CEILING = Object.freeze([
23
+ 'text/html', 'text/css', 'text/javascript', 'application/json',
24
+ 'image/png', 'image/jpeg', 'image/gif', 'image/webp', 'image/avif',
25
+ 'image/svg+xml', 'image/x-icon',
26
+ 'application/pdf',
27
+ 'font/woff', 'font/woff2', 'font/ttf', 'font/otf',
28
+ 'video/mp4', 'video/webm',
29
+ ]);
30
+ /** True when the MIME type is inside the generic ceiling. */
31
+ export function isWithinMimeCeiling(mimeType) {
32
+ return SERVER_MIME_CEILING.includes(mimeType);
33
+ }
34
+ /** Magic-byte signatures checked for binary types before any pin or release. */
35
+ const MAGIC_BYTES = Object.freeze({
36
+ 'image/png': [[0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]],
37
+ 'image/jpeg': [[0xff, 0xd8, 0xff]],
38
+ 'image/gif': [[0x47, 0x49, 0x46, 0x38, 0x37, 0x61], [0x47, 0x49, 0x46, 0x38, 0x39, 0x61]],
39
+ 'image/webp': [[0x52, 0x49, 0x46, 0x46]], // RIFF....WEBP checked below
40
+ 'image/avif': [[0x66, 0x74, 0x79, 0x70, 0x61, 0x76, 0x69, 0x66]], // ftypavif
41
+ 'image/x-icon': [[0x00, 0x00, 0x01, 0x00]],
42
+ 'application/pdf': [[0x25, 0x50, 0x44, 0x46, 0x2d]], // %PDF-
43
+ 'font/woff': [[0x77, 0x4f, 0x46, 0x46]], // wOFF
44
+ 'font/woff2': [[0x77, 0x4f, 0x46, 0x32]], // wOF2
45
+ 'font/ttf': [[0x00, 0x01, 0x00, 0x00]],
46
+ 'font/otf': [[0x4f, 0x54, 0x54, 0x4f]], // OTTO
47
+ 'video/mp4': [[0x66, 0x74, 0x79, 0x70]], // ftyp (brand checked loosely: isom/iso2/mp41/mp42/avc1/dash/msdh/m4v...)
48
+ 'video/webm': [[0x1a, 0x45, 0xdf, 0xa3]], // EBML
49
+ });
50
+ function hasMagic(bytes, magic) {
51
+ if (bytes.length < magic.length)
52
+ return false;
53
+ return magic.every((byte, index) => bytes[index] === byte);
54
+ }
55
+ /** True for the RIFF....WEBP container (bytes 0-3 RIFF, 8-11 WEBP). */
56
+ function isWebp(bytes) {
57
+ return hasMagic(bytes, [0x52, 0x49, 0x46, 0x46]) && bytes.length >= 12 &&
58
+ hasMagic(bytes.subarray(8), [0x57, 0x45, 0x42, 0x50]);
59
+ }
60
+ /** True for an ISO-BMFF ftyp box whose major brand is an mp4 family brand. */
61
+ function isMp4(bytes) {
62
+ if (!hasMagic(bytes, [0x66, 0x74, 0x79, 0x70]) || bytes.length < 12)
63
+ return false;
64
+ const brand = String.fromCharCode(...bytes.subarray(8, 12));
65
+ return /^(isom|iso2|mp41|mp42|mp4v|avc1|dash|msdh|msix|m4v|m4a|3gp)/.test(brand);
66
+ }
67
+ /** True for an ISO-BMFF ftyp box whose major brand is avif/avis. */
68
+ function isAvif(bytes) {
69
+ if (!hasMagic(bytes, [0x66, 0x74, 0x79, 0x70]) || bytes.length < 12)
70
+ return false;
71
+ const brand = String.fromCharCode(...bytes.subarray(8, 12));
72
+ return brand === 'avif' || brand === 'avis';
73
+ }
74
+ const SVG_FORBIDDEN_RE = /<script|\son[a-z]+\s*=|href\s*=\s*["'](?!#)|xlink:href\s*=\s*["'](?!#)/i;
75
+ /**
76
+ * Validate file bytes against the declared MIME type. Throws on mismatch;
77
+ * callers map the failure to `verification_failed` (422) with no pin and no
78
+ * release. Text types must decode as strict UTF-8; SVG must be XML text
79
+ * without scripts, event handlers or external references.
80
+ */
81
+ export function validateFileBytes(mimeType, bytes) {
82
+ if (!isWithinMimeCeiling(mimeType))
83
+ throw new Error(`MIME type outside the server ceiling: ${mimeType}`);
84
+ if (TEXT_MIME_RE.test(mimeType)) {
85
+ if (mimeType === 'image/svg+xml') {
86
+ let text;
87
+ try {
88
+ text = new TextDecoder('utf-8', { fatal: true }).decode(bytes);
89
+ }
90
+ catch {
91
+ throw new Error('SVG is not strict UTF-8');
92
+ }
93
+ if (!/<svg[\s>]/i.test(text))
94
+ throw new Error('SVG has no root <svg> element');
95
+ if (SVG_FORBIDDEN_RE.test(text)) {
96
+ throw new Error('SVG contains a script, event handler or external reference');
97
+ }
98
+ return;
99
+ }
100
+ try {
101
+ new TextDecoder('utf-8', { fatal: true }).decode(bytes);
102
+ }
103
+ catch {
104
+ throw new Error(`text type ${mimeType} is not strict UTF-8`);
105
+ }
106
+ return;
107
+ }
108
+ if (mimeType === 'image/webp') {
109
+ if (!isWebp(bytes))
110
+ throw new Error('webp magic bytes mismatch');
111
+ return;
112
+ }
113
+ if (mimeType === 'image/avif') {
114
+ if (!isAvif(bytes))
115
+ throw new Error('avif magic bytes mismatch');
116
+ return;
117
+ }
118
+ if (mimeType === 'video/mp4') {
119
+ if (!isMp4(bytes))
120
+ throw new Error('mp4 magic bytes mismatch');
121
+ return;
122
+ }
123
+ const magics = MAGIC_BYTES[mimeType];
124
+ if (magics === undefined)
125
+ throw new Error(`no magic-byte rule for ${mimeType}`);
126
+ if (!magics.some((magic) => hasMagic(bytes, magic))) {
127
+ throw new Error(`${mimeType} magic bytes mismatch`);
128
+ }
129
+ }
@@ -26,6 +26,35 @@ 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
+ * G2 principal directory port (converged-r2 §2.3). The host-trusted side of
31
+ * the model boundary: it knows internal principal ids and full emails; the
32
+ * package resolves opaque `userRef`s to internal principals and projects every
33
+ * model-visible output back to `userRef` + masked `emailHint`. Search and
34
+ * resolution are scope-filtered; approval is NOT part of resolution — every
35
+ * resolution/approval failure merges into the single `person_not_shareable`.
36
+ */
37
+ export interface DirectoryPerson {
38
+ /** Opaque model-facing reference; the only principal form a model may see or send back. */
39
+ readonly userRef: string;
40
+ readonly displayName: string;
41
+ /** Full email, host-side only; never projected to a model payload. */
42
+ readonly email: string;
43
+ }
44
+ export interface PrincipalDirectoryPort {
45
+ /** Approved accounts of the scope matching the query (case/accent-insensitive on name and email). */
46
+ searchPeople(scope: string, query: string, limit: number): Promise<readonly DirectoryPerson[]>;
47
+ /** Resolve one opaque userRef to the internal principal id; undefined when unknown or out of scope. */
48
+ resolvePrincipal(scope: string, userRef: string): Promise<string | undefined>;
49
+ /** Inverse projection: internal principal id → directory person (userRef/displayName/email). */
50
+ describePrincipal(scope: string, principalId: string): Promise<DirectoryPerson | undefined>;
51
+ }
52
+ /**
53
+ * Mask an email for model payloads: first local-part character kept, rest of
54
+ * the local part masked, domain visible — lifts homonyms without disclosing
55
+ * the directory. The package masks, so no full email can reach the wire.
56
+ */
57
+ export declare function maskEmailHint(email: string): string;
29
58
  /**
30
59
  * G1 sharing policy port (converged-r2 §2.2, lock 2 of the double lock).
31
60
  * Resolved by the host per storage scope, inside the commit transaction and
@@ -21,6 +21,17 @@ export function createCryptoUuid() {
21
21
  },
22
22
  };
23
23
  }
24
+ /**
25
+ * Mask an email for model payloads: first local-part character kept, rest of
26
+ * the local part masked, domain visible — lifts homonyms without disclosing
27
+ * the directory. The package masks, so no full email can reach the wire.
28
+ */
29
+ export function maskEmailHint(email) {
30
+ const at = email.lastIndexOf('@');
31
+ if (at <= 0)
32
+ return '***';
33
+ return `${email.slice(0, 1)}***@${email.slice(at + 1)}`;
34
+ }
24
35
  /** Fail-closed policy used whenever no well-formed answer exists. */
25
36
  export const CLOSED_SHARING_POLICY = Object.freeze({ allowPublicSharing: false, policyRevision: 'none' });
26
37
  /** Resolve the runtime lock fail-closed: absent port, throw or malformed answer ⇒ closed. */
@@ -4,6 +4,18 @@ export interface PublicationLimits {
4
4
  maxFileBytes: number;
5
5
  maxTotalBytes: number;
6
6
  }
7
+ /**
8
+ * Generic server maxima (files parity LOT 1). A profile above any ceiling
9
+ * fails compilation, and `publicationLimits` refuses overrides above them:
10
+ * the ceiling is generic, the values are profile-owned below it.
11
+ * 255 files per release, 16 MiB per file, 64 MiB per release.
12
+ */
13
+ export declare const SERVER_MAX_FILES_PER_RELEASE = 255;
14
+ export declare const SERVER_MAX_FILE_BYTES: number;
15
+ export declare const SERVER_MAX_TOTAL_BYTES: number;
16
+ /** Concurrent open upload sessions per principal (leaked-URL DoS bound). */
17
+ export declare const SERVER_MAX_UPLOAD_SESSIONS_PER_PRINCIPAL = 8;
18
+ /** Generic defaults: 255 files, 16 MiB per file, 64 MiB total (files parity LOT 1). */
7
19
  export declare const DEFAULT_PUBLICATION_LIMITS: Readonly<PublicationLimits>;
8
20
  export declare function publicationLimits(overrides?: Partial<PublicationLimits>): Readonly<PublicationLimits>;
9
21
  /** Validate before copying bytes, hashing, idempotency lookup or recording intents. */
@@ -1,11 +1,29 @@
1
+ /**
2
+ * Generic server maxima (files parity LOT 1). A profile above any ceiling
3
+ * fails compilation, and `publicationLimits` refuses overrides above them:
4
+ * the ceiling is generic, the values are profile-owned below it.
5
+ * 255 files per release, 16 MiB per file, 64 MiB per release.
6
+ */
7
+ export const SERVER_MAX_FILES_PER_RELEASE = 255;
8
+ export const SERVER_MAX_FILE_BYTES = 16 * 1024 * 1024;
9
+ export const SERVER_MAX_TOTAL_BYTES = 64 * 1024 * 1024;
10
+ /** Concurrent open upload sessions per principal (leaked-URL DoS bound). */
11
+ export const SERVER_MAX_UPLOAD_SESSIONS_PER_PRINCIPAL = 8;
12
+ /** Generic defaults: 255 files, 16 MiB per file, 64 MiB total (files parity LOT 1). */
1
13
  export const DEFAULT_PUBLICATION_LIMITS = Object.freeze({
2
- maxFiles: 128, maxFileBytes: 16 * 1024 * 1024, maxTotalBytes: 64 * 1024 * 1024,
14
+ maxFiles: SERVER_MAX_FILES_PER_RELEASE,
15
+ maxFileBytes: SERVER_MAX_FILE_BYTES,
16
+ maxTotalBytes: SERVER_MAX_TOTAL_BYTES,
3
17
  });
4
18
  export function publicationLimits(overrides = {}) {
5
19
  const limits = { ...DEFAULT_PUBLICATION_LIMITS, ...overrides };
6
20
  if (Object.values(limits).some((value) => !Number.isSafeInteger(value) || value <= 0)) {
7
21
  throw new Error('invalid publication limits');
8
22
  }
23
+ if (limits.maxFiles > SERVER_MAX_FILES_PER_RELEASE || limits.maxFileBytes > SERVER_MAX_FILE_BYTES ||
24
+ limits.maxTotalBytes > SERVER_MAX_TOTAL_BYTES) {
25
+ throw new Error('publication limits above the server maxima');
26
+ }
9
27
  return Object.freeze(limits);
10
28
  }
11
29
  /** Validate before copying bytes, hashing, idempotency lookup or recording intents. */
@@ -62,6 +62,44 @@ export interface PublishResult {
62
62
  releaseId: string;
63
63
  manifest: string;
64
64
  }
65
+ /** Minimal shape needed for a read-back verification batch (uploads commit reuses this). */
66
+ export interface VerifyStagedBlobEntry {
67
+ readonly key: string;
68
+ readonly bytes: Uint8Array;
69
+ }
70
+ /** Default bounded in-flight blob operations per publish batch. */
71
+ export declare const DEFAULT_BLOB_CONCURRENCY = 6;
72
+ /** Hard ceiling for the configurable blob concurrency: no unbounded parallelism. */
73
+ export declare const MAX_BLOB_CONCURRENCY = 8;
74
+ /** Resolve the bounded blob-operation concurrency: default 6, clamped to 8, never below 1. */
75
+ export declare function resolveBlobConcurrency(value: number | undefined): number;
76
+ export interface BlobPoolOptions {
77
+ /** Resolved max operations in flight (1..MAX_BLOB_CONCURRENCY). */
78
+ readonly concurrency: number;
79
+ /** One deadline (epoch ms) shared by every operation of the batch; no new operation starts after it. */
80
+ readonly deadlineAt?: number;
81
+ /** Checked before each operation starts; a throw becomes the batch's first fatal error. */
82
+ readonly beforeEach?: () => void | Promise<void>;
83
+ }
84
+ /**
85
+ * Run one async operation per item with bounded concurrency. At most
86
+ * `concurrency` operations are in flight at any time; every operation of the
87
+ * batch shares the same `deadlineAt`; the first fatal error stops scheduling
88
+ * (in-flight operations run to completion — the blob-store port has no abort
89
+ * signal) and is rethrown unchanged, so the per-operation error projection is
90
+ * identical to the sequential loop.
91
+ */
92
+ export declare function runBlobPool<T>(items: readonly T[], options: BlobPoolOptions, operation: (item: T) => Promise<void>): Promise<void>;
93
+ export interface VerifyStagedOptions {
94
+ /** Bounded in-flight read-backs; defaults to DEFAULT_BLOB_CONCURRENCY, clamped to MAX_BLOB_CONCURRENCY. */
95
+ readonly concurrency?: number;
96
+ /** Shared deadline (epoch ms) for the whole read-back batch. */
97
+ readonly deadlineAt?: number;
98
+ }
99
+ /** Read-back verification shared by the split and finalized paths (bounded concurrency).
100
+ * Exported for files parity LOT 1: commit_upload re-verifies a promoted staging object
101
+ * through the same #907 bounded pool before pinning it. */
102
+ export declare function verifyStagedBlobs<T extends VerifyStagedBlobEntry>(blobs: PublicationBlobStore, entries: readonly T[], options?: VerifyStagedOptions): Promise<void>;
65
103
  export interface PublicationService {
66
104
  readonly limits?: Readonly<PublicationLimits>;
67
105
  /** The host source store participates in the idempotent commit when a source is supplied. */
@@ -78,6 +116,8 @@ export declare function createPublicationService(deps: {
78
116
  intents: IntentStore;
79
117
  idempotency?: IdempotencyStore;
80
118
  limits?: Partial<PublicationLimits>;
119
+ /** Bounded in-flight blob read-backs per publish; default 6, clamped to 8. */
120
+ blobConcurrency?: number;
81
121
  }): PublicationService;
82
122
  /**
83
123
  * L4 (immo #861) — guarded publication through the L3 atomic finalization
@@ -155,6 +195,10 @@ export interface GuardedPublicationDeps {
155
195
  readonly noteAbandoned?: (attemptId: string) => void | Promise<void>;
156
196
  readonly cleanupWindowMs?: number;
157
197
  readonly limits?: Partial<PublicationLimits>;
198
+ /** Bounded in-flight blob PUTs/read-backs per publish; default 6, clamped to 8. */
199
+ readonly blobConcurrency?: number;
200
+ /** Per-publish blob-staging budget in ms; one shared deadline for every concurrent blob operation. */
201
+ readonly blobDeadlineMs?: number;
158
202
  }
159
203
  export interface GuardedPublicationService {
160
204
  replayFinalized(input: Omit<GuardedPublishInput, 'files' | 'source' | 'profile'>): Promise<FinalizeResult | undefined>;
@@ -105,9 +105,70 @@ 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
+ * Exported for files parity LOT 1: commit_upload re-verifies a promoted staging object
166
+ * through the same #907 bounded pool before pinning it. */
167
+ export async function verifyStagedBlobs(blobs, entries, options = {}) {
168
+ await runBlobPool(entries, {
169
+ concurrency: resolveBlobConcurrency(options.concurrency),
170
+ ...(options.deadlineAt === undefined ? {} : { deadlineAt: options.deadlineAt }),
171
+ }, async ({ key, bytes }) => {
111
172
  const stored = await blobs.getBlob(key);
112
173
  if (stored === undefined || shaHex(stored) !== shaHex(bytes)) {
113
174
  throw new Error(`publication digest mismatch for ${key}: read-back failed`);
@@ -115,11 +176,12 @@ async function verifyStagedBlobs(blobs, entries) {
115
176
  if (stored.length !== bytes.length) {
116
177
  throw new Error(`publication size mismatch for ${key}: read-back failed`);
117
178
  }
118
- }
179
+ });
119
180
  }
120
181
  /** Create a publication service over injected stores (no driver imports). */
121
182
  export function createPublicationService(deps) {
122
183
  const limits = publicationLimits(deps.limits);
184
+ const blobConcurrency = resolveBlobConcurrency(deps.blobConcurrency);
123
185
  async function commitOnce(input, prepared, sources) {
124
186
  const releaseId = crypto.randomUUID();
125
187
  const { entries, digest, manifest } = prepared;
@@ -132,7 +194,7 @@ export function createPublicationService(deps) {
132
194
  for (const { key, bytes } of entries) {
133
195
  await deps.blobs.putBlob(key, bytes);
134
196
  }
135
- await verifyStagedBlobs(deps.blobs, entries);
197
+ await verifyStagedBlobs(deps.blobs, entries, { concurrency: blobConcurrency });
136
198
  await deps.state.putRelease({
137
199
  releaseId,
138
200
  artifactId: input.artifactId,
@@ -272,6 +334,11 @@ export function createGuardedPublicationService(deps) {
272
334
  const cleanupWindowMs = deps.cleanupWindowMs ?? DEFAULT_CLEANUP_WINDOW_MS;
273
335
  if (!Number.isSafeInteger(cleanupWindowMs) || cleanupWindowMs < 1)
274
336
  throw new Error('invalid preparation lifetime');
337
+ const blobConcurrency = resolveBlobConcurrency(deps.blobConcurrency);
338
+ const blobDeadlineMs = deps.blobDeadlineMs;
339
+ if (blobDeadlineMs !== undefined && (!Number.isSafeInteger(blobDeadlineMs) || blobDeadlineMs < 1)) {
340
+ throw new Error('invalid blob deadline');
341
+ }
275
342
  const guard = (client, authorizeCommit) => async (context, transaction) => {
276
343
  const { state, acl } = await deps.createUnitWriter(client()).readAuthorization(context.artifactId);
277
344
  const verdict = decidePublishAuthorization({ lifecycleState: state, acl, actorId: context.actorId });
@@ -342,15 +409,27 @@ export function createGuardedPublicationService(deps) {
342
409
  pinned.push(digest);
343
410
  }
344
411
  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
- }
412
+ // Bounded concurrency over the staged PUTs: one shared deadline for the
413
+ // whole batch, the intent-pending check before every PUT, and the first
414
+ // fatal error stops scheduling and propagates unchanged.
415
+ const deadlineAt = blobDeadlineMs === undefined ? undefined : nowMs + blobDeadlineMs;
416
+ await runBlobPool(prepared.entries, {
417
+ concurrency: blobConcurrency,
418
+ ...(deadlineAt === undefined ? {} : { deadlineAt }),
419
+ beforeEach: async () => {
420
+ if ((await deps.intents.get(intent.intentId))?.state !== 'pending') {
421
+ throw new Error('preparation abandoned before blob PUT');
422
+ }
423
+ },
424
+ }, async ({ key, bytes }) => {
349
425
  await deps.blobs.putBlob(key, bytes);
350
- }
426
+ });
351
427
  await deps.coordinator.testObserver?.arrive('after_blob_put_before_verify', invocationId);
352
428
  await deps.coordinator.testObserver?.arrive('before_blob_readback', invocationId);
353
- await verifyStagedBlobs(deps.blobs, prepared.entries);
429
+ await verifyStagedBlobs(deps.blobs, prepared.entries, {
430
+ concurrency: blobConcurrency,
431
+ ...(deadlineAt === undefined ? {} : { deadlineAt }),
432
+ });
354
433
  const addedRefs = [];
355
434
  const source = input.source === undefined ? undefined : parseSourceRef(input.source);
356
435
  let finalizationClient;
@@ -0,0 +1,58 @@
1
+ /**
2
+ * Lot 1a — host port for the personal reader store, consent slice
3
+ * (design-merged §1.3, §3.1). One identity, one store: consent rows key on
4
+ * the same `(storageScopeId, readerAccountId, artifactId)` tuple as the
5
+ * personal KV and the `me/` subtree of lots 2–3. Server only: the page can
6
+ * neither read, write nor enumerate consent; it learns only the binary
7
+ * outcome of its own call. Absent port ⇒ closed: hosts without a wired
8
+ * store refuse consent routes with `capability_unavailable`.
9
+ */
10
+ import { type ConsentKey, type ReaderConsentEvent, type ReaderConsentRecord } from './consent.js';
11
+ export type ConsentRevokedBy = 'self' | 'admin' | 'cascade';
12
+ export interface ConsentRevokeAudit {
13
+ actor: string;
14
+ surface: 'screen' | 'api' | 'mcp' | 'cascade';
15
+ }
16
+ export interface PrincipalDataExport {
17
+ consents: readonly ReaderConsentRecord[];
18
+ /** Lot 2 fills the personal KV slice; empty until then. */
19
+ kv: readonly unknown[];
20
+ /** Lot 3 fills the me-documents slice; empty until then. */
21
+ meDocs: readonly unknown[];
22
+ /** Lot 3 fills shared-write references; empty until then. */
23
+ sharedWriteRefs: readonly unknown[];
24
+ }
25
+ export interface ArtifactReaderStore {
26
+ /** Lifecycle-filtered finder: live rows only, like the A4 grant finder. */
27
+ findLiveConsent(key: ConsentKey): Promise<ReaderConsentRecord | undefined>;
28
+ /** A live row for the key converges: the existing row is returned, no second row or event. */
29
+ grantConsent(record: ReaderConsentRecord): Promise<ReaderConsentRecord>;
30
+ revokeConsent(key: ConsentKey, by: ConsentRevokedBy, at: string, audit: ConsentRevokeAudit): Promise<{
31
+ changed: boolean;
32
+ revokedAt?: string;
33
+ }>;
34
+ /**
35
+ * Self or admin revocation of every live row of one artifact, optionally
36
+ * restricted to one scope across all its versions (the MCP `scope`
37
+ * argument names a scope, never a version). Omitted scope revokes all.
38
+ */
39
+ revokeAllConsents(key: Omit<ConsentKey, 'scopeId' | 'scopeVersion'> & {
40
+ scopeId?: string;
41
+ }, by: ConsentRevokedBy, at: string, audit: ConsentRevokeAudit): Promise<{
42
+ changed: boolean;
43
+ revoked: number;
44
+ }>;
45
+ /** All states, `grantedAt` then bytewise `consentId` ordering. */
46
+ listConsentsForReader(scope: string, reader: string): Promise<readonly ReaderConsentRecord[]>;
47
+ /** Append-only audit without content, same transaction as the mutation. */
48
+ listConsentEvents(scope: string, artifactId: string): Promise<readonly ReaderConsentEvent[]>;
49
+ purgeForArtifact(scope: string, artifactId: string): Promise<void>;
50
+ purgeByPrincipal(scope: string, principalId: string): Promise<{
51
+ consents: number;
52
+ kv: number;
53
+ docs: number;
54
+ }>;
55
+ exportByPrincipal(scope: string, principalId: string): Promise<PrincipalDataExport>;
56
+ }
57
+ /** In-memory double: single process, synchronous mutation plus audit, no clock (callers stamp). */
58
+ export declare function createMemoryReaderConsentStore(): ArtifactReaderStore;