@sentropic/artifacts 0.2.12 → 0.2.14

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 (74) hide show
  1. package/CHANGELOG.md +93 -0
  2. package/README.md +45 -10
  3. package/dist/adapters/local-blob.d.ts +3 -0
  4. package/dist/adapters/local-blob.js +93 -0
  5. package/dist/adapters/postgres-management.js +3 -2
  6. package/dist/adapters/postgres-reader-consent.d.ts +11 -0
  7. package/dist/adapters/postgres-reader-consent.js +109 -0
  8. package/dist/adapters/postgres-uploads.d.ts +14 -0
  9. package/dist/adapters/postgres-uploads.js +174 -0
  10. package/dist/adapters/postgres.js +4 -3
  11. package/dist/adapters/s3-uploads.d.ts +33 -0
  12. package/dist/adapters/s3-uploads.js +105 -0
  13. package/dist/adapters/s3.js +23 -0
  14. package/dist/adapters/sqlite-activation.d.ts +20 -0
  15. package/dist/adapters/sqlite-activation.js +205 -0
  16. package/dist/adapters/sqlite-commit.d.ts +15 -0
  17. package/dist/adapters/sqlite-commit.js +89 -0
  18. package/dist/adapters/sqlite-management.d.ts +10 -0
  19. package/dist/adapters/sqlite-management.js +60 -0
  20. package/dist/adapters/sqlite-sql.d.ts +32 -0
  21. package/dist/adapters/sqlite-sql.js +36 -0
  22. package/dist/adapters/sqlite-store.d.ts +12 -0
  23. package/dist/adapters/sqlite-store.js +410 -0
  24. package/dist/adapters/sqlite.d.ts +33 -0
  25. package/dist/adapters/sqlite.js +95 -0
  26. package/dist/content/handler.d.ts +5 -0
  27. package/dist/content/handler.js +80 -9
  28. package/dist/content/headers.js +12 -0
  29. package/dist/http.d.ts +32 -2
  30. package/dist/http.js +615 -13
  31. package/dist/mcp-core.d.ts +3 -3
  32. package/dist/mcp-core.js +90 -4
  33. package/dist/profile/contracts.d.ts +1 -1
  34. package/dist/profile/contracts.js +7 -0
  35. package/dist/profile/index.js +43 -2
  36. package/dist/profile/radar.js +7 -0
  37. package/dist/profile/schemas.js +119 -0
  38. package/dist/profile/validation.d.ts +11 -0
  39. package/dist/profile/validation.js +98 -6
  40. package/dist/server/access.d.ts +2 -0
  41. package/dist/server/command-identity.d.ts +1 -1
  42. package/dist/server/command-identity.js +6 -3
  43. package/dist/server/consent.d.ts +65 -0
  44. package/dist/server/consent.js +42 -0
  45. package/dist/server/gc.d.ts +42 -0
  46. package/dist/server/gc.js +98 -0
  47. package/dist/server/management.d.ts +3 -1
  48. package/dist/server/management.js +48 -7
  49. package/dist/server/metrics.d.ts +21 -0
  50. package/dist/server/metrics.js +6 -0
  51. package/dist/server/mime.d.ts +26 -2
  52. package/dist/server/mime.js +124 -2
  53. package/dist/server/ports.d.ts +29 -0
  54. package/dist/server/ports.js +11 -0
  55. package/dist/server/publication-limits.d.ts +20 -0
  56. package/dist/server/publication-limits.js +27 -1
  57. package/dist/server/publication.d.ts +14 -0
  58. package/dist/server/publication.js +10 -2
  59. package/dist/server/reader-store.d.ts +58 -0
  60. package/dist/server/reader-store.js +109 -0
  61. package/dist/server/source-read.d.ts +12 -9
  62. package/dist/server/source-read.js +17 -5
  63. package/dist/server/templates.js +50 -2
  64. package/dist/server/upload-page.d.ts +157 -0
  65. package/dist/server/upload-page.js +438 -0
  66. package/dist/server/uploads.d.ts +229 -19
  67. package/dist/server/uploads.js +387 -80
  68. package/migrations/0007_uploads.sql +43 -0
  69. package/migrations/0008_reader_consent.sql +48 -0
  70. package/migrations/0009_upload_pages.sql +25 -0
  71. package/package.json +34 -1
  72. package/sql/reader-consent.sql +47 -0
  73. package/sql/sqlite/0001_artifacts.sql +156 -0
  74. package/sql/sqlite/0002_activation.sql +73 -0
package/CHANGELOG.md CHANGED
@@ -1,5 +1,98 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.2.14
4
+
5
+ - Add a durable local SQLite adapter set behind the new `./sqlite` subpath export:
6
+ `sqlite.ts`, `sqlite-store.ts`, `sqlite-commit.ts`, `sqlite-management.ts`,
7
+ `sqlite-activation.ts` and `local-blob.ts` implement the same port interfaces as
8
+ the Postgres adapters and the S3 blob store, backed by the builtin `node:sqlite`
9
+ driver (no new dependency) and the local filesystem with sha256 digest
10
+ verification on put, get and strict delete.
11
+ - Cover bindings, intents, idempotency, ACL, lifecycle, publication state, refcounts,
12
+ the commit coordinator with the same transactional semantics and release CAS, and
13
+ the activation store. Multi-statement units run in one serialized writer
14
+ transaction (`BEGIN IMMEDIATE`); that isolation is stronger than the Postgres
15
+ READ COMMITTED baseline while the observable port behaviour is unchanged.
16
+ - Prove parity with one parameterized conformance suite executed against both the
17
+ Postgres and the SQLite backends, including restart durability, concurrent
18
+ writers, CAS conflicts and the refcount/GC edges.
19
+ - The root and portable entries stay free of `node:sqlite` and `better-sqlite3`;
20
+ import the local adapters only through `@sentropic/artifacts/sqlite`.
21
+ - Artifacts 0.2.14 stays inside the cluster-mesh peer range `>=0.2.0 <0.3.0`;
22
+ the API keeps its pinned APP-P1 profile digest and requalifies the APP-P1
23
+ manifest digest for this version.
24
+ - Union fix on the train: the SQLite management unit, store ACL paths and the
25
+ `artifact_access_events` audit table follow the G2 sharing port
26
+ (`SetAccessOutput.accessMode`/`changed`, `recordEvent`, authoritative
27
+ `access_mode` with `is_public` as projection).
28
+
29
+ ## 0.2.13
30
+
31
+ - G2 MCP sharing tools: new read-only tools `artifacts_lookup_people`
32
+ (approved-caller guard, directory search returning opaque `userRef`s with
33
+ masked `emailHint`s, homonyms never silently resolved) and
34
+ `artifacts_list_access` (mode, owner, grant list; readers see only their own
35
+ entry; admin management visibility exception). Both ship with static,
36
+ frozen-at-publication definitions; every pre-existing tool definition keeps
37
+ its exact bytes (CI tools/list snapshot extended to the new tools).
38
+ - New `PrincipalDirectoryPort` (search, `userRef` → internal resolution,
39
+ inverse projection). `artifacts_set_access` accepts opaque `userRef`s in
40
+ `principalId` alongside the `sentropic:` sentinels; resolution happens inside
41
+ the commit transaction after visibility and the management right, so the
42
+ `commandHash` (computed on the payload as provided) never leaks a resolution.
43
+ - Every model-visible output is projected through the directory: `ownerId` and
44
+ `grants[].principalId` of `artifacts_get`/`artifacts_list`/`artifacts_ensure`,
45
+ the `artifacts_set_access` receipt, and both new tools — no internal
46
+ principal id or full email reaches a model payload. Without a port, the new
47
+ tools answer `capability_unavailable` (sentinels keep working).
48
+ - Single `person_not_shareable` 422 error merging the four non-shareable
49
+ causes (unknown, inactive, unapproved, out-of-scope), evaluated at §2.3 step
50
+ 4 after visibility and the management right; grant rows gain `createdAt`
51
+ (read from the existing `artifact_access.created_at`, no new migration).
52
+ - Shipped radar profile gains the `set_access`, `lookup_people` and
53
+ `list_access` operation profiles (the four-tool radar selection itself is
54
+ unchanged).
55
+ - Files parity LOT 1: a local agent can publish large dossiers with the bytes
56
+ outside the model. New tools `artifacts_create_upload`,
57
+ `artifacts_commit_upload` and `artifacts_publish_bundle` (static
58
+ definitions, frozen at birth; the 17 pre-existing tool definitions are
59
+ byte-identical, pinned by sha256 in the tests).
60
+ - Upload sessions are durable rows (migration `0007_uploads.sql` ALTERs the
61
+ existing `artifacts.uploads` table: artifact/scope/owner binding,
62
+ `expires_at`, `staged_files`) with a presigned signed PUT per session. A
63
+ SigV4 presigned PUT cannot carry a content-length range, so the signature
64
+ binds the EXACT declared Content-Length plus `content-type`, the PUT must
65
+ carry `x-amz-checksum-sha256` (S3 validates the body, BadDigest on
66
+ mismatch), and `commit_upload` re-verifies size, SHA-256 digest and MIME
67
+ server-side before pinning. Open sessions per principal are quota-bounded
68
+ (8) and an enforced sweeper (gc.ts) expires stale sessions and deletes their
69
+ staging objects.
70
+ - Server maxima are hard ceilings: 255 files per release, 16 MiB per file,
71
+ 64 MiB per release; profile limit keys (`releaseFilesMax`,
72
+ `releaseFileBytesMax`, `releaseTotalBytesMax` on the publish operation) may
73
+ only move below them and default to the inline values. The MIME ceiling
74
+ (17 types) is enforced at profile compile time, and every file — inline or
75
+ uploaded — is validated at commit: magic bytes for binary types, strict
76
+ UTF-8 for text, script/handler/external-reference-free SVG.
77
+ - `artifacts_publish_bundle` publishes one atomic release from the union of
78
+ inline files, `{path, uploadId}` assets and `{path, digest, size, mimeType}`
79
+ CAS assets, reusing the 0.2.12 bounded blob pool and `verifyStagedBlobs`;
80
+ one missing or digest-mismatched asset fails the whole publish and commits
81
+ nothing. The strict-profile writer ban does not cover the upload tools (they
82
+ mutate no release pointer). `artifacts_get_source` keeps its frozen
83
+ maxItems 32 ceiling; server-side caps only move below the frozen schema.
84
+ - Persistent reader consent (lot 1a): consent rows per (reader account,
85
+ artifact, scope, scope version) with a pure evaluator and Gate B helper;
86
+ the reader screen is skipped only when a live consent at the current scope
87
+ version meets fresh rights, suspension or withdrawn share refuses despite
88
+ consent. One new MCP tool `artifacts_revoke_reader_consent`
89
+ (self-revocation only, static definition frozen at birth; the 17
90
+ pre-existing tool definitions are byte-identical) plus control-origin
91
+ list/revoke API routes; revocation takes effect on the next call. Host
92
+ migration `0008_reader_consent.sql` (additive, train-numbered from the
93
+ reviewed `sql/reader-consent.sql` body); immo screen binding and silent
94
+ renew land in lot 1b.
95
+
3
96
  ## 0.2.12
4
97
 
5
98
  - Bounded concurrency in multi-file publication blob staging (#art-conc, P1):
package/README.md CHANGED
@@ -227,21 +227,53 @@ Keys are isolated by operation and
227
227
  principal. A changed payload under the same key returns an explicit conflict.
228
228
  Persisted unscoped replay keys are no longer consulted after upgrading.
229
229
 
230
- Publication defaults to 128 files, 16 MiB per file and 64 MiB total. Hosts can
230
+ Publication defaults to 255 files, 16 MiB per file and 64 MiB total. Hosts can
231
231
  override these positive integer limits through `createPublicationService({
232
232
  limits: { maxFiles, maxFileBytes, maxTotalBytes } })`; the HTTP decoder uses the
233
- same byte budgets before allocating bytes. Paths must be unique canonical
233
+ same byte budgets before allocating bytes. These profile values are bounded by
234
+ generic server maxima — 255 files per release, 16 MiB per file, 64 MiB per
235
+ release — enforced both when a profile is compiled and again in
236
+ `publicationLimits`, so a profile can only narrow them, never exceed them.
237
+ Paths must be unique canonical
234
238
  relative paths, at most 1024 UTF-8 bytes: empty/dot segments, backslashes,
235
239
  percent escapes, URL delimiters, colons and control characters are rejected.
236
240
  Existing integrations using larger bundles or noncanonical paths must adjust
237
241
  their limits or filenames. Invalid publications fail before object-store effects.
238
- Upload sessions cap client `maxSize` by the host `maxUploadBytes` and publication
239
- file/total limits. Every append checks remaining cumulative capacity before
240
- decoding bytes or writing staging. Upload publication metadata is validated
241
- before the session is consumed; a rejected path or MIME type can be corrected
242
- and committed using the same staged bytes. Finalization validates, hashes and
243
- publishes one copied snapshot. Overlapping append/commit operations return 409;
244
- failed verification or metadata validation leaves the session retryable.
242
+
243
+ Two budgets exist because inline MCP bytes cost model tokens while uploaded
244
+ bytes do not: the inline keys (`publishFilesMax`, `maxDecodedFileBytes`,
245
+ `maxDecodedTotalBytes`) bound what travels inside `artifacts_publish` and the
246
+ inline `files` of `artifacts_publish_bundle`, while the release keys
247
+ (`releaseFilesMax`, `releaseFileBytesMax`, `releaseTotalBytesMax` on the same
248
+ publish operation) bound the final release however its files arrived; absent
249
+ release keys default to the inline values.
250
+
251
+ ## Uploading files outside the model (signed PUT)
252
+
253
+ Large or binary files never travel through the model or the MCP payload:
254
+ `artifacts_create_upload` mints a presigned PUT for exactly one staging key
255
+ `artifacts/<scope>/staging/<uploadId>` (URL expiry ≤ 10 minutes). A SigV4
256
+ presigned PUT cannot carry a content-length range, so the signature binds the
257
+ content type and the exact declared `Content-Length` (`maxSize`, itself capped
258
+ by the release per-file limit and the 16 MiB server ceiling); the PUT must also
259
+ carry `x-amz-checksum-sha256` (base64 SHA-256 of the body), which S3 validates
260
+ against the body (`BadDigest` on mismatch). The local agent performs the PUT
261
+ with exactly the returned `requiredHeaders`. Open sessions per principal are
262
+ capped (server maximum 8); stale sessions are expired by the enforced sweeper
263
+ in `gc.ts` (`createUploadSweeper`, driven by `uploads.expires_at`).
264
+ `artifacts_commit_upload` then declares `{path, mimeType, digest, size}`; the
265
+ server re-reads the staged object once and re-verifies size, SHA-256 digest and
266
+ MIME (magic bytes, strict UTF-8, SVG script/handler/href rules) before
267
+ promoting the bytes to the digest-addressed blob store
268
+ (`artifacts/<scope>/blobs/sha256/<hex>`) through the bounded blob pool with
269
+ read-back verification, and pinning them with reason `upload:<uploadId>`.
270
+ A wrong size or digest is refused with `verification_failed` (422) and nothing
271
+ is pinned; commit alone creates no release. `artifacts_publish_bundle` finally
272
+ publishes one atomic release from inline `files` and/or `assets` (each asset
273
+ `{path, uploadId}` or `{path, digest, size, mimeType}` referencing an
274
+ already-pinned blob of the same scope); `expectedCurrentReleaseId` is always
275
+ required, the release budget applies to the union, and one missing or
276
+ mismatched asset fails the whole publish before anything commits.
245
277
 
246
278
  Content `HEAD` responses have the corresponding GET headers and no body,
247
279
  including errors and activation. Errors and activation responses include the
@@ -457,7 +489,10 @@ Size and digest are verified on the raw bytes, then each file is encoded for the
457
489
  wire: text mime types as `text` with `encoding: "utf8"`, all other files as
458
490
  `base64` with `encoding: "base64"` — never an integer array. The result carries
459
491
  a `guideRef` (`{tool, version}`) instead of the guide body. The snapshot is
460
- limited to 32 files and 262144 decoded bytes. Hosts must qualify
492
+ limited to 32 files and 262144 decoded bytes: that ceiling is part of the
493
+ frozen `artifacts_get_source` tool definition and does not move; server-side
494
+ caps may only go below it, and larger listings belong to dedicated listing
495
+ tools. Hosts must qualify
461
496
  a 2 MiB serialized MCP result budget before selecting this capability.
462
497
 
463
498
  `POST /set_access` grants or revokes a named principal's read access, requires a
@@ -0,0 +1,3 @@
1
+ import type { PublicationBlobStore } from '../server/publication.js';
2
+ /** Create a filesystem-backed blob store rooted at `root` (created on demand). */
3
+ export declare function createLocalBlobStore(root: string): PublicationBlobStore;
@@ -0,0 +1,93 @@
1
+ /**
2
+ * U1 — local filesystem PublicationBlobStore, the local equivalent of
3
+ * `createS3BlobStore`. Same key discipline (only
4
+ * `artifacts/<scope>/blobs/sha256/<64 hex>`, hostile keys refused before any
5
+ * I/O, prefix listing sorted, absent reads undefined), plus what S3 cannot
6
+ * offer locally: sha256 digest verification of the stored bytes on put AND
7
+ * read-back, atomic temp-file+rename writes, and strict deletes (unknown keys
8
+ * fail so callers notice, per the port contract).
9
+ */
10
+ import { createHash } from 'node:crypto';
11
+ import { existsSync, mkdirSync, readdirSync, readFileSync, renameSync, rmSync, unlinkSync, writeFileSync } from 'node:fs';
12
+ import { dirname, join } from 'node:path';
13
+ import { blobDigestOfKey } from '../server/publication.js';
14
+ import { assertBlobPrefix } from '../server/blob-prefix.js';
15
+ const BLOB_KEY_PATTERN = /^artifacts\/[A-Za-z0-9_-]+\/blobs\/sha256\/[0-9a-f]{64}$/;
16
+ /** Reject anything but digest-addressed blob keys, before any I/O. */
17
+ function assertBlobKey(key) {
18
+ if (!BLOB_KEY_PATTERN.test(key)) {
19
+ throw new Error(`invalid blob key (must be artifacts/<scope>/blobs/sha256/<hex>): ${key}`);
20
+ }
21
+ }
22
+ function sha256Hex(bytes) {
23
+ return createHash('sha256').update(bytes).digest('hex');
24
+ }
25
+ /** Create a filesystem-backed blob store rooted at `root` (created on demand). */
26
+ export function createLocalBlobStore(root) {
27
+ const pathOf = (key) => join(root, ...key.split('/'));
28
+ const walk = (dir, prefix, out) => {
29
+ if (!existsSync(dir))
30
+ return;
31
+ for (const entry of readdirSync(dir, { withFileTypes: true })) {
32
+ const full = join(dir, entry.name);
33
+ if (entry.isDirectory()) {
34
+ walk(full, `${prefix}${entry.name}/`, out);
35
+ }
36
+ else if (entry.isFile()) {
37
+ out.push(`${prefix}${entry.name}`);
38
+ }
39
+ }
40
+ };
41
+ return {
42
+ async putBlob(key, bytes) {
43
+ assertBlobKey(key);
44
+ const expected = blobDigestOfKey(key).slice('sha256:'.length);
45
+ const actual = sha256Hex(bytes);
46
+ if (actual !== expected) {
47
+ throw new Error(`digest mismatch for blob key ${key}: content sha256:${actual}`);
48
+ }
49
+ const target = pathOf(key);
50
+ mkdirSync(dirname(target), { recursive: true });
51
+ const temp = `${target}.tmp-${process.pid}-${Math.random().toString(36).slice(2)}`;
52
+ writeFileSync(temp, bytes);
53
+ renameSync(temp, target);
54
+ },
55
+ async getBlob(key) {
56
+ assertBlobKey(key);
57
+ const target = pathOf(key);
58
+ if (!existsSync(target))
59
+ return undefined;
60
+ const bytes = new Uint8Array(readFileSync(target));
61
+ const expected = blobDigestOfKey(key).slice('sha256:'.length);
62
+ const actual = sha256Hex(bytes);
63
+ if (actual !== expected) {
64
+ throw new Error(`digest mismatch on read for blob key ${key}: stored sha256:${actual}`);
65
+ }
66
+ return bytes;
67
+ },
68
+ async listKeys(prefix) {
69
+ assertBlobPrefix(prefix);
70
+ const keys = [];
71
+ walk(root, '', keys);
72
+ return keys.filter((key) => key.startsWith(prefix)).sort();
73
+ },
74
+ async deleteBlob(key) {
75
+ assertBlobKey(key);
76
+ const target = pathOf(key);
77
+ if (!existsSync(target))
78
+ throw new Error(`unknown blob: ${key}`);
79
+ unlinkSync(target);
80
+ // Best-effort prune of now-empty directories up to the root.
81
+ let dir = dirname(target);
82
+ while (dir.startsWith(root) && dir !== root) {
83
+ try {
84
+ rmSync(dir, { recursive: false });
85
+ }
86
+ catch {
87
+ break;
88
+ }
89
+ dir = dirname(dir);
90
+ }
91
+ },
92
+ };
93
+ }
@@ -2,8 +2,9 @@ import { applyModeTransition, PLATFORM_PRINCIPAL, PUBLIC_PRINCIPAL } from '../se
2
2
  /** Parent lock serializes ACL inserts, lifecycle changes and publication FKs. */
3
3
  export function createPostgresManagementUnit(client) {
4
4
  const listGrants = async (id) => {
5
- const { rows } = await client.query('SELECT principal_id, permission FROM artifacts.artifact_access WHERE artifact_id = $1 ORDER BY principal_id', [id]);
6
- return rows.map((row) => ({ principalId: row.principal_id, grant: row.permission }));
5
+ const { rows } = await client.query('SELECT principal_id, permission, created_at FROM artifacts.artifact_access WHERE artifact_id = $1 ORDER BY principal_id', [id]);
6
+ return rows.map((row) => ({ principalId: row.principal_id, grant: row.permission,
7
+ createdAt: row.created_at.toISOString() }));
7
8
  };
8
9
  return {
9
10
  async lock(id) {
@@ -0,0 +1,11 @@
1
+ /**
2
+ * Lot 1a — reference Postgres adapter for the reader consent slice
3
+ * (design-merged §1.2, §3.1). Over an injected pg Pool, no DDL at runtime
4
+ * (the train numbers `sql/reader-consent.sql` at land time). Every mutation
5
+ * runs with its audit event in one transaction: a rollback removes the grant
6
+ * plus the event.
7
+ */
8
+ import type { Pool } from 'pg';
9
+ import type { ArtifactReaderStore } from '../server/reader-store.js';
10
+ /** Reference adapter; the tables come from the train-numbered migration. */
11
+ export declare function createPostgresReaderConsentStore(pool: Pool): ArtifactReaderStore;
@@ -0,0 +1,109 @@
1
+ import { assertConsentScopeId, assertConsentScopeVersion } from '../server/consent.js';
2
+ const toRecord = (row) => ({ consentId: row.consent_id,
3
+ storageScopeId: row.storage_scope_id, readerAccountId: row.reader_account_id, artifactId: row.artifact_id,
4
+ scopeId: row.scope_id, scopeVersion: row.scope_version, grantedAt: row.granted_at.toISOString(),
5
+ grantedVia: row.granted_via, ...(row.revoked_at === null ? {} : { revokedAt: row.revoked_at.toISOString() }),
6
+ ...(row.revoked_by === null ? {} : { revokedBy: row.revoked_by }) });
7
+ const LIVE_WHERE = `storage_scope_id = $1 AND reader_account_id = $2 AND artifact_id = $3
8
+ AND scope_id = $4 AND scope_version = $5 AND revoked_at IS NULL`;
9
+ async function tx(pool, work) {
10
+ const client = await pool.connect();
11
+ try {
12
+ await client.query('BEGIN');
13
+ try {
14
+ const result = await work(client);
15
+ await client.query('COMMIT');
16
+ return result;
17
+ }
18
+ catch (error) {
19
+ await client.query('ROLLBACK').catch(() => undefined);
20
+ throw error;
21
+ }
22
+ }
23
+ finally {
24
+ client.release();
25
+ }
26
+ }
27
+ const INSERT_EVENT = `INSERT INTO artifacts.reader_consent_events (consent_id, storage_scope_id,
28
+ reader_account_id, artifact_id, scope_id, scope_version, action, actor, surface, created_at)
29
+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)`;
30
+ /** Reference adapter; the tables come from the train-numbered migration. */
31
+ export function createPostgresReaderConsentStore(pool) {
32
+ return {
33
+ async findLiveConsent(key) {
34
+ const { rows } = await pool.query(`SELECT * FROM artifacts.reader_consents WHERE ${LIVE_WHERE}`, [key.storageScopeId, key.readerAccountId, key.artifactId, key.scopeId, key.scopeVersion]);
35
+ return rows[0] === undefined ? undefined : toRecord(rows[0]);
36
+ },
37
+ async grantConsent(record) {
38
+ assertConsentScopeId(record.scopeId);
39
+ assertConsentScopeVersion(record.scopeVersion);
40
+ return tx(pool, async (client) => {
41
+ const live = await client.query(`SELECT * FROM artifacts.reader_consents WHERE ${LIVE_WHERE} FOR UPDATE`, [record.storageScopeId, record.readerAccountId, record.artifactId, record.scopeId, record.scopeVersion]);
42
+ if (live.rows[0] !== undefined)
43
+ return toRecord(live.rows[0]);
44
+ await client.query(`INSERT INTO artifacts.reader_consents (consent_id, storage_scope_id, reader_account_id,
45
+ artifact_id, scope_id, scope_version, granted_at, granted_via)
46
+ VALUES ($1, $2, $3, $4, $5, $6, $7, 'reader_screen')`, [record.consentId, record.storageScopeId, record.readerAccountId, record.artifactId,
47
+ record.scopeId, record.scopeVersion, record.grantedAt]);
48
+ await client.query(INSERT_EVENT, [record.consentId, record.storageScopeId, record.readerAccountId,
49
+ record.artifactId, record.scopeId, record.scopeVersion, 'grant', record.readerAccountId, 'screen', record.grantedAt]);
50
+ return { ...record };
51
+ });
52
+ },
53
+ async revokeConsent(key, by, at, audit) {
54
+ return tx(pool, async (client) => {
55
+ const live = await client.query(`SELECT * FROM artifacts.reader_consents WHERE ${LIVE_WHERE} FOR UPDATE`, [key.storageScopeId, key.readerAccountId, key.artifactId, key.scopeId, key.scopeVersion]);
56
+ if (live.rows[0] === undefined)
57
+ return { changed: false };
58
+ await client.query(`UPDATE artifacts.reader_consents SET revoked_at = $1, revoked_by = $2 WHERE consent_id = $3`, [at, by, live.rows[0].consent_id]);
59
+ await client.query(INSERT_EVENT, [live.rows[0].consent_id, key.storageScopeId, key.readerAccountId,
60
+ key.artifactId, key.scopeId, key.scopeVersion, 'revoke', audit.actor, audit.surface, at]);
61
+ return { changed: true, revokedAt: at };
62
+ });
63
+ },
64
+ async revokeAllConsents(key, by, at, audit) {
65
+ return tx(pool, async (client) => {
66
+ const { rows } = await client.query(`SELECT * FROM artifacts.reader_consents
67
+ WHERE storage_scope_id = $1 AND reader_account_id = $2 AND artifact_id = $3
68
+ AND ($4::text IS NULL OR scope_id = $4) AND revoked_at IS NULL FOR UPDATE`, [key.storageScopeId, key.readerAccountId, key.artifactId, key.scopeId ?? null]);
69
+ for (const row of rows) {
70
+ await client.query(`UPDATE artifacts.reader_consents SET revoked_at = $1, revoked_by = $2 WHERE consent_id = $3`, [at, by, row.consent_id]);
71
+ await client.query(INSERT_EVENT, [row.consent_id, row.storage_scope_id, row.reader_account_id,
72
+ row.artifact_id, row.scope_id, row.scope_version, 'revoke', audit.actor, audit.surface, at]);
73
+ }
74
+ return { changed: rows.length > 0, revoked: rows.length };
75
+ });
76
+ },
77
+ async listConsentsForReader(scope, reader) {
78
+ const { rows } = await pool.query(`SELECT * FROM artifacts.reader_consents
79
+ WHERE storage_scope_id = $1 AND reader_account_id = $2 ORDER BY granted_at, consent_id`, [scope, reader]);
80
+ return rows.map(toRecord);
81
+ },
82
+ async listConsentEvents(scope, artifactId) {
83
+ const { rows } = await pool.query(`SELECT consent_id AS "consentId", storage_scope_id AS "storageScopeId",
84
+ reader_account_id AS "readerAccountId", artifact_id AS "artifactId", scope_id AS "scopeId",
85
+ scope_version AS "scopeVersion", action, actor, surface, created_at FROM artifacts.reader_consent_events
86
+ WHERE storage_scope_id = $1 AND artifact_id = $2 ORDER BY id`, [scope, artifactId]);
87
+ return rows.map((row) => ({ consentId: row.consentId, storageScopeId: row.storageScopeId,
88
+ readerAccountId: row.readerAccountId, artifactId: row.artifactId, scopeId: row.scopeId,
89
+ scopeVersion: row.scopeVersion, action: row.action,
90
+ actor: row.actor, surface: row.surface, at: row.created_at.toISOString() }));
91
+ },
92
+ async purgeForArtifact(scope, artifactId) {
93
+ await tx(pool, async (client) => {
94
+ await client.query(`DELETE FROM artifacts.reader_consent_events WHERE storage_scope_id = $1 AND artifact_id = $2`, [scope, artifactId]);
95
+ await client.query(`DELETE FROM artifacts.reader_consents WHERE storage_scope_id = $1 AND artifact_id = $2`, [scope, artifactId]);
96
+ });
97
+ },
98
+ async purgeByPrincipal(scope, principalId) {
99
+ return tx(pool, async (client) => {
100
+ await client.query(`DELETE FROM artifacts.reader_consent_events WHERE storage_scope_id = $1 AND reader_account_id = $2`, [scope, principalId]);
101
+ const removed = await client.query(`DELETE FROM artifacts.reader_consents WHERE storage_scope_id = $1 AND reader_account_id = $2`, [scope, principalId]);
102
+ return { consents: removed.rowCount ?? 0, kv: 0, docs: 0 };
103
+ });
104
+ },
105
+ async exportByPrincipal(scope, principalId) {
106
+ return { consents: await this.listConsentsForReader(scope, principalId), kv: [], meDocs: [], sharedWriteRefs: [] };
107
+ },
108
+ };
109
+ }
@@ -0,0 +1,14 @@
1
+ /**
2
+ * Files parity LOT 2 §A.5 — Postgres upload session store over the 0007 +
3
+ * 0009 tables (mirrors the reader-consent adapter shape). Over an injected pg
4
+ * Pool: no eager connections, no DDL at runtime. Quota-critical writes run in
5
+ * one transaction holding the per-scope advisory lock, so the check and the
6
+ * insert stay paired under concurrency.
7
+ */
8
+ import type { Pool } from 'pg';
9
+ import type { UploadSessionStore } from '../server/uploads.js';
10
+ import type { UploadPageStore } from '../server/upload-page.js';
11
+ /** Postgres upload session ledger; quota writes hold the scope advisory lock. */
12
+ export declare function createPostgresUploadSessionStore(pool: Pool): UploadSessionStore;
13
+ /** Postgres upload-page rows over the 0009 table; rows are kept after expiry. */
14
+ export declare function createPostgresUploadPageStore(pool: Pool): UploadPageStore;
@@ -0,0 +1,174 @@
1
+ async function tx(pool, work) {
2
+ const client = await pool.connect();
3
+ try {
4
+ await client.query('BEGIN');
5
+ try {
6
+ const result = await work(client);
7
+ await client.query('COMMIT');
8
+ return result;
9
+ }
10
+ catch (error) {
11
+ await client.query('ROLLBACK').catch(() => undefined);
12
+ throw error;
13
+ }
14
+ }
15
+ finally {
16
+ client.release();
17
+ }
18
+ }
19
+ const toSession = (row) => ({
20
+ uploadId: row.id,
21
+ artifactId: row.artifact_id ?? '',
22
+ storageScopeId: row.storage_scope_id ?? '',
23
+ ownerId: row.owner_id ?? '',
24
+ mimeType: row.mime_type,
25
+ maxSize: row.max_size,
26
+ state: row.state,
27
+ expiresAt: (row.expires_at ?? row.created_at).toISOString(),
28
+ createdAt: row.created_at.toISOString(),
29
+ ...(row.page_session_id === null ? {} : { pageSessionId: row.page_session_id }),
30
+ });
31
+ const toStaged = (row) => ({
32
+ uploadId: row.upload_id,
33
+ artifactId: row.artifact_id,
34
+ path: row.path,
35
+ mimeType: row.mime_type,
36
+ digest: row.digest,
37
+ size: row.size,
38
+ createdAt: row.created_at.toISOString(),
39
+ });
40
+ function using(pool, db, inTx) {
41
+ return {
42
+ async create(session) {
43
+ await db.query(`INSERT INTO artifacts.uploads (id, artifact_id, storage_scope_id, owner_id, mime_type,
44
+ max_size, state, expires_at, created_at, page_session_id)
45
+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)`, [session.uploadId, session.artifactId, session.storageScopeId, session.ownerId,
46
+ session.mimeType, session.maxSize, session.state, session.expiresAt,
47
+ session.createdAt, session.pageSessionId ?? null]);
48
+ },
49
+ async get(uploadId) {
50
+ const { rows } = await db.query('SELECT * FROM artifacts.uploads WHERE id = $1', [uploadId]);
51
+ return rows[0] === undefined ? undefined : toSession(rows[0]);
52
+ },
53
+ async countOpen(storageScopeId, ownerId) {
54
+ const { rows } = await db.query(`SELECT COUNT(*) AS n FROM artifacts.uploads
55
+ WHERE storage_scope_id = $1 AND owner_id = $2 AND state = 'open'`, [storageScopeId, ownerId]);
56
+ return Number(rows[0]?.n ?? 0);
57
+ },
58
+ async listExpiredOpen(at) {
59
+ const { rows } = await db.query(`SELECT * FROM artifacts.uploads WHERE state = 'open' AND expires_at <= $1 ORDER BY expires_at, id`, [at.toISOString()]);
60
+ return rows.map(toSession);
61
+ },
62
+ async markCommitted(uploadId) {
63
+ const { rowCount } = await db.query(`UPDATE artifacts.uploads SET state = 'committed' WHERE id = $1`, [uploadId]);
64
+ if (rowCount === 0)
65
+ throw new Error(`unknown upload: ${uploadId}`);
66
+ },
67
+ async markExpired(uploadId) {
68
+ const { rowCount } = await db.query(`UPDATE artifacts.uploads SET state = 'expired' WHERE id = $1`, [uploadId]);
69
+ if (rowCount === 0)
70
+ throw new Error(`unknown upload: ${uploadId}`);
71
+ },
72
+ async recordStagedFile(record) {
73
+ await db.query(`INSERT INTO artifacts.staged_files (upload_id, artifact_id, path, mime_type, digest, size, created_at)
74
+ VALUES ($1, $2, $3, $4, $5, $6, $7)
75
+ ON CONFLICT (upload_id) DO UPDATE SET artifact_id = EXCLUDED.artifact_id, path = EXCLUDED.path,
76
+ mime_type = EXCLUDED.mime_type, digest = EXCLUDED.digest, size = EXCLUDED.size,
77
+ created_at = EXCLUDED.created_at`, [record.uploadId, record.artifactId, record.path, record.mimeType,
78
+ record.digest, record.size, record.createdAt]);
79
+ },
80
+ async getStagedFile(uploadId) {
81
+ const { rows } = await db.query('SELECT * FROM artifacts.staged_files WHERE upload_id = $1', [uploadId]);
82
+ return rows[0] === undefined ? undefined : toStaged(rows[0]);
83
+ },
84
+ async listStagedFiles(artifactId) {
85
+ const { rows } = await db.query('SELECT * FROM artifacts.staged_files WHERE artifact_id = $1 ORDER BY path', [artifactId]);
86
+ return rows.map(toStaged);
87
+ },
88
+ async sumOpenMaxSize(storageScopeId) {
89
+ const { rows } = await db.query(`SELECT COALESCE(SUM(max_size), 0) AS total FROM artifacts.uploads
90
+ WHERE storage_scope_id = $1 AND state = 'open'`, [storageScopeId]);
91
+ return Number(rows[0]?.total ?? 0);
92
+ },
93
+ async sumStagedBytesByScope(storageScopeId) {
94
+ const { rows } = await db.query(`SELECT COALESCE(SUM(s.size), 0) AS total FROM artifacts.staged_files s
95
+ JOIN artifacts.uploads u ON u.id = s.upload_id
96
+ WHERE u.storage_scope_id = $1`, [storageScopeId]);
97
+ return Number(rows[0]?.total ?? 0);
98
+ },
99
+ async listPageSessions(pageSessionId) {
100
+ const { rows } = await db.query('SELECT * FROM artifacts.uploads WHERE page_session_id = $1 ORDER BY created_at, id', [pageSessionId]);
101
+ return rows.map(toSession);
102
+ },
103
+ withScopeLock(storageScopeId, action) {
104
+ // A tx-bound facade inherits the outer lock: never nest transactions.
105
+ if (inTx)
106
+ return action(using(pool, db, true));
107
+ return tx(pool, async (client) => {
108
+ await client.query('SELECT pg_advisory_xact_lock(hashtextextended($1, 0))', [`artifacts-uploads:${storageScopeId}`]);
109
+ return action(using(pool, client, true));
110
+ });
111
+ },
112
+ async listExpiredStaged(at, ttlMs) {
113
+ const cutoff = new Date(at.getTime() - ttlMs).toISOString();
114
+ const { rows } = await db.query('SELECT * FROM artifacts.staged_files WHERE created_at <= $1 ORDER BY created_at', [cutoff]);
115
+ return rows.map(toStaged);
116
+ },
117
+ async deleteStagedFile(uploadId) {
118
+ await db.query('DELETE FROM artifacts.staged_files WHERE upload_id = $1', [uploadId]);
119
+ },
120
+ };
121
+ }
122
+ /** Postgres upload session ledger; quota writes hold the scope advisory lock. */
123
+ export function createPostgresUploadSessionStore(pool) {
124
+ return using(pool, pool, false);
125
+ }
126
+ /** Postgres upload-page rows over the 0009 table; rows are kept after expiry. */
127
+ export function createPostgresUploadPageStore(pool) {
128
+ const toRow = (row) => ({
129
+ pageSessionId: row.id,
130
+ artifactId: row.artifact_id,
131
+ storageScopeId: row.storage_scope_id,
132
+ ownerId: row.owner_id,
133
+ tokenHash: row.token_hash,
134
+ state: row.state,
135
+ maxFiles: row.max_files,
136
+ createdAt: row.created_at.toISOString(),
137
+ expiresAt: row.expires_at.toISOString(),
138
+ ...(row.exchanged_at === null ? {} : { exchangedAt: row.exchanged_at.toISOString() }),
139
+ });
140
+ return {
141
+ async create(row) {
142
+ await pool.query(`INSERT INTO artifacts.upload_pages (id, artifact_id, storage_scope_id, owner_id,
143
+ token_hash, state, max_files, expires_at, created_at, exchanged_at)
144
+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)`, [row.pageSessionId, row.artifactId, row.storageScopeId, row.ownerId, row.tokenHash,
145
+ row.state, row.maxFiles, row.expiresAt, row.createdAt, row.exchangedAt ?? null]);
146
+ },
147
+ async get(pageSessionId) {
148
+ const { rows } = await pool.query('SELECT * FROM artifacts.upload_pages WHERE id = $1', [pageSessionId]);
149
+ return rows[0] === undefined ? undefined : toRow(rows[0]);
150
+ },
151
+ async countActiveByOwner(ownerId) {
152
+ const { rows } = await pool.query(`SELECT COUNT(*) AS n FROM artifacts.upload_pages
153
+ WHERE owner_id = $1 AND state IN ('open', 'exchanged')`, [ownerId]);
154
+ return Number(rows[0]?.n ?? 0);
155
+ },
156
+ async listExpiredPages(at) {
157
+ const { rows } = await pool.query(`SELECT * FROM artifacts.upload_pages
158
+ WHERE state IN ('open', 'exchanged') AND expires_at <= $1 ORDER BY expires_at`, [at.toISOString()]);
159
+ return rows.map(toRow);
160
+ },
161
+ async markExchanged(pageSessionId, at) {
162
+ const current = await pool.query('SELECT * FROM artifacts.upload_pages WHERE id = $1', [pageSessionId]);
163
+ if (current.rows[0] === undefined)
164
+ throw new Error(`unknown upload page: ${pageSessionId}`);
165
+ if (current.rows[0].state !== 'open') {
166
+ throw new Error(`upload page not open (${current.rows[0].state}): ${pageSessionId}`);
167
+ }
168
+ await pool.query(`UPDATE artifacts.upload_pages SET state = 'exchanged', exchanged_at = $2 WHERE id = $1`, [pageSessionId, at]);
169
+ },
170
+ async markExpired(pageSessionId) {
171
+ await pool.query(`UPDATE artifacts.upload_pages SET state = 'expired' WHERE id = $1`, [pageSessionId]);
172
+ },
173
+ };
174
+ }
@@ -202,7 +202,7 @@ export function createPostgresArtifactStore(pool) {
202
202
  const row = rows[0];
203
203
  if (row === undefined)
204
204
  return undefined;
205
- const grants = await pool.query(`SELECT principal_id, permission FROM artifacts.artifact_access
205
+ const grants = await pool.query(`SELECT principal_id, permission, created_at FROM artifacts.artifact_access
206
206
  WHERE artifact_id = $1 ORDER BY principal_id`, [artifactId]);
207
207
  // G1: access_mode is authoritative; is_public is its legacy projection.
208
208
  const accessMode = (row.access_mode ?? (row.is_public ? 'platform' : 'restricted'));
@@ -217,6 +217,7 @@ export function createPostgresArtifactStore(pool) {
217
217
  grants: grants.rows.map((grant) => ({
218
218
  principalId: grant.principal_id,
219
219
  grant: grant.permission,
220
+ createdAt: grant.created_at.toISOString(),
220
221
  })),
221
222
  ...(row.metadata === null || Object.keys(row.metadata).length === 0 ? {} : { metadata: row.metadata }),
222
223
  };
@@ -239,8 +240,8 @@ export function createPostgresArtifactStore(pool) {
239
240
  // the source guard on re-insert, so the stale source grant is demoted
240
241
  // to read — the grant row is kept, never dropped.
241
242
  const permission = grant.grant === 'source' && accessMode !== 'restricted' ? 'read' : grant.grant;
242
- await pool.query(`INSERT INTO artifacts.artifact_access (artifact_id, principal_id, permission)
243
- VALUES ($1, $2, $3)`, [artifactId, grant.principalId, permission]);
243
+ await pool.query(`INSERT INTO artifacts.artifact_access (artifact_id, principal_id, permission, created_at)
244
+ VALUES ($1, $2, $3, COALESCE($4::timestamptz, now()))`, [artifactId, grant.principalId, permission, grant.createdAt ?? null]);
244
245
  }
245
246
  },
246
247
  async listArtifactIds() {