@sentropic/artifacts 0.2.13 → 0.2.15

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 (52) hide show
  1. package/CHANGELOG.md +37 -0
  2. package/dist/adapters/local-blob.d.ts +3 -0
  3. package/dist/adapters/local-blob.js +93 -0
  4. package/dist/adapters/postgres-uploads.d.ts +14 -0
  5. package/dist/adapters/postgres-uploads.js +174 -0
  6. package/dist/adapters/s3.js +23 -0
  7. package/dist/adapters/sqlite-activation.d.ts +20 -0
  8. package/dist/adapters/sqlite-activation.js +205 -0
  9. package/dist/adapters/sqlite-commit.d.ts +15 -0
  10. package/dist/adapters/sqlite-commit.js +89 -0
  11. package/dist/adapters/sqlite-management.d.ts +10 -0
  12. package/dist/adapters/sqlite-management.js +60 -0
  13. package/dist/adapters/sqlite-sql.d.ts +32 -0
  14. package/dist/adapters/sqlite-sql.js +36 -0
  15. package/dist/adapters/sqlite-store.d.ts +12 -0
  16. package/dist/adapters/sqlite-store.js +410 -0
  17. package/dist/adapters/sqlite.d.ts +33 -0
  18. package/dist/adapters/sqlite.js +95 -0
  19. package/dist/content/handler.d.ts +5 -0
  20. package/dist/content/handler.js +80 -9
  21. package/dist/http.d.ts +16 -0
  22. package/dist/http.js +435 -97
  23. package/dist/mcp-core.d.ts +3 -3
  24. package/dist/mcp-core.js +43 -4
  25. package/dist/profile/contracts.d.ts +1 -1
  26. package/dist/profile/contracts.js +4 -0
  27. package/dist/profile/index.js +12 -2
  28. package/dist/profile/schemas.js +60 -0
  29. package/dist/profile/validation.js +31 -4
  30. package/dist/server/command-identity.d.ts +1 -1
  31. package/dist/server/command-identity.js +4 -3
  32. package/dist/server/gc.d.ts +28 -3
  33. package/dist/server/gc.js +81 -5
  34. package/dist/server/management.js +10 -5
  35. package/dist/server/metrics.d.ts +21 -0
  36. package/dist/server/metrics.js +6 -0
  37. package/dist/server/ports.d.ts +7 -0
  38. package/dist/server/ports.js +7 -0
  39. package/dist/server/publication-limits.d.ts +8 -0
  40. package/dist/server/publication-limits.js +8 -0
  41. package/dist/server/publication.d.ts +5 -0
  42. package/dist/server/publication.js +6 -0
  43. package/dist/server/source-read.d.ts +12 -9
  44. package/dist/server/source-read.js +17 -5
  45. package/dist/server/upload-page.d.ts +157 -0
  46. package/dist/server/upload-page.js +438 -0
  47. package/dist/server/uploads.d.ts +75 -1
  48. package/dist/server/uploads.js +187 -27
  49. package/migrations/0009_upload_pages.sql +25 -0
  50. package/package.json +13 -1
  51. package/sql/sqlite/0001_artifacts.sql +156 -0
  52. package/sql/sqlite/0002_activation.sql +73 -0
@@ -0,0 +1,33 @@
1
+ import type { CommitExecutor } from '../server/commit/types.js';
2
+ import type { PostgresArtifactStore } from './postgres.js';
3
+ import type { SqliteDatabase } from './sqlite-sql.js';
4
+ export type { SqliteDatabase, SqliteStatement } from './sqlite-sql.js';
5
+ export { normalizeSql, runQuery } from './sqlite-sql.js';
6
+ /** Serialized writer over the single connection (async mutex, not reentrant). */
7
+ export interface SqliteWriter {
8
+ /** Run work holding the writer; concurrent callers queue behind it. */
9
+ run<T>(work: () => T): Promise<T>;
10
+ /** run + BEGIN IMMEDIATE … COMMIT (ROLLBACK on throw): one atomic unit. */
11
+ tx<T>(work: () => T): Promise<T>;
12
+ /** Acquire the writer across awaits; the returned function releases it. */
13
+ acquire(): Promise<() => void>;
14
+ }
15
+ /** Open (creating if needed) a durable local database file and apply the DDL. */
16
+ export declare function openSqliteDatabase(path: string): SqliteDatabase;
17
+ /** Create the serialized writer over one database connection. */
18
+ export declare function createSqliteWriter(db: SqliteDatabase): SqliteWriter;
19
+ export type SqliteArtifactStore = PostgresArtifactStore;
20
+ import { createSqliteArtifactStore } from './sqlite-store.js';
21
+ import { createSqliteCommitExecutor } from './sqlite-commit.js';
22
+ export { createSqliteArtifactStore, createSqliteCommitExecutor };
23
+ export { createSqliteManagementUnit } from './sqlite-management.js';
24
+ export { createSqliteActivationStore, type SqliteActivationStore } from './sqlite-activation.js';
25
+ export { createLocalBlobStore } from './local-blob.js';
26
+ /** One-call wiring: open a file, create the writer, build store + executor. */
27
+ export declare function openSqliteArtifacts(path: string): {
28
+ db: SqliteDatabase;
29
+ writer: SqliteWriter;
30
+ store: SqliteArtifactStore;
31
+ executor: CommitExecutor;
32
+ close(): void;
33
+ };
@@ -0,0 +1,95 @@
1
+ /**
2
+ * U1 — local SQLite adapter set, entry point (`@sentropic/artifacts/sqlite`).
3
+ *
4
+ * Durable local equivalent of the Postgres adapters, over the repo-standard
5
+ * `node:sqlite` driver (same driver as cluster-mesh identity; no new native
6
+ * dependency). One connection per database file plus one serialized writer:
7
+ * every mutation runs through `SqliteWriter`, and multi-statement units run
8
+ * inside a single `BEGIN IMMEDIATE` transaction. SQLite then serializes
9
+ * writers — stronger isolation than the Postgres READ COMMITTED units, with
10
+ * the same observable port behaviour; there is no second behaviour. The
11
+ * 0004 terminal guards are enforced in adapter code because all writes are
12
+ * serialized (check-then-write is atomic). The root and portable entries
13
+ * never import this module: only the `./sqlite` subpath pulls in node:sqlite.
14
+ *
15
+ * Schema mapping: SQLite has no schemas, so Postgres `artifacts.<t>` /
16
+ * `artifact_host.<t>` map to plain `<t>` in the single file (DDL owned by
17
+ * this adapter: sql/sqlite/0001_artifacts.sql, sql/sqlite/0002_activation.sql).
18
+ */
19
+ import { readFileSync } from 'node:fs';
20
+ import { DatabaseSync } from 'node:sqlite';
21
+ export { normalizeSql, runQuery } from './sqlite-sql.js';
22
+ const DDL_ARTIFACTS = readFileSync(new URL('../../sql/sqlite/0001_artifacts.sql', import.meta.url), 'utf8');
23
+ const DDL_ACTIVATION = readFileSync(new URL('../../sql/sqlite/0002_activation.sql', import.meta.url), 'utf8');
24
+ /** Open (creating if needed) a durable local database file and apply the DDL. */
25
+ export function openSqliteDatabase(path) {
26
+ const db = new DatabaseSync(path);
27
+ db.exec('PRAGMA journal_mode = WAL');
28
+ db.exec('PRAGMA synchronous = FULL');
29
+ db.exec('PRAGMA foreign_keys = ON');
30
+ db.exec(DDL_ARTIFACTS);
31
+ db.exec(DDL_ACTIVATION);
32
+ return db;
33
+ }
34
+ /** Create the serialized writer over one database connection. */
35
+ export function createSqliteWriter(db) {
36
+ let tail = Promise.resolve();
37
+ const acquire = () => {
38
+ let release;
39
+ const gate = new Promise((resolve) => { release = resolve; });
40
+ const previous = tail;
41
+ tail = previous.then(() => gate);
42
+ return previous.then(() => release);
43
+ };
44
+ return {
45
+ acquire,
46
+ async run(work) {
47
+ const release = await acquire();
48
+ try {
49
+ return work();
50
+ }
51
+ finally {
52
+ release();
53
+ }
54
+ },
55
+ async tx(work) {
56
+ const release = await acquire();
57
+ try {
58
+ db.exec('BEGIN IMMEDIATE');
59
+ try {
60
+ const result = work();
61
+ db.exec('COMMIT');
62
+ return result;
63
+ }
64
+ catch (error) {
65
+ try {
66
+ db.exec('ROLLBACK');
67
+ }
68
+ catch { /* transaction already gone */ }
69
+ throw error;
70
+ }
71
+ }
72
+ finally {
73
+ release();
74
+ }
75
+ },
76
+ };
77
+ }
78
+ import { createSqliteArtifactStore } from './sqlite-store.js';
79
+ import { createSqliteCommitExecutor } from './sqlite-commit.js';
80
+ export { createSqliteArtifactStore, createSqliteCommitExecutor };
81
+ export { createSqliteManagementUnit } from './sqlite-management.js';
82
+ export { createSqliteActivationStore } from './sqlite-activation.js';
83
+ export { createLocalBlobStore } from './local-blob.js';
84
+ /** One-call wiring: open a file, create the writer, build store + executor. */
85
+ export function openSqliteArtifacts(path) {
86
+ const db = openSqliteDatabase(path);
87
+ const writer = createSqliteWriter(db);
88
+ return {
89
+ db,
90
+ writer,
91
+ store: createSqliteArtifactStore(db, writer),
92
+ executor: createSqliteCommitExecutor(db, writer),
93
+ close() { db.close(); },
94
+ };
95
+ }
@@ -1,4 +1,5 @@
1
1
  import type { AclStore } from '../server/access.js';
2
+ import type { ArtifactsMetrics } from '../server/metrics.js';
2
3
  import type { LifecycleService } from '../server/lifecycle.js';
3
4
  import { type SharingPolicyPort } from '../server/ports.js';
4
5
  import type { PublicationBlobStore, PublicationService } from '../server/publication.js';
@@ -11,6 +12,8 @@ export interface ContentRequest {
11
12
  actorId?: string;
12
13
  cookie?: string;
13
14
  ticket?: string;
15
+ /** Raw HTTP Range header, mapped by the host; absent ⇒ whole file. */
16
+ range?: string;
14
17
  }
15
18
  export interface ContentResponse {
16
19
  status: number;
@@ -26,6 +29,8 @@ export interface ContentHandlerDeps {
26
29
  grants: GrantSigner;
27
30
  tickets: TicketService;
28
31
  baseDomain: string;
32
+ /** LOT 2 §D.3: `content_range_requests {result}`; absent ⇒ no-op. */
33
+ metrics?: ArtifactsMetrics;
29
34
  isApprovedAccount?: (principalId: string) => boolean | Promise<boolean>;
30
35
  /** G1 lock 2 (runtime): sharing policy per scope, fail-closed when absent. */
31
36
  sharingPolicy?: SharingPolicyPort;
@@ -42,7 +42,48 @@ export function createContentHandler(deps) {
42
42
  const approved = (await deps.isApprovedAccount?.(subjectId)) ?? false;
43
43
  return deps.lifecycle.canRead({ artifactId, state }, acl, subjectId, 'read', () => approved, policy);
44
44
  }
45
- async function serveFile(artifactId, manifest, filePath) {
45
+ /**
46
+ * Files parity LOT 2 §B.4: RFC 9110 §14 single-range subset. Only the
47
+ * `bytes=` unit with one satisfiable range is honored; malformed or
48
+ * multi-range headers fall back to the whole file (never an error).
49
+ */
50
+ function parseRange(header, size) {
51
+ if (header === undefined)
52
+ return 'full';
53
+ const match = /^bytes=(\d*)-(\d*)$/.exec(header.trim());
54
+ if (match?.[1] === undefined || match[2] === undefined)
55
+ return 'ignore';
56
+ if (match[1] === '' && match[2] === '')
57
+ return 'ignore';
58
+ if (match[1] === '') {
59
+ // Suffix range: the last N bytes; longer than the file ⇒ the file.
60
+ const suffix = Number(match[2]);
61
+ if (!Number.isSafeInteger(suffix) || suffix <= 0)
62
+ return 'unsatisfiable';
63
+ if (suffix >= size)
64
+ return size === 0 ? 'unsatisfiable' : { start: 0, end: size - 1 };
65
+ return { start: size - suffix, end: size - 1 };
66
+ }
67
+ const start = Number(match[1]);
68
+ if (!Number.isSafeInteger(start) || start >= size)
69
+ return 'unsatisfiable';
70
+ if (match[2] === '')
71
+ return { start, end: size - 1 };
72
+ const end = Number(match[2]);
73
+ if (!Number.isSafeInteger(end) || end < start)
74
+ return 'ignore';
75
+ return { start, end: Math.min(end, size - 1) };
76
+ }
77
+ async function rangeSlice(key, start, end) {
78
+ const ranged = await deps.blobs.getBlobRange?.(key, start, end);
79
+ if (ranged !== undefined) {
80
+ // A short store read is distrusted: serve the whole file instead.
81
+ return ranged.length === end - start + 1 ? ranged : undefined;
82
+ }
83
+ const bytes = await deps.blobs.getBlob(key);
84
+ return bytes === undefined ? undefined : bytes.slice(start, end + 1);
85
+ }
86
+ async function serveFile(artifactId, manifest, filePath, rangeHeader) {
46
87
  const acl = await deps.acls.getArtifactAcl(artifactId);
47
88
  if (acl === undefined)
48
89
  return fail(404);
@@ -53,18 +94,48 @@ export function createContentHandler(deps) {
53
94
  if (file === undefined || typeof file.digest !== 'string')
54
95
  return fail(404);
55
96
  const hex = file.digest.startsWith('sha256:') ? file.digest.slice(7) : file.digest;
56
- const bytes = await deps.blobs.getBlob(`artifacts/${acl.storageScopeId}/blobs/sha256/${hex}`);
97
+ const key = `artifacts/${acl.storageScopeId}/blobs/sha256/${hex}`;
98
+ const mimeType = typeof file.mimeType === 'string' ? file.mimeType : 'application/octet-stream';
99
+ const size = typeof file.size === 'number' ? file.size : undefined;
100
+ const emitRange = (result) => {
101
+ if (deps.metrics !== undefined && rangeHeader !== undefined) {
102
+ deps.metrics.emit({ name: 'content_range_requests', labels: { result } });
103
+ }
104
+ };
105
+ if (rangeHeader !== undefined && size !== undefined) {
106
+ const range = parseRange(rangeHeader, size);
107
+ if (range === 'unsatisfiable') {
108
+ emitRange('416');
109
+ const response = fail(416);
110
+ return { ...response, headers: { ...response.headers, 'content-range': `bytes */${size}` } };
111
+ }
112
+ if (range !== 'full' && range !== 'ignore') {
113
+ const bytes = await rangeSlice(key, range.start, range.end);
114
+ if (bytes === undefined)
115
+ return fail(404);
116
+ emitRange('206');
117
+ return {
118
+ status: 206,
119
+ headers: { ...contentHeaders({ mimeType, size: bytes.length,
120
+ assetCacheSeconds: deps.assetCacheSeconds }),
121
+ 'content-range': `bytes ${range.start}-${range.end}/${size}`,
122
+ 'accept-ranges': 'bytes' },
123
+ bytes,
124
+ };
125
+ }
126
+ if (range === 'ignore')
127
+ emitRange('ignored');
128
+ }
129
+ const bytes = await deps.blobs.getBlob(key);
57
130
  if (bytes === undefined)
58
131
  return fail(404);
59
- if (typeof file.size === 'number' && bytes.length !== file.size)
132
+ if (size !== undefined && bytes.length !== size)
60
133
  return fail(422);
61
134
  return {
62
135
  status: 200,
63
- headers: contentHeaders({
64
- mimeType: typeof file.mimeType === 'string' ? file.mimeType : 'application/octet-stream',
65
- size: bytes.length,
66
- assetCacheSeconds: deps.assetCacheSeconds,
67
- }),
136
+ headers: { ...contentHeaders({ mimeType, size: bytes.length,
137
+ assetCacheSeconds: deps.assetCacheSeconds }),
138
+ 'accept-ranges': 'bytes' },
68
139
  bytes,
69
140
  };
70
141
  }
@@ -140,7 +211,7 @@ export function createContentHandler(deps) {
140
211
  const filePath = resolveContentPath(request.path);
141
212
  if (filePath === undefined || isServiceWorkerPath(filePath))
142
213
  return fail(404);
143
- return serveFile(artifactId, release.manifest, filePath);
214
+ return serveFile(artifactId, release.manifest, filePath, request.range);
144
215
  }
145
216
  return {
146
217
  async handle(request) {
package/dist/http.d.ts CHANGED
@@ -5,6 +5,8 @@ import { type IdempotencyStore } from './server/idempotency.js';
5
5
  import { type KvPort, type PrincipalDirectoryPort, type SharingPolicyPort } from './server/ports.js';
6
6
  import { type GuardedPublicationDeps, type PublicationService } from './server/publication.js';
7
7
  import { type StagingStore, type UploadSessionStore, type UploadSignerPort } from './server/uploads.js';
8
+ import type { ArtifactsMetrics } from './server/metrics.js';
9
+ import type { UploadPageStore } from './server/upload-page.js';
8
10
  import { type AclStore } from './server/access.js';
9
11
  import type { ArtifactReaderStore } from './server/reader-store.js';
10
12
  import type { LifecycleService } from './server/lifecycle.js';
@@ -73,6 +75,20 @@ export interface HttpAppDeps {
73
75
  staging: StagingStore;
74
76
  signer: UploadSignerPort;
75
77
  idempotency?: IdempotencyStore;
78
+ /** LOT 2 §D: per-artifact staged TTL (host option, ceiling 7 days) and per-scope staging aggregate. */
79
+ stagedFileTtlMs?: number;
80
+ stagingQuotaBytesPerScope?: number;
81
+ /** LOT 2 §D.3: upload/storage metering; absent ⇒ no-op. */
82
+ metrics?: ArtifactsMetrics;
83
+ };
84
+ /** LOT 2 §A.5: browser upload page host wiring (required when `artifacts_create_upload_page` is selected). */
85
+ uploadPage?: {
86
+ /** Page ledger; absent ⇒ an in-memory ledger (single process only). */
87
+ pages?: UploadPageStore;
88
+ cookieSecret: string | Uint8Array;
89
+ controlOrigin: string;
90
+ pageBaseUrl: string;
91
+ s3Origins: readonly string[];
76
92
  };
77
93
  }
78
94
  export interface ArtifactApp {