@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
@@ -0,0 +1,33 @@
1
+ /**
2
+ * Files parity LOT 1 — S3 adapter for upload staging + presigned PUT signer.
3
+ *
4
+ * StagingStore over an injected S3 client and bucket: only keys under
5
+ * `artifacts/<scope>/staging/<uuid>` are accepted (assertStagingKey/assertStagingPrefix
6
+ * refuse anything else before any network call), mirroring adapters/s3.ts.
7
+ *
8
+ * UploadSignerPort over `@aws-sdk/s3-request-presigner`: the signature binds
9
+ * content-type and the EXACT Content-Length (a SigV4 presigned PUT cannot
10
+ * carry a content-length range — review finding 3), plus the checksum header
11
+ * when the digest is known at signing time. `x-amz-checksum-sha256` is passed
12
+ * as unhoistable so it stays a signed header instead of being hoisted into
13
+ * the query string. The client (endpoint, region, credentials, path style) is
14
+ * built by the host and injected — this module never reads env or connects.
15
+ */
16
+ import { type S3Client } from '@aws-sdk/client-s3';
17
+ import { type StagingStore, type UploadSignerPort } from '../server/uploads.js';
18
+ export interface S3StagingStoreOptions {
19
+ client: S3Client;
20
+ bucket: string;
21
+ }
22
+ /** Create an S3-backed staging store over an injected client (no env reads). */
23
+ export declare function createS3StagingStore(options: S3StagingStoreOptions): StagingStore;
24
+ export interface S3UploadSignerOptions {
25
+ client: S3Client;
26
+ bucket: string;
27
+ }
28
+ /**
29
+ * Create a presigned-PUT signer over an injected client. The signature binds
30
+ * content-type + exact content-length (declared size) and, when the digest is
31
+ * known, x-amz-checksum-sha256 (kept as a signed header via unhoistableHeaders).
32
+ */
33
+ export declare function createS3UploadSigner(options: S3UploadSignerOptions): UploadSignerPort;
@@ -0,0 +1,105 @@
1
+ /**
2
+ * Files parity LOT 1 — S3 adapter for upload staging + presigned PUT signer.
3
+ *
4
+ * StagingStore over an injected S3 client and bucket: only keys under
5
+ * `artifacts/<scope>/staging/<uuid>` are accepted (assertStagingKey/assertStagingPrefix
6
+ * refuse anything else before any network call), mirroring adapters/s3.ts.
7
+ *
8
+ * UploadSignerPort over `@aws-sdk/s3-request-presigner`: the signature binds
9
+ * content-type and the EXACT Content-Length (a SigV4 presigned PUT cannot
10
+ * carry a content-length range — review finding 3), plus the checksum header
11
+ * when the digest is known at signing time. `x-amz-checksum-sha256` is passed
12
+ * as unhoistable so it stays a signed header instead of being hoisted into
13
+ * the query string. The client (endpoint, region, credentials, path style) is
14
+ * built by the host and injected — this module never reads env or connects.
15
+ */
16
+ import { DeleteObjectCommand, GetObjectCommand, ListObjectsV2Command, PutObjectCommand, } from '@aws-sdk/client-s3';
17
+ import { getSignedUrl } from '@aws-sdk/s3-request-presigner';
18
+ import { assertStagingKey, assertStagingPrefix, checksumHeaderValue, } from '../server/uploads.js';
19
+ /** Create an S3-backed staging store over an injected client (no env reads). */
20
+ export function createS3StagingStore(options) {
21
+ return {
22
+ async put(key, bytes) {
23
+ assertStagingKey(key);
24
+ await options.client.send(new PutObjectCommand({ Bucket: options.bucket, Key: key, Body: bytes }));
25
+ },
26
+ async get(key) {
27
+ assertStagingKey(key);
28
+ try {
29
+ const out = await options.client.send(new GetObjectCommand({ Bucket: options.bucket, Key: key }));
30
+ if (out.Body === undefined)
31
+ return undefined;
32
+ const collected = await out.Body.transformToByteArray();
33
+ return new Uint8Array(collected);
34
+ }
35
+ catch (error) {
36
+ if (typeof error === 'object' && error !== null && 'name' in error) {
37
+ const name = error.name;
38
+ if (name === 'NoSuchKey' || name === 'NotFound')
39
+ return undefined;
40
+ }
41
+ throw error;
42
+ }
43
+ },
44
+ async delete(key) {
45
+ assertStagingKey(key);
46
+ await options.client.send(new DeleteObjectCommand({ Bucket: options.bucket, Key: key }));
47
+ },
48
+ async listKeys(prefix) {
49
+ assertStagingPrefix(prefix);
50
+ const keys = [];
51
+ let token;
52
+ do {
53
+ const out = await options.client.send(new ListObjectsV2Command({ Bucket: options.bucket, Prefix: prefix, ContinuationToken: token }));
54
+ for (const entry of out.Contents ?? []) {
55
+ if (entry.Key !== undefined)
56
+ keys.push(entry.Key);
57
+ }
58
+ token = out.IsTruncated === true ? out.NextContinuationToken : undefined;
59
+ } while (token !== undefined);
60
+ return keys.sort();
61
+ },
62
+ };
63
+ }
64
+ /**
65
+ * Create a presigned-PUT signer over an injected client. The signature binds
66
+ * content-type + exact content-length (declared size) and, when the digest is
67
+ * known, x-amz-checksum-sha256 (kept as a signed header via unhoistableHeaders).
68
+ */
69
+ export function createS3UploadSigner(options) {
70
+ return {
71
+ async signPut(input) {
72
+ assertStagingKey(input.key);
73
+ if (!Number.isSafeInteger(input.contentLength) || input.contentLength < 0) {
74
+ throw new Error('invalid signed content-length');
75
+ }
76
+ const checksumHeader = input.checksumSha256 === undefined
77
+ ? undefined
78
+ : checksumHeaderValue(input.checksumSha256);
79
+ const command = new PutObjectCommand({
80
+ Bucket: options.bucket,
81
+ Key: input.key,
82
+ ContentType: input.contentType,
83
+ ContentLength: input.contentLength,
84
+ ...(checksumHeader === undefined ? {} : { ChecksumSHA256: checksumHeader }),
85
+ });
86
+ const url = await getSignedUrl(options.client, command, {
87
+ expiresIn: input.expiresInSeconds,
88
+ // keep the checksum a signed header (x-amz-* headers are hoisted to the
89
+ // query by default); content-type/content-length are never hoisted and
90
+ // are therefore always signed headers the client must send exactly.
91
+ unhoistableHeaders: new Set(['x-amz-checksum-sha256']),
92
+ });
93
+ return {
94
+ url,
95
+ method: 'PUT',
96
+ headers: {
97
+ 'content-type': input.contentType,
98
+ 'content-length': String(input.contentLength),
99
+ ...(checksumHeader === undefined ? {} : { 'x-amz-checksum-sha256': checksumHeader }),
100
+ },
101
+ expiresAt: new Date(Date.now() + input.expiresInSeconds * 1000).toISOString(),
102
+ };
103
+ },
104
+ };
105
+ }
@@ -43,6 +43,29 @@ export function createS3BlobStore(options) {
43
43
  throw error;
44
44
  }
45
45
  },
46
+ async getBlobRange(key, start, endInclusive) {
47
+ assertBlobKey(key);
48
+ if (!Number.isSafeInteger(start) || !Number.isSafeInteger(endInclusive) || start < 0 ||
49
+ endInclusive < start) {
50
+ return undefined;
51
+ }
52
+ try {
53
+ const out = await options.client.send(new GetObjectCommand({ Bucket: options.bucket, Key: key,
54
+ Range: `bytes=${start}-${endInclusive}` }));
55
+ if (out.Body === undefined)
56
+ return undefined;
57
+ const collected = await out.Body.transformToByteArray();
58
+ return new Uint8Array(collected);
59
+ }
60
+ catch (error) {
61
+ if (typeof error === 'object' && error !== null && 'name' in error) {
62
+ const name = error.name;
63
+ if (name === 'NoSuchKey' || name === 'NotFound' || name === 'InvalidRange')
64
+ return undefined;
65
+ }
66
+ throw error;
67
+ }
68
+ },
46
69
  async listKeys(prefix) {
47
70
  assertBlobPrefix(prefix);
48
71
  const keys = [];
@@ -0,0 +1,20 @@
1
+ import { type PostgresActivationStore } from './postgres-activation.js';
2
+ import type { SqliteDatabase } from './sqlite-sql.js';
3
+ import type { SqliteWriter } from './sqlite.js';
4
+ export type SqliteActivationStore = PostgresActivationStore;
5
+ /** Query client handed to the authority callback (pg hands a PoolClient). */
6
+ export interface SqliteQueryClient {
7
+ query<T>(text: string, params?: readonly unknown[]): Promise<{
8
+ rows: T[];
9
+ rowCount: number;
10
+ }>;
11
+ }
12
+ /** No eager I/O or DDL. Hosts issue fresh random IDs with ttlSeconds <=60.
13
+ * Use consume for browser activation; standalone TicketStore supports existing services.
14
+ * Only an acknowledged consume result permits the host to sign/set a grant cookie.
15
+ */
16
+ export declare function createSqliteActivationStore(options: {
17
+ db: SqliteDatabase;
18
+ writer: SqliteWriter;
19
+ namespace: string;
20
+ }): SqliteActivationStore;
@@ -0,0 +1,205 @@
1
+ import { ACTIVATION_MAX_TTL_SECONDS, ActivationCommitUnknownError, } from './postgres-activation.js';
2
+ import { runQuery } from './sqlite-sql.js';
3
+ /** DB milliseconds now, one reading per statement. */
4
+ const NOW_MS = "CAST((julianday('now') - 2440587.5) * 86400000 AS INTEGER)";
5
+ const bindingKeys = ['subjectId', 'artifactId', 'releaseId', 'channel'];
6
+ const flowKeys = [...bindingKeys, 'nonceDigest', 'sessionId', 'profileDigest', 'policyRevision', 'targetOrigin'];
7
+ function text(value) {
8
+ if (typeof value !== 'string' || value.length === 0 || value.length > 256 ||
9
+ value.includes('\0') || Buffer.from(value).toString('utf8') !== value) {
10
+ throw new Error('invalid activation binding');
11
+ }
12
+ return value;
13
+ }
14
+ function binding(value) {
15
+ if (value.channel !== 'stable' && value.channel !== 'pinned')
16
+ throw new Error('invalid activation channel');
17
+ return { subjectId: text(value.subjectId), artifactId: text(value.artifactId),
18
+ releaseId: text(value.releaseId), channel: value.channel };
19
+ }
20
+ function deadline(value) {
21
+ if (!Number.isSafeInteger(value) || value <= 0)
22
+ throw new Error('invalid activation deadline');
23
+ return value;
24
+ }
25
+ function flowBinding(value) {
26
+ const targetOrigin = text(value.targetOrigin);
27
+ const url = new URL(targetOrigin);
28
+ if (url.protocol !== 'https:' || url.origin !== targetOrigin)
29
+ throw new Error('invalid activation origin');
30
+ for (const digest of [value.nonceDigest, value.profileDigest]) {
31
+ if (!/^[0-9a-f]{64}$/.test(digest))
32
+ throw new Error('invalid activation digest');
33
+ }
34
+ return { ...binding(value), nonceDigest: value.nonceDigest, profileDigest: value.profileDigest,
35
+ sessionId: text(value.sessionId), policyRevision: text(value.policyRevision), targetOrigin };
36
+ }
37
+ const parse = (row) => row === undefined ? undefined : JSON.parse(row.payload);
38
+ /** One serialized writer transaction: BEGIN IMMEDIATE … COMMIT (ROLLBACK on
39
+ * throw). A lost COMMIT acknowledgement surfaces as ActivationCommitUnknownError. */
40
+ async function transaction(db, writer, namespace, work) {
41
+ const release = await writer.acquire();
42
+ let committing = false;
43
+ try {
44
+ db.exec('BEGIN IMMEDIATE');
45
+ runQuery(db, 'INSERT OR IGNORE INTO activation_namespaces (namespace) VALUES ($1)', [namespace]);
46
+ const { rows } = runQuery(db, 'SELECT generation FROM activation_namespaces WHERE namespace = $1', [namespace]);
47
+ const client = {
48
+ query: async (text, params = []) => runQuery(db, text, params),
49
+ };
50
+ const result = await work(client, Number(rows[0].generation));
51
+ committing = true;
52
+ db.exec('COMMIT');
53
+ return result;
54
+ }
55
+ catch (cause) {
56
+ if (committing)
57
+ throw new ActivationCommitUnknownError(cause);
58
+ try {
59
+ db.exec('ROLLBACK');
60
+ }
61
+ catch { /* transaction already closed */ }
62
+ throw cause;
63
+ }
64
+ finally {
65
+ release();
66
+ }
67
+ }
68
+ function recordStores(run, namespace) {
69
+ const parameters = (id, generation) => [namespace, text(id), generation];
70
+ const tickets = {
71
+ async issue(value, ttlMs) {
72
+ if (!Number.isSafeInteger(ttlMs) || ttlMs <= 0 || ttlMs > ACTIVATION_MAX_TTL_SECONDS * 1000) {
73
+ throw new Error('invalid activation lifetime');
74
+ }
75
+ const payload = { ...binding(value), ticketId: text(value.ticketId) };
76
+ return run(async (client, generation) => {
77
+ const { rows } = await client.query(`WITH issued AS (SELECT ${NOW_MS} AS ms)
78
+ INSERT INTO activation_tickets (namespace, generation, payload, issued_ms)
79
+ SELECT $1, $2, json_set($3, '$.expiresAt', ms + $4), ms FROM issued
80
+ RETURNING payload`, [namespace, generation, JSON.stringify(payload), ttlMs]);
81
+ return parse(rows[0]);
82
+ });
83
+ },
84
+ async put(value) {
85
+ const payload = { ...binding(value), ticketId: text(value.ticketId), expiresAt: deadline(value.expiresAt) };
86
+ await run(async (client, generation) => {
87
+ await client.query('INSERT INTO activation_tickets (namespace, generation, payload) VALUES ($1, $2, $3)', [namespace, generation, JSON.stringify(payload)]);
88
+ });
89
+ },
90
+ async peek(id) {
91
+ text(id);
92
+ return run(async (client, generation) => {
93
+ const { rows } = await client.query(`SELECT payload FROM activation_tickets WHERE namespace = $1 AND ticket_id = $2 AND generation = $3 AND expires_ms > ${NOW_MS}`, parameters(id, generation));
94
+ return parse(rows[0]);
95
+ });
96
+ },
97
+ async take(id) {
98
+ text(id);
99
+ return run(async (client, generation) => {
100
+ // pg locks flow-then-ticket first; the serialized writer makes that atomic.
101
+ const { rows } = await client.query(`DELETE FROM activation_tickets WHERE namespace = $1 AND ticket_id = $2 AND generation = $3 AND expires_ms > ${NOW_MS} RETURNING payload`, parameters(id, generation));
102
+ return parse(rows[0]);
103
+ });
104
+ },
105
+ async remove(id) {
106
+ text(id);
107
+ await run(async (client, generation) => {
108
+ await client.query('DELETE FROM activation_tickets WHERE namespace = $1 AND ticket_id = $2 AND generation = $3', parameters(id, generation));
109
+ });
110
+ },
111
+ };
112
+ const flows = {
113
+ async put(value) {
114
+ const payload = { ...flowBinding(value), flowId: text(value.flowId),
115
+ ticketId: text(value.ticketId), expiresAt: deadline(value.expiresAt) };
116
+ await run(async (client, generation) => {
117
+ const { rowCount } = await client.query(`INSERT INTO browser_flows (namespace, generation, payload, ticket_expires_ms)
118
+ SELECT namespace, generation, $4, expires_ms FROM activation_tickets
119
+ WHERE namespace = $1 AND ticket_id = $2 AND generation = $3 AND expires_ms > ${NOW_MS} AND $5 > ${NOW_MS}`, [...parameters(payload.ticketId, generation), JSON.stringify(payload), payload.expiresAt]);
120
+ if (rowCount !== 1)
121
+ throw new Error('invalid activation ticket');
122
+ });
123
+ },
124
+ async peek(id) {
125
+ text(id);
126
+ return run(async (client, generation) => {
127
+ const { rows } = await client.query(`SELECT payload FROM browser_flows WHERE namespace = $1 AND flow_id = $2 AND generation = $3 AND expires_ms > ${NOW_MS}`, parameters(id, generation));
128
+ return parse(rows[0]);
129
+ });
130
+ },
131
+ async remove(id) {
132
+ text(id);
133
+ await run(async (client, generation) => {
134
+ await client.query('DELETE FROM browser_flows WHERE namespace = $1 AND flow_id = $2 AND generation = $3', parameters(id, generation));
135
+ });
136
+ },
137
+ };
138
+ return { tickets, flows };
139
+ }
140
+ /** No eager I/O or DDL. Hosts issue fresh random IDs with ttlSeconds <=60.
141
+ * Use consume for browser activation; standalone TicketStore supports existing services.
142
+ * Only an acknowledged consume result permits the host to sign/set a grant cookie.
143
+ */
144
+ export function createSqliteActivationStore(options) {
145
+ const namespace = text(options.namespace);
146
+ const { db, writer } = options;
147
+ const run = work => transaction(db, writer, namespace, work);
148
+ return {
149
+ ...recordStores(run, namespace),
150
+ async consume(value, authorize) {
151
+ // Snapshot before the writer is acquired; callers cannot retarget an in-flight consume.
152
+ const flowId = text(value.flowId);
153
+ const ticketId = text(value.ticketId);
154
+ const expected = { ...value.expected };
155
+ return run(async (client, generation) => {
156
+ const flowResult = await client.query('SELECT payload FROM browser_flows WHERE namespace = $1 AND flow_id = $2 AND generation = $3', [namespace, flowId, generation]);
157
+ const flow = parse(flowResult.rows[0]);
158
+ if (!flow || flow.ticketId !== ticketId || flowKeys.some(key => flow[key] !== expected[key]))
159
+ return undefined;
160
+ const ticketResult = await client.query('SELECT payload FROM activation_tickets WHERE namespace = $1 AND ticket_id = $2 AND generation = $3', [namespace, ticketId, generation]);
161
+ const ticket = parse(ticketResult.rows[0]);
162
+ if (!ticket || bindingKeys.some(key => ticket[key] !== expected[key]))
163
+ return undefined;
164
+ // This read happens AFTER both lookups; authority may wait again (writer held).
165
+ const live = await client.query(`SELECT 1 AS one FROM browser_flows WHERE namespace = $1 AND flow_id = $2 AND generation = $3 AND expires_ms > ${NOW_MS}`, [namespace, flowId, generation]);
166
+ if (live.rows.length === 0)
167
+ return undefined;
168
+ if (await authorize({ client: client, namespace,
169
+ ticket: Object.freeze({ ...ticket }), flow: Object.freeze({ ...flow }) }) !== true)
170
+ return undefined;
171
+ // One visibility decision after ALL authority waits; cascade consumes the flow.
172
+ const consumed = await client.query(`DELETE FROM activation_tickets WHERE namespace = $1 AND ticket_id = $2 AND generation = $3 AND expires_ms > ${NOW_MS}
173
+ AND EXISTS (
174
+ SELECT 1 FROM browser_flows f WHERE f.namespace = activation_tickets.namespace
175
+ AND f.ticket_id = activation_tickets.ticket_id AND f.flow_id = $4 AND f.generation = activation_tickets.generation AND f.expires_ms > ${NOW_MS})
176
+ RETURNING payload`, [namespace, ticketId, generation, flowId]);
177
+ return parse(consumed.rows[0]);
178
+ });
179
+ },
180
+ async cleanup(limit = 100) {
181
+ if (!Number.isInteger(limit) || limit < 1 || limit > 1000)
182
+ throw new Error('invalid activation cleanup limit');
183
+ return run(async (client, generation) => {
184
+ // No DELETE…LIMIT / FOR UPDATE SKIP LOCKED in SQLite: bounded IN-subselects
185
+ // under the serialized writer, same row selection and total bound.
186
+ const flows = await client.query(`DELETE FROM browser_flows WHERE namespace = $1 AND flow_id IN (
187
+ SELECT flow_id FROM browser_flows WHERE namespace = $2
188
+ AND (expires_ms <= ${NOW_MS} OR generation < $3) ORDER BY expires_ms, flow_id LIMIT $4)`, [namespace, namespace, generation, limit]);
189
+ const flowCount = flows.rowCount;
190
+ const tickets = await client.query(`DELETE FROM activation_tickets WHERE namespace = $1 AND ticket_id IN (
191
+ SELECT ticket_id FROM activation_tickets t WHERE t.namespace = $2
192
+ AND (t.expires_ms <= ${NOW_MS} OR t.generation < $3)
193
+ AND NOT EXISTS (SELECT 1 FROM browser_flows f WHERE f.namespace = t.namespace AND f.ticket_id = t.ticket_id)
194
+ ORDER BY t.expires_ms, t.ticket_id LIMIT $4)`, [namespace, namespace, generation, limit - flowCount]);
195
+ return { flows: flowCount, tickets: tickets.rowCount };
196
+ });
197
+ },
198
+ async invalidate() {
199
+ // pg takes the namespace row FOR UPDATE; the serialized writer is already exclusive.
200
+ await transaction(db, writer, namespace, async (client) => {
201
+ await client.query('UPDATE activation_namespaces SET generation = generation + 1 WHERE namespace = $1', [namespace]);
202
+ });
203
+ },
204
+ };
205
+ }
@@ -0,0 +1,15 @@
1
+ /**
2
+ * U1 — SQLite finalization executor (spec r2 §3.1 A4), same CommitExecutor
3
+ * seam as `createPostgresCommitExecutor`. One connection: beginFinalization
4
+ * acquires the serialized writer and opens BEGIN IMMEDIATE, which SQLite
5
+ * serializes against every other writer — stronger than the pg READ
6
+ * COMMITTED unit, same coordinator-visible semantics (the operation-key row
7
+ * lock is the writer mutex itself). Caller SQL goes through normalizeSql
8
+ * ($N -> ?, casts and FOR UPDATE stripped). release(error) rolls back any
9
+ * open transaction; with a single connection there is no pool to poison.
10
+ */
11
+ import type { CommitExecutor } from '../server/commit/types.js';
12
+ import { type SqliteDatabase } from './sqlite-sql.js';
13
+ import type { SqliteWriter } from './sqlite.js';
14
+ /** Create the SQLite finalization executor over one database + writer. */
15
+ export declare function createSqliteCommitExecutor(db: SqliteDatabase, writer: SqliteWriter): CommitExecutor;
@@ -0,0 +1,89 @@
1
+ import { runQuery } from './sqlite-sql.js';
2
+ function toReceipt(row) {
3
+ return {
4
+ scopeId: row.storage_scope_id,
5
+ internalKey: row.internal_key,
6
+ commandHash: row.command_hash,
7
+ codecVersion: row.command_codec,
8
+ receipt: JSON.parse(row.receipt),
9
+ createdAt: row.created_at,
10
+ };
11
+ }
12
+ /** Create the SQLite finalization executor over one database + writer. */
13
+ export function createSqliteCommitExecutor(db, writer) {
14
+ return {
15
+ async ensureCoordinationRow(scopeId, internalKey) {
16
+ await writer.run(() => {
17
+ runQuery(db, 'INSERT INTO operation_keys (storage_scope_id, internal_key) VALUES ($1, $2) ON CONFLICT (storage_scope_id, internal_key) DO NOTHING', [scopeId, internalKey]);
18
+ });
19
+ },
20
+ async beginFinalization() {
21
+ const releaseWriter = await writer.acquire();
22
+ db.exec('BEGIN IMMEDIATE');
23
+ let finished = false;
24
+ let released = false;
25
+ const finish = () => {
26
+ if (!finished) {
27
+ finished = true;
28
+ try {
29
+ db.exec('ROLLBACK');
30
+ }
31
+ catch { /* transaction already closed */ }
32
+ }
33
+ };
34
+ return {
35
+ query(text, params) {
36
+ // pg deferred-constraint directive has no SQLite equivalent; every
37
+ // SQLite constraint is already immediate, which is what it asks for.
38
+ if (/^\s*SET\s+CONSTRAINTS\b/i.test(text))
39
+ return Promise.resolve({ rows: [], rowCount: 0 });
40
+ return Promise.resolve(runQuery(db, text, params));
41
+ },
42
+ // BEGIN IMMEDIATE is already open; SQLite serializes writers, which
43
+ // subsumes the pg READ COMMITTED + FOR UPDATE key lock.
44
+ beginReadCommitted() { return Promise.resolve(); },
45
+ lockOperationKey(scopeId, internalKey) {
46
+ runQuery(db, 'SELECT 1 FROM operation_keys WHERE storage_scope_id = $1 AND internal_key = $2', [scopeId, internalKey]);
47
+ return Promise.resolve();
48
+ },
49
+ async readReceipt(scopeId, internalKey) {
50
+ const { rows } = runQuery(db, `SELECT storage_scope_id, internal_key, command_codec, command_hash, receipt, created_at
51
+ FROM operation_receipts WHERE storage_scope_id = $1 AND internal_key = $2`, [scopeId, internalKey]);
52
+ return rows[0] === undefined ? undefined : toReceipt(rows[0]);
53
+ },
54
+ async insertReceipt(receipt) {
55
+ try {
56
+ runQuery(db, `INSERT INTO operation_receipts (storage_scope_id, internal_key, command_codec, command_hash, receipt)
57
+ VALUES ($1, $2, $3, $4, $5)`, [receipt.scopeId, receipt.internalKey, receipt.codecVersion, receipt.commandHash, JSON.stringify(receipt.receipt)]);
58
+ }
59
+ catch (error) {
60
+ // Adapt the driver error to the pg code the coordinator's
61
+ // isUniqueViolation() port contract expects.
62
+ if (error instanceof Error && /UNIQUE constraint failed/i.test(error.message)) {
63
+ throw Object.assign(new Error(error.message, { cause: error }), { code: '23505' });
64
+ }
65
+ throw error;
66
+ }
67
+ },
68
+ async commit() {
69
+ db.exec('COMMIT');
70
+ finished = true;
71
+ },
72
+ async rollback() {
73
+ finish();
74
+ },
75
+ release(error) {
76
+ if (released)
77
+ throw new Error('finalization client already released');
78
+ released = true;
79
+ finish();
80
+ releaseWriter();
81
+ if (error !== undefined) {
82
+ // Single connection: nothing to destroy; an uncertain COMMIT left
83
+ // the file consistent (WAL), and the caller sees the error.
84
+ }
85
+ },
86
+ };
87
+ },
88
+ };
89
+ }
@@ -0,0 +1,10 @@
1
+ /**
2
+ * U1 — SQLite management unit, same ManagementUnit port as
3
+ * `createPostgresManagementUnit`. Runs on the caller's finalization client
4
+ * (inside the serialized writer transaction), so the pg FOR UPDATE row locks
5
+ * are unnecessary: the parent lock is the writer mutex itself.
6
+ */
7
+ import type { FinalizeTxClient } from '../server/commit/types.js';
8
+ import type { ManagementUnit } from '../server/management.js';
9
+ /** Parent lock serializes ACL inserts, lifecycle changes and publication FKs. */
10
+ export declare function createSqliteManagementUnit(client: FinalizeTxClient): ManagementUnit;
@@ -0,0 +1,60 @@
1
+ import { applyModeTransition, PLATFORM_PRINCIPAL, PUBLIC_PRINCIPAL } from '../server/access.js';
2
+ /** Parent lock serializes ACL inserts, lifecycle changes and publication FKs. */
3
+ export function createSqliteManagementUnit(client) {
4
+ const listGrants = async (id) => {
5
+ const { rows } = await client.query('SELECT principal_id, permission, created_at FROM 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 }));
8
+ };
9
+ return {
10
+ async lock(id) {
11
+ await client.query('SELECT id FROM artifacts WHERE id = $1', [id]);
12
+ await client.query('SELECT principal_id FROM artifact_access WHERE artifact_id = $1 ORDER BY principal_id', [id]);
13
+ await client.query('SELECT release_id FROM artifact_current WHERE artifact_id = $1', [id]);
14
+ },
15
+ async read(id) {
16
+ const { rows } = await client.query(`SELECT a.owner_id, a.storage_scope_id, a.lifecycle_state, a.is_public, a.access_mode, a.terminal_deleted_at, c.release_id
17
+ FROM artifacts a LEFT JOIN artifact_current c ON c.artifact_id = a.id WHERE a.id = $1`, [id]);
18
+ const row = rows[0];
19
+ if (!row)
20
+ return undefined;
21
+ // G1: access_mode is authoritative; is_public is its legacy projection.
22
+ const accessMode = (row.access_mode ?? (row.is_public === 1 ? 'platform' : 'restricted'));
23
+ const acl = { ownerId: row.owner_id, storageScopeId: row.storage_scope_id,
24
+ isPublic: accessMode !== 'restricted', accessMode, withdrawn: row.lifecycle_state === 'withdrawn', grants: [] };
25
+ return { acl, state: row.lifecycle_state, terminal: row.terminal_deleted_at !== null,
26
+ currentReleaseId: row.release_id };
27
+ },
28
+ async setAccess(id, principalId, action, updatedAt) {
29
+ const modeRow = await client.query('SELECT access_mode, is_public FROM artifacts WHERE id = $1', [id]);
30
+ const current = (modeRow.rows[0] === undefined ? 'restricted'
31
+ : (modeRow.rows[0].access_mode ?? (modeRow.rows[0].is_public === 1 ? 'platform' : 'restricted')));
32
+ if (principalId === PLATFORM_PRINCIPAL || principalId === PUBLIC_PRINCIPAL) {
33
+ // Wide-audience sentinels move the mode through the normative transitions;
34
+ // is_public follows as projection (never forced to false).
35
+ const transition = applyModeTransition(current, action, principalId);
36
+ if (transition.changed) {
37
+ await client.query(`UPDATE artifacts SET access_mode = $2, is_public = ($2 <> 'restricted'), updated_at = $3 WHERE id = $1`, [id, transition.mode, updatedAt]);
38
+ }
39
+ return { grants: await listGrants(id), updatedAt, accessMode: transition.mode, changed: transition.changed };
40
+ }
41
+ const changed = action === 'grant' ? await client.query(`INSERT INTO artifact_access (artifact_id, principal_id, permission) VALUES ($1, $2, 'read')
42
+ ON CONFLICT (artifact_id, principal_id) DO NOTHING`, [id, principalId])
43
+ : await client.query('DELETE FROM artifact_access WHERE artifact_id = $1 AND principal_id = $2', [id, principalId]);
44
+ if (changed.rowCount > 0) {
45
+ await client.query('UPDATE artifacts SET updated_at = $2 WHERE id = $1', [id, updatedAt]);
46
+ }
47
+ const stamp = await client.query('SELECT updated_at FROM artifacts WHERE id = $1', [id]);
48
+ return { grants: await listGrants(id), updatedAt: stamp.rows[0]?.updated_at ?? null,
49
+ accessMode: current, changed: changed.rowCount > 0 };
50
+ },
51
+ async recordEvent(event) {
52
+ await client.query(`INSERT INTO artifact_access_events (artifact_id, actor_id, action, audience, principal_id, policy_revision)
53
+ VALUES ($1, $2, $3, $4, $5, $6)`, [event.artifactId, event.actorId, event.action, event.audience, event.principalId, event.policyRevision]);
54
+ },
55
+ async delete(id, deletedAt) {
56
+ await client.query(`UPDATE artifacts SET lifecycle_state = 'deleted', terminal_deleted_at = $2,
57
+ updated_at = $2, is_public = 0 WHERE id = $1`, [id, deletedAt]);
58
+ },
59
+ };
60
+ }
@@ -0,0 +1,32 @@
1
+ /**
2
+ * U1 — shared SQLite SQL helpers for the local adapter set (no driver import:
3
+ * only the structural database interface, so test doubles can wrap it).
4
+ */
5
+ export interface SqliteStatement {
6
+ run(...params: unknown[]): {
7
+ changes: number | bigint;
8
+ };
9
+ all(...params: unknown[]): unknown[];
10
+ get(...params: unknown[]): unknown;
11
+ }
12
+ export interface SqliteDatabase {
13
+ exec(sql: string): void;
14
+ prepare(sql: string): SqliteStatement;
15
+ close(): void;
16
+ }
17
+ /**
18
+ * Normalize portable caller SQL for SQLite: `$N` placeholders become `?`
19
+ * (params re-ordered by first appearance), pg casts `::type` and row-lock
20
+ * clauses (`FOR UPDATE/SHARE … SKIP LOCKED/NOWAIT`) are stripped — the
21
+ * serialized writer already provides the locking. Booleans bind as 0/1,
22
+ * undefined as NULL.
23
+ */
24
+ export declare function normalizeSql(text: string, params?: readonly unknown[]): {
25
+ sql: string;
26
+ args: unknown[];
27
+ };
28
+ /** Execute one statement: rows for SELECT/RETURNING, rowCount = changes otherwise. */
29
+ export declare function runQuery<T>(db: SqliteDatabase, text: string, params?: readonly unknown[]): {
30
+ rows: T[];
31
+ rowCount: number;
32
+ };
@@ -0,0 +1,36 @@
1
+ /**
2
+ * Normalize portable caller SQL for SQLite: `$N` placeholders become `?`
3
+ * (params re-ordered by first appearance), pg casts `::type` and row-lock
4
+ * clauses (`FOR UPDATE/SHARE … SKIP LOCKED/NOWAIT`) are stripped — the
5
+ * serialized writer already provides the locking. Booleans bind as 0/1,
6
+ * undefined as NULL.
7
+ */
8
+ export function normalizeSql(text, params = []) {
9
+ const args = [];
10
+ let sql = text.replace(/\$(\d+)/g, (_match, index) => {
11
+ args.push(params[Number(index) - 1]);
12
+ return '?';
13
+ });
14
+ sql = sql
15
+ .replace(/::[A-Za-z_][A-Za-z0-9_]*(\[\])?/g, '')
16
+ .replace(/\s+FOR\s+(?:UPDATE|SHARE|KEY\s+SHARE|NO KEY UPDATE)(?:\s+OF\s+[A-Za-z_][A-Za-z0-9_]*(?:\s*,\s*[A-Za-z_][A-Za-z0-9_]*)*)?(?:\s+(?:SKIP\s+LOCKED|NOWAIT))?/gi, '');
17
+ const bound = args.map((value) => {
18
+ if (value === undefined)
19
+ return null;
20
+ if (typeof value === 'boolean')
21
+ return value ? 1 : 0;
22
+ return value;
23
+ });
24
+ return { sql, args: bound };
25
+ }
26
+ /** Execute one statement: rows for SELECT/RETURNING, rowCount = changes otherwise. */
27
+ export function runQuery(db, text, params = []) {
28
+ const { sql, args } = normalizeSql(text, params);
29
+ const statement = db.prepare(sql);
30
+ if (/\bRETURNING\b/i.test(sql) || /^\s*SELECT\b/i.test(sql)) {
31
+ const rows = statement.all(...args);
32
+ return { rows, rowCount: rows.length };
33
+ }
34
+ const info = statement.run(...args);
35
+ return { rows: [], rowCount: Number(info.changes) };
36
+ }
@@ -0,0 +1,12 @@
1
+ import type { RefcountStore } from '../server/gc.js';
2
+ import type { LifecycleStore } from '../server/lifecycle.js';
3
+ import type { SourceStore } from '../server/sources.js';
4
+ import type { PreparationIntentStore } from '../server/object-intents.js';
5
+ import type { IdempotencyStore } from '../server/idempotency.js';
6
+ import type { PublicationStateStore } from '../server/publication.js';
7
+ import type { PostgresArtifactStore } from './postgres.js';
8
+ import { type SqliteDatabase } from './sqlite-sql.js';
9
+ import type { SqliteWriter } from './sqlite.js';
10
+ /** Create the SQLite-backed store implementing the same ports as the pg store. */
11
+ export declare function createSqliteArtifactStore(db: SqliteDatabase, writer: SqliteWriter): PostgresArtifactStore;
12
+ export type { PreparationIntentStore, PublicationStateStore, IdempotencyStore, RefcountStore, SourceStore, LifecycleStore };