@sentropic/artifacts 0.2.12 → 0.2.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/CHANGELOG.md +67 -0
  2. package/README.md +45 -10
  3. package/dist/adapters/postgres-management.js +3 -2
  4. package/dist/adapters/postgres-reader-consent.d.ts +11 -0
  5. package/dist/adapters/postgres-reader-consent.js +109 -0
  6. package/dist/adapters/postgres.js +4 -3
  7. package/dist/adapters/s3-uploads.d.ts +33 -0
  8. package/dist/adapters/s3-uploads.js +105 -0
  9. package/dist/content/headers.js +12 -0
  10. package/dist/http.d.ts +16 -2
  11. package/dist/http.js +325 -12
  12. package/dist/mcp-core.d.ts +3 -3
  13. package/dist/mcp-core.js +51 -4
  14. package/dist/profile/contracts.d.ts +1 -1
  15. package/dist/profile/contracts.js +3 -0
  16. package/dist/profile/index.js +33 -2
  17. package/dist/profile/radar.js +7 -0
  18. package/dist/profile/schemas.js +59 -0
  19. package/dist/profile/validation.d.ts +11 -0
  20. package/dist/profile/validation.js +71 -6
  21. package/dist/server/access.d.ts +2 -0
  22. package/dist/server/command-identity.d.ts +1 -1
  23. package/dist/server/command-identity.js +5 -3
  24. package/dist/server/consent.d.ts +65 -0
  25. package/dist/server/consent.js +42 -0
  26. package/dist/server/gc.d.ts +17 -0
  27. package/dist/server/gc.js +22 -0
  28. package/dist/server/management.d.ts +3 -1
  29. package/dist/server/management.js +48 -7
  30. package/dist/server/mime.d.ts +26 -2
  31. package/dist/server/mime.js +124 -2
  32. package/dist/server/ports.d.ts +29 -0
  33. package/dist/server/ports.js +11 -0
  34. package/dist/server/publication-limits.d.ts +12 -0
  35. package/dist/server/publication-limits.js +19 -1
  36. package/dist/server/publication.d.ts +9 -0
  37. package/dist/server/publication.js +4 -2
  38. package/dist/server/reader-store.d.ts +58 -0
  39. package/dist/server/reader-store.js +109 -0
  40. package/dist/server/templates.js +50 -2
  41. package/dist/server/uploads.d.ts +154 -18
  42. package/dist/server/uploads.js +227 -80
  43. package/migrations/0007_uploads.sql +43 -0
  44. package/migrations/0008_reader_consent.sql +48 -0
  45. package/package.json +22 -1
  46. package/sql/reader-consent.sql +47 -0
@@ -1,32 +1,168 @@
1
- export interface BlobRef {
2
- digest: string;
3
- size: number;
1
+ export declare const UPLOAD_URL_TTL_SECONDS = 600;
2
+ export declare const UPLOAD_SESSION_TTL_MS: number;
3
+ export type UploadSessionState = 'open' | 'committed' | 'discarded' | 'expired';
4
+ export interface UploadSession {
5
+ readonly uploadId: string;
6
+ readonly artifactId: string;
7
+ readonly storageScopeId: string;
8
+ readonly ownerId: string;
9
+ readonly mimeType: string;
10
+ readonly maxSize: number;
11
+ readonly state: UploadSessionState;
12
+ readonly expiresAt: string;
13
+ readonly createdAt: string;
14
+ }
15
+ export interface StagedFileRecord {
16
+ readonly uploadId: string;
17
+ readonly artifactId: string;
18
+ readonly path: string;
19
+ readonly mimeType: string;
20
+ readonly digest: string;
21
+ readonly size: number;
22
+ readonly createdAt: string;
23
+ }
24
+ /** Durable session ledger (Postgres in the host via migration 0007; memory double in tests). */
25
+ export interface UploadSessionStore {
26
+ create(session: UploadSession): Promise<void>;
27
+ get(uploadId: string): Promise<UploadSession | undefined>;
28
+ /** Open sessions of one principal in one scope (quota check). */
29
+ countOpen(storageScopeId: string, ownerId: string): Promise<number>;
30
+ /** Sessions still open whose expires_at passed (sweeper input). */
31
+ listExpiredOpen(now: Date): Promise<UploadSession[]>;
32
+ markCommitted(uploadId: string): Promise<void>;
33
+ markExpired(uploadId: string): Promise<void>;
34
+ recordStagedFile(record: StagedFileRecord): Promise<void>;
35
+ getStagedFile(uploadId: string): Promise<StagedFileRecord | undefined>;
36
+ listStagedFiles(artifactId: string): Promise<StagedFileRecord[]>;
4
37
  }
38
+ /** Byte store under the staging prefix (S3 in the host; memory double in tests). */
5
39
  export interface StagingStore {
6
- write(uploadId: string, bytes: Uint8Array): Promise<void>;
7
- read(uploadId: string): Promise<Uint8Array>;
8
- discard(uploadId: string): Promise<void>;
40
+ put(key: string, bytes: Uint8Array): Promise<void>;
41
+ get(key: string): Promise<Uint8Array | undefined>;
42
+ delete(key: string): Promise<void>;
43
+ listKeys(prefix: string): Promise<string[]>;
9
44
  }
45
+ /**
46
+ * Presigner port. The signature binds content-type, the EXACT content-length
47
+ * (declared size) and, when known at signing time, x-amz-checksum-sha256;
48
+ * no content-length range exists in a SigV4 presigned PUT (review finding 3).
49
+ */
50
+ export interface UploadSignerPort {
51
+ signPut(input: {
52
+ key: string;
53
+ contentType: string;
54
+ contentLength: number;
55
+ /** Canonical `sha256:<hex>` digest, when known at signing time. */
56
+ checksumSha256?: string;
57
+ expiresInSeconds: number;
58
+ }): Promise<{
59
+ url: string;
60
+ method: 'PUT';
61
+ /** Headers the client must send with exactly these values. */
62
+ headers: Record<string, string>;
63
+ expiresAt: string;
64
+ }>;
65
+ }
66
+ export declare const STAGING_KEY_PATTERN: RegExp;
67
+ /** Staging key of one upload session. */
68
+ export declare function stagingKey(storageScopeId: string, uploadId: string): string;
69
+ /**
70
+ * Value of the `x-amz-checksum-sha256` header for a canonical `sha256:<hex>`
71
+ * digest: S3 expects the base64 of the raw digest bytes (no `sha256:` prefix).
72
+ */
73
+ export declare function checksumHeaderValue(digest: string): string;
74
+ /** Reject anything but a staging key, before any I/O. */
75
+ export declare function assertStagingKey(key: string): void;
76
+ /** Reject empty or escaping staging prefixes before enumeration. */
77
+ export declare function assertStagingPrefix(prefix: string): void;
10
78
  /** In-memory StagingStore double for unit tests. */
11
79
  export declare function createMemoryStaging(): StagingStore;
12
- export interface BeginUploadInput {
80
+ /** In-memory UploadSessionStore double for unit tests. */
81
+ export declare function createMemoryUploadSessionStore(now?: () => Date): UploadSessionStore;
82
+ /**
83
+ * Memory signer double: records every signed PUT and simulates S3's
84
+ * enforcement of the signed headers (exact content-length equality) and of
85
+ * the checksum header (body must hash to it when present).
86
+ */
87
+ export declare function createMemoryUploadSigner(): {
88
+ signer: UploadSignerPort;
89
+ signed: {
90
+ key: string;
91
+ contentType: string;
92
+ contentLength: number;
93
+ checksumSha256?: string | undefined;
94
+ expiresAt: string;
95
+ url: string;
96
+ }[];
97
+ /** Simulate the client PUT against "S3": signed headers are enforced exactly. */
98
+ put(signedPut: {
99
+ key: string;
100
+ contentType: string;
101
+ contentLength: number;
102
+ checksumSha256?: string;
103
+ }, bytes: Uint8Array, headers: Record<string, string>): void;
104
+ };
105
+ export interface CreateUploadInput {
106
+ artifactId: string;
107
+ storageScopeId: string;
108
+ ownerId: string;
13
109
  mimeType: string;
110
+ /** Declared size; clamped to the host budget. Bound as the exact signed Content-Length. */
14
111
  maxSize?: number;
15
112
  }
113
+ export interface CreateUploadResult {
114
+ uploadId: string;
115
+ uploadUrl: string;
116
+ method: 'PUT';
117
+ /** Presigned-URL expiry (≤ 10 minutes). */
118
+ expiresAt: string;
119
+ maxSize: number;
120
+ /** Headers the client must send with exactly these values (bound by the signature). */
121
+ requiredHeaders: Record<string, string>;
122
+ /**
123
+ * The PUT must also carry this header with the base64 SHA-256 of the body;
124
+ * S3 validates it against the body (BadDigest on mismatch) and commit
125
+ * re-verifies size and digest server-side.
126
+ */
127
+ checksumHeader: 'x-amz-checksum-sha256';
128
+ stagingKey: string;
129
+ }
130
+ export interface CommitUploadInput {
131
+ uploadId: string;
132
+ artifactId: string;
133
+ storageScopeId: string;
134
+ ownerId: string;
135
+ path: string;
136
+ mimeType: string;
137
+ digest: string;
138
+ size: number;
139
+ }
16
140
  export interface UploadServiceOptions {
141
+ /** Host ceiling for one upload (min of profile releaseFileBytesMax and the server maximum). */
17
142
  maxUploadBytes: number;
143
+ maxSessionsPerPrincipal: number;
144
+ now?: () => Date;
145
+ ids?: () => string;
18
146
  }
19
147
  export interface UploadService {
20
- begin(input: BeginUploadInput): Promise<{
21
- uploadId: string;
22
- }>;
23
- /** Check that the session is open and optionally validate its sequential offset before decoding. */
24
- remainingBytes(uploadId: string, offset?: number): number;
25
- append(uploadId: string, offset: number, chunk: Uint8Array): Promise<{
148
+ create(input: CreateUploadInput): Promise<CreateUploadResult>;
149
+ /**
150
+ * Load the session for commit: must exist, be open, unexpired and bound to
151
+ * the same artifact + scope + owner. Returns the session (caller reads the
152
+ * staged bytes once and verifies size/digest/MIME before pinning).
153
+ */
154
+ sessionForCommit(input: CommitUploadInput): Promise<UploadSession>;
155
+ /** Verify the staged bytes against the declared size, digest and MIME type. */
156
+ verifyStaged(session: UploadSession, bytes: Uint8Array, expected: {
157
+ digest: string;
26
158
  size: number;
27
- }>;
28
- /** Validate the commit snapshot before consuming the session; rejected validation remains retryable. */
29
- commit(uploadId: string, expected: BlobRef, validate?: (bytes: Uint8Array) => void): Promise<BlobRef>;
159
+ mimeType: string;
160
+ }): void;
161
+ /** Record the staged file and close the session after a successful promotion. */
162
+ completeCommit(session: UploadSession, record: Omit<StagedFileRecord, 'uploadId' | 'artifactId' | 'createdAt'>): Promise<StagedFileRecord>;
30
163
  }
31
- /** Create an upload service over an injected staging store (no S3 imports). */
32
- export declare function createUploadService(staging: StagingStore, options: UploadServiceOptions, ids?: () => string): UploadService;
164
+ export declare function createUploadService(deps: {
165
+ sessions: UploadSessionStore;
166
+ staging: StagingStore;
167
+ signer: UploadSignerPort;
168
+ }, options: UploadServiceOptions): UploadService;
@@ -1,114 +1,261 @@
1
1
  /**
2
- * L-5b — bounded uploads (spec-v8 §9).
2
+ * Files parity LOT 1 — durable upload sessions with a presigned signed PUT
3
+ * (design-r1 §B.3, review finding 3 applied).
3
4
  *
4
- * Uploads stage bytes under a bounded prefix with a strict size budget and
5
- * sequential offsets. Commit verifies the staged bytes against the declared
6
- * SHA-256 digest and size before returning a blob reference; false
7
- * hashes/sizes, over-budget appends, out-of-order offsets and any write
8
- * after commit are refused fail-closed. Staging is ephemeral: sessions live
9
- * in memory and never become visible releases (publication owns durability
10
- * via object intents). The byte store is injected; the memory double serves
11
- * unit tests and the S3 adapter serves the L-5b integration proof.
5
+ * Bytes never travel through the model or the MCP host: `create_upload`
6
+ * mints a presigned PUT for exactly one staging key
7
+ * `artifacts/<scope>/staging/<uploadId>`; the local agent performs the PUT;
8
+ * `commit_upload` re-reads the staged object once and verifies the declared
9
+ * size and SHA-256 digest before anything is pinned.
10
+ *
11
+ * SigV4 note (review finding 3): a presigned PUT cannot carry a
12
+ * content-length RANGE (that exists only in POST policies), so the signature
13
+ * binds an EXACT Content-Length (the declared size) plus the checksum header
14
+ * (`x-amz-checksum-sha256`) whenever the digest is known at signing time;
15
+ * S3 itself rejects a PUT whose signed headers do not match. The digest is
16
+ * declared at commit, so the create-time signature binds content-type +
17
+ * exact content-length, the PUT must carry `x-amz-checksum-sha256` (S3
18
+ * validates it against the body, BadDigest on mismatch), and commit
19
+ * re-verifies size and digest server-side before pinning. Residual exposure
20
+ * of a leaked URL is bounded by the declared size (≤ 16 MiB), the
21
+ * per-principal open-session quota and the enforced sweeper (gc.ts).
22
+ *
23
+ * Sessions are durable rows (migration 0007 ALTERs `artifacts.uploads`);
24
+ * the byte store, session store and signer are injected ports — the memory
25
+ * doubles serve unit tests, the S3 adapter serves the host.
12
26
  */
13
27
  import { createHash } from 'node:crypto';
28
+ import { validateFileBytes } from './mime.js';
29
+ export const UPLOAD_URL_TTL_SECONDS = 600; // presigned URL: ≤ 10 minutes
30
+ export const UPLOAD_SESSION_TTL_MS = 24 * 60 * 60 * 1000; // staged file: 24 h
31
+ export const STAGING_KEY_PATTERN = /^artifacts\/[A-Za-z0-9_-]+\/staging\/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
32
+ /** Staging key of one upload session. */
33
+ export function stagingKey(storageScopeId, uploadId) {
34
+ return `artifacts/${storageScopeId}/staging/${uploadId}`;
35
+ }
36
+ /**
37
+ * Value of the `x-amz-checksum-sha256` header for a canonical `sha256:<hex>`
38
+ * digest: S3 expects the base64 of the raw digest bytes (no `sha256:` prefix).
39
+ */
40
+ export function checksumHeaderValue(digest) {
41
+ const match = /^sha256:([0-9a-f]{64})$/.exec(digest);
42
+ if (match === null)
43
+ throw new Error(`invalid sha256 digest: ${digest}`);
44
+ return Buffer.from(match[1], 'hex').toString('base64');
45
+ }
46
+ /** Reject anything but a staging key, before any I/O. */
47
+ export function assertStagingKey(key) {
48
+ if (!STAGING_KEY_PATTERN.test(key)) {
49
+ throw new Error(`invalid staging key (must be artifacts/<scope>/staging/<uuid>): ${key}`);
50
+ }
51
+ }
52
+ /** Reject empty or escaping staging prefixes before enumeration. */
53
+ export function assertStagingPrefix(prefix) {
54
+ if (prefix.length === 0 || prefix.includes('..') || !prefix.endsWith('/staging/')) {
55
+ throw new Error(`invalid staging prefix: ${prefix}`);
56
+ }
57
+ }
14
58
  /** In-memory StagingStore double for unit tests. */
15
59
  export function createMemoryStaging() {
16
60
  const staged = new Map();
17
61
  return {
18
- write(uploadId, bytes) {
19
- staged.set(uploadId, bytes);
62
+ put(key, bytes) {
63
+ assertStagingKey(key);
64
+ staged.set(key, new Uint8Array(bytes));
65
+ return Promise.resolve();
66
+ },
67
+ get(key) {
68
+ assertStagingKey(key);
69
+ const bytes = staged.get(key);
70
+ return Promise.resolve(bytes === undefined ? undefined : new Uint8Array(bytes));
71
+ },
72
+ delete(key) {
73
+ assertStagingKey(key);
74
+ staged.delete(key);
75
+ return Promise.resolve();
76
+ },
77
+ listKeys(prefix) {
78
+ assertStagingPrefix(prefix);
79
+ return Promise.resolve([...staged.keys()].filter((key) => key.startsWith(prefix)).sort());
80
+ },
81
+ };
82
+ }
83
+ /** In-memory UploadSessionStore double for unit tests. */
84
+ export function createMemoryUploadSessionStore(now = () => new Date()) {
85
+ const sessions = new Map();
86
+ const stagedFiles = new Map();
87
+ return {
88
+ create(session) {
89
+ sessions.set(session.uploadId, session);
90
+ return Promise.resolve();
91
+ },
92
+ get(uploadId) {
93
+ return Promise.resolve(sessions.get(uploadId));
94
+ },
95
+ countOpen(storageScopeId, ownerId) {
96
+ let count = 0;
97
+ for (const session of sessions.values()) {
98
+ if (session.storageScopeId === storageScopeId && session.ownerId === ownerId && session.state === 'open')
99
+ count += 1;
100
+ }
101
+ return Promise.resolve(count);
102
+ },
103
+ listExpiredOpen(at) {
104
+ return Promise.resolve([...sessions.values()].filter((session) => session.state === 'open' && new Date(session.expiresAt).getTime() <= at.getTime()).sort());
105
+ },
106
+ markCommitted(uploadId) {
107
+ const session = sessions.get(uploadId);
108
+ if (session === undefined)
109
+ throw new Error(`unknown upload: ${uploadId}`);
110
+ sessions.set(uploadId, { ...session, state: 'committed' });
20
111
  return Promise.resolve();
21
112
  },
22
- read(uploadId) {
23
- const bytes = staged.get(uploadId);
24
- if (bytes === undefined)
113
+ markExpired(uploadId) {
114
+ const session = sessions.get(uploadId);
115
+ if (session === undefined)
25
116
  throw new Error(`unknown upload: ${uploadId}`);
26
- return Promise.resolve(bytes);
117
+ sessions.set(uploadId, { ...session, state: 'expired' });
118
+ return Promise.resolve();
27
119
  },
28
- discard(uploadId) {
29
- staged.delete(uploadId);
120
+ recordStagedFile(record) {
121
+ stagedFiles.set(record.uploadId, record);
30
122
  return Promise.resolve();
31
123
  },
124
+ getStagedFile(uploadId) {
125
+ return Promise.resolve(stagedFiles.get(uploadId));
126
+ },
127
+ listStagedFiles(artifactId) {
128
+ return Promise.resolve([...stagedFiles.values()].filter((record) => record.artifactId === artifactId));
129
+ },
32
130
  };
33
131
  }
34
- /** Create an upload service over an injected staging store (no S3 imports). */
35
- export function createUploadService(staging, options, ids = () => crypto.randomUUID()) {
132
+ /**
133
+ * Memory signer double: records every signed PUT and simulates S3's
134
+ * enforcement of the signed headers (exact content-length equality) and of
135
+ * the checksum header (body must hash to it when present).
136
+ */
137
+ export function createMemoryUploadSigner() {
138
+ const signed = [];
139
+ const signer = {
140
+ signPut(input) {
141
+ assertStagingKey(input.key);
142
+ if (!Number.isSafeInteger(input.contentLength) || input.contentLength < 0) {
143
+ throw new Error('invalid signed content-length');
144
+ }
145
+ const expiresAt = new Date(Date.now() + input.expiresInSeconds * 1000).toISOString();
146
+ const url = `https://s3.test/${input.key}?X-Amz-Signature=mem-${signed.length}`;
147
+ const checksumHeader = input.checksumSha256 === undefined ? undefined : checksumHeaderValue(input.checksumSha256);
148
+ signed.push({ key: input.key, contentType: input.contentType, contentLength: input.contentLength,
149
+ ...(checksumHeader === undefined ? {} : { checksumSha256: checksumHeader }),
150
+ expiresAt, url });
151
+ return Promise.resolve({
152
+ url,
153
+ method: 'PUT',
154
+ headers: {
155
+ 'content-type': input.contentType,
156
+ 'content-length': String(input.contentLength),
157
+ ...(checksumHeader === undefined ? {} : { 'x-amz-checksum-sha256': checksumHeader }),
158
+ },
159
+ expiresAt,
160
+ });
161
+ },
162
+ };
163
+ return {
164
+ signer,
165
+ signed,
166
+ /** Simulate the client PUT against "S3": signed headers are enforced exactly. */
167
+ put(signedPut, bytes, headers) {
168
+ if (String(bytes.length) !== headers['content-length'] || bytes.length !== signedPut.contentLength) {
169
+ throw new Error(`content-length mismatch: signed ${signedPut.contentLength}, body ${bytes.length}`);
170
+ }
171
+ if (headers['content-type'] !== signedPut.contentType) {
172
+ throw new Error('content-type mismatch with the signed header');
173
+ }
174
+ if (signedPut.checksumSha256 !== undefined && headers['x-amz-checksum-sha256'] !== signedPut.checksumSha256) {
175
+ throw new Error('x-amz-checksum-sha256 mismatch with the signed header');
176
+ }
177
+ if (headers['x-amz-checksum-sha256'] !== undefined &&
178
+ createHash('sha256').update(bytes).digest('base64') !== headers['x-amz-checksum-sha256']) {
179
+ throw new Error('BadDigest: body does not match x-amz-checksum-sha256');
180
+ }
181
+ },
182
+ };
183
+ }
184
+ export function createUploadService(deps, options) {
185
+ const now = options.now ?? (() => new Date());
186
+ const ids = options.ids ?? (() => crypto.randomUUID());
36
187
  if (!Number.isSafeInteger(options.maxUploadBytes) || options.maxUploadBytes < 1) {
37
188
  throw new Error('invalid upload byte budget');
38
189
  }
39
- const sessions = new Map();
40
- function openSession(uploadId) {
41
- const session = sessions.get(uploadId);
42
- if (session === undefined)
43
- throw new Error(`unknown upload: ${uploadId}`);
44
- if (session.committed)
45
- throw new Error(`upload already committed: ${uploadId}`);
46
- if (session.busy)
47
- throw new Error(`upload conflict: operation in progress for ${uploadId}`);
48
- return session;
49
- }
50
- async function exclusive(uploadId, run) {
51
- const session = openSession(uploadId);
52
- session.busy = true;
53
- try {
54
- return await run(session);
55
- }
56
- finally {
57
- session.busy = false;
58
- }
59
- }
60
- function remainingBytes(uploadId, offset) {
61
- const session = openSession(uploadId);
62
- if (offset !== undefined && (!Number.isSafeInteger(offset) || offset !== session.size)) {
63
- throw new Error(`upload offset mismatch for ${uploadId}: expected ${session.size}, got ${offset}`);
64
- }
65
- return session.maxSize - session.size;
190
+ if (!Number.isSafeInteger(options.maxSessionsPerPrincipal) || options.maxSessionsPerPrincipal < 1) {
191
+ throw new Error('invalid upload session quota');
66
192
  }
67
193
  return {
68
- remainingBytes,
69
- async begin(input) {
194
+ async create(input) {
70
195
  if (input.maxSize !== undefined && (!Number.isSafeInteger(input.maxSize) || input.maxSize < 1)) {
71
196
  throw new Error('invalid upload byte budget');
72
197
  }
198
+ const open = await deps.sessions.countOpen(input.storageScopeId, input.ownerId);
199
+ if (open >= options.maxSessionsPerPrincipal) {
200
+ throw new Error(`open upload session quota exceeded for principal (max ${options.maxSessionsPerPrincipal})`);
201
+ }
202
+ const maxSize = Math.min(input.maxSize ?? options.maxUploadBytes, options.maxUploadBytes);
73
203
  const uploadId = ids();
74
- sessions.set(uploadId, {
75
- committed: false,
76
- busy: false,
77
- maxSize: Math.min(input.maxSize ?? options.maxUploadBytes, options.maxUploadBytes),
78
- size: 0,
204
+ const createdAt = now().toISOString();
205
+ const expiresAt = new Date(now().getTime() + UPLOAD_SESSION_TTL_MS).toISOString();
206
+ const key = stagingKey(input.storageScopeId, uploadId);
207
+ await deps.sessions.create({
208
+ uploadId, artifactId: input.artifactId, storageScopeId: input.storageScopeId,
209
+ ownerId: input.ownerId, mimeType: input.mimeType, maxSize, state: 'open', expiresAt, createdAt,
79
210
  });
80
- await staging.write(uploadId, new Uint8Array(0));
81
- return { uploadId };
82
- },
83
- async append(uploadId, offset, chunk) {
84
- const remaining = remainingBytes(uploadId, offset);
85
- return exclusive(uploadId, async (session) => {
86
- if (chunk.length > remaining) {
87
- throw new Error(`upload budget exceeded for ${uploadId}: max ${session.maxSize} bytes`);
88
- }
89
- const current = await staging.read(uploadId);
90
- const next = new Uint8Array(current.length + chunk.length);
91
- next.set(current, 0);
92
- next.set(chunk, current.length);
93
- await staging.write(uploadId, next);
94
- session.size = next.length;
95
- return { size: session.size };
211
+ // The signature binds content-type and the EXACT declared Content-Length
212
+ // (a presigned PUT cannot carry a content-length range). The digest is
213
+ // declared at commit, so the PUT must also carry x-amz-checksum-sha256,
214
+ // which S3 validates against the body; commit re-verifies both.
215
+ const signed = await deps.signer.signPut({
216
+ key, contentType: input.mimeType, contentLength: maxSize, expiresInSeconds: UPLOAD_URL_TTL_SECONDS,
96
217
  });
218
+ return {
219
+ uploadId, uploadUrl: signed.url, method: signed.method, expiresAt: signed.expiresAt, maxSize,
220
+ requiredHeaders: signed.headers, checksumHeader: 'x-amz-checksum-sha256',
221
+ stagingKey: key,
222
+ };
97
223
  },
98
- async commit(uploadId, expected, validate) {
99
- return exclusive(uploadId, async (session) => {
100
- const bytes = new Uint8Array(await staging.read(uploadId));
101
- validate?.(bytes);
102
- if (bytes.length !== expected.size) {
103
- throw new Error(`upload size mismatch for ${uploadId}: staged ${bytes.length}, declared ${expected.size}`);
224
+ sessionForCommit(input) {
225
+ return deps.sessions.get(input.uploadId).then((session) => {
226
+ if (session === undefined || session.artifactId !== input.artifactId ||
227
+ session.storageScopeId !== input.storageScopeId || session.ownerId !== input.ownerId) {
228
+ throw new Error(`unknown upload for this artifact/owner/scope: ${input.uploadId}`);
104
229
  }
105
- const actual = `sha256:${createHash('sha256').update(bytes).digest('hex')}`;
106
- if (actual !== expected.digest) {
107
- throw new Error(`upload digest mismatch for ${uploadId}: staged ${actual}`);
230
+ if (session.state !== 'open')
231
+ throw new Error(`upload not open (${session.state}): ${input.uploadId}`);
232
+ if (new Date(session.expiresAt).getTime() <= now().getTime()) {
233
+ throw new Error(`upload session expired: ${input.uploadId}`);
108
234
  }
109
- session.committed = true;
110
- return { digest: actual, size: bytes.length };
235
+ return session;
111
236
  });
112
237
  },
238
+ verifyStaged(session, bytes, expected) {
239
+ if (bytes.length !== expected.size) {
240
+ throw new Error(`upload size mismatch for ${session.uploadId}: staged ${bytes.length}, declared ${expected.size}`);
241
+ }
242
+ const actual = `sha256:${createHash('sha256').update(bytes).digest('hex')}`;
243
+ if (actual !== expected.digest) {
244
+ throw new Error(`upload digest mismatch for ${session.uploadId}: staged ${actual}`);
245
+ }
246
+ if (expected.mimeType !== session.mimeType) {
247
+ throw new Error(`upload MIME mismatch for ${session.uploadId}: session ${session.mimeType}, declared ${expected.mimeType}`);
248
+ }
249
+ validateFileBytes(expected.mimeType, bytes);
250
+ },
251
+ async completeCommit(session, record) {
252
+ const staged = {
253
+ uploadId: session.uploadId, artifactId: session.artifactId, createdAt: now().toISOString(),
254
+ path: record.path, mimeType: record.mimeType, digest: record.digest, size: record.size,
255
+ };
256
+ await deps.sessions.recordStagedFile(staged);
257
+ await deps.sessions.markCommitted(session.uploadId);
258
+ return staged;
259
+ },
113
260
  };
114
261
  }
@@ -0,0 +1,43 @@
1
+ -- Files parity LOT 1 — durable upload sessions (design-r1 §B.3, review
2
+ -- files-design-large4_r1 finding 1: 0001 already creates artifacts.uploads,
3
+ -- so this migration ALTERs it instead of recreating it).
4
+ --
5
+ -- 0001's uploads table was an ephemeral staging ledger (id, max_size, size,
6
+ -- mime_type, state, created_at) with no artifact binding and no expiry. LOT 1
7
+ -- binds every session to its artifact, storage scope and owner, adds
8
+ -- expires_at for the enforced staging sweeper (gc.ts), and adds the
9
+ -- staged-file records that commit_upload writes and publish_bundle
10
+ -- references. Pre-existing rows belong to the never-wired append surface:
11
+ -- they are discarded (not deleted) so no stale session stays open.
12
+
13
+ ALTER TABLE artifacts.uploads
14
+ ADD COLUMN IF NOT EXISTS artifact_id UUID REFERENCES artifacts.artifacts (id) ON DELETE CASCADE,
15
+ ADD COLUMN IF NOT EXISTS storage_scope_id TEXT REFERENCES artifacts.storage_scopes (id),
16
+ ADD COLUMN IF NOT EXISTS owner_id TEXT,
17
+ ADD COLUMN IF NOT EXISTS expires_at TIMESTAMPTZ;
18
+
19
+ -- Pre-existing rows have no artifact binding: close them, keep the audit trail.
20
+ UPDATE artifacts.uploads SET state = 'discarded' WHERE artifact_id IS NULL;
21
+
22
+ -- 'expired' is set by the sweeper when expires_at passes with the session open.
23
+ ALTER TABLE artifacts.uploads DROP CONSTRAINT IF EXISTS uploads_state_check;
24
+ ALTER TABLE artifacts.uploads
25
+ ADD CONSTRAINT uploads_state_check CHECK (state IN ('open', 'committed', 'discarded', 'expired'));
26
+
27
+ CREATE INDEX IF NOT EXISTS uploads_by_expiry ON artifacts.uploads (state, expires_at)
28
+ WHERE state = 'open';
29
+
30
+ -- Staged files: one row per committed upload, referenced by publish_bundle
31
+ -- assets ({path, uploadId}). The blob itself is content-addressed under
32
+ -- artifacts/<scope>/blobs/sha256/<hex>; this row carries the manifest path.
33
+ CREATE TABLE IF NOT EXISTS artifacts.staged_files (
34
+ upload_id UUID PRIMARY KEY REFERENCES artifacts.uploads (id) ON DELETE CASCADE,
35
+ artifact_id UUID NOT NULL REFERENCES artifacts.artifacts (id) ON DELETE CASCADE,
36
+ path TEXT NOT NULL,
37
+ mime_type TEXT NOT NULL,
38
+ digest TEXT NOT NULL CHECK (digest ~ '^sha256:[0-9a-f]{64}$'),
39
+ size INTEGER NOT NULL CHECK (size >= 0),
40
+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
41
+ UNIQUE (artifact_id, path)
42
+ );
43
+ CREATE INDEX IF NOT EXISTS staged_files_by_artifact ON artifacts.staged_files (artifact_id);
@@ -0,0 +1,48 @@
1
+ -- Train 2026-11-04 — persistent reader consent, lot 1a (wagon C).
2
+ --
3
+ -- Train-numbered wrapper of packages/artifacts/sql/reader-consent.sql:
4
+ -- wagon lanes never pre-assign migration numbers, so the train assigns the
5
+ -- next additive number at land time. The statements below are identical to
6
+ -- the reviewed lot-1a body (consent rows authorize a data class; they never
7
+ -- record data use: no basket identifier, no query, no page data, no
8
+ -- session/device/network data). Additive only: IF NOT EXISTS guards, no
9
+ -- nullable owner column participates in uniqueness, storage_scope_id is part
10
+ -- of every unique key so isolation is structural.
11
+
12
+ CREATE TABLE IF NOT EXISTS artifacts.reader_consents (
13
+ consent_id UUID PRIMARY KEY,
14
+ storage_scope_id TEXT NOT NULL,
15
+ reader_account_id TEXT NOT NULL,
16
+ artifact_id UUID NOT NULL REFERENCES artifacts.artifacts (id) ON DELETE CASCADE,
17
+ scope_id TEXT NOT NULL,
18
+ scope_version TEXT NOT NULL,
19
+ granted_at TIMESTAMPTZ NOT NULL DEFAULT now(),
20
+ granted_via TEXT NOT NULL DEFAULT 'reader_screen' CHECK (granted_via = 'reader_screen'),
21
+ revoked_at TIMESTAMPTZ NULL,
22
+ revoked_by TEXT NULL CHECK (revoked_by IN ('self', 'admin', 'cascade'))
23
+ );
24
+
25
+ -- At most one live row per (scope, reader, artifact, scope, version);
26
+ -- re-grant after revoke mints a new row, history stays auditable.
27
+ CREATE UNIQUE INDEX IF NOT EXISTS reader_consents_live_uniq ON artifacts.reader_consents
28
+ (storage_scope_id, reader_account_id, artifact_id, scope_id, scope_version)
29
+ WHERE revoked_at IS NULL;
30
+ CREATE INDEX IF NOT EXISTS reader_consents_by_reader ON artifacts.reader_consents
31
+ (storage_scope_id, reader_account_id, granted_at, consent_id);
32
+
33
+ -- Append-only audit, no content (actor, surface and version only).
34
+ CREATE TABLE IF NOT EXISTS artifacts.reader_consent_events (
35
+ id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
36
+ consent_id UUID NOT NULL,
37
+ storage_scope_id TEXT NOT NULL,
38
+ reader_account_id TEXT NOT NULL,
39
+ artifact_id UUID NOT NULL,
40
+ scope_id TEXT NOT NULL,
41
+ scope_version TEXT NOT NULL,
42
+ action TEXT NOT NULL CHECK (action IN ('grant', 'revoke')),
43
+ actor TEXT NOT NULL,
44
+ surface TEXT NOT NULL CHECK (surface IN ('screen', 'api', 'mcp', 'cascade')),
45
+ created_at TIMESTAMPTZ NOT NULL DEFAULT now()
46
+ );
47
+ CREATE INDEX IF NOT EXISTS reader_consent_events_by_artifact ON artifacts.reader_consent_events
48
+ (storage_scope_id, artifact_id, id);