@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.
- package/CHANGELOG.md +37 -0
- package/dist/adapters/local-blob.d.ts +3 -0
- package/dist/adapters/local-blob.js +93 -0
- package/dist/adapters/postgres-uploads.d.ts +14 -0
- package/dist/adapters/postgres-uploads.js +174 -0
- package/dist/adapters/s3.js +23 -0
- package/dist/adapters/sqlite-activation.d.ts +20 -0
- package/dist/adapters/sqlite-activation.js +205 -0
- package/dist/adapters/sqlite-commit.d.ts +15 -0
- package/dist/adapters/sqlite-commit.js +89 -0
- package/dist/adapters/sqlite-management.d.ts +10 -0
- package/dist/adapters/sqlite-management.js +60 -0
- package/dist/adapters/sqlite-sql.d.ts +32 -0
- package/dist/adapters/sqlite-sql.js +36 -0
- package/dist/adapters/sqlite-store.d.ts +12 -0
- package/dist/adapters/sqlite-store.js +410 -0
- package/dist/adapters/sqlite.d.ts +33 -0
- package/dist/adapters/sqlite.js +95 -0
- package/dist/content/handler.d.ts +5 -0
- package/dist/content/handler.js +80 -9
- package/dist/http.d.ts +16 -0
- package/dist/http.js +435 -97
- package/dist/mcp-core.d.ts +3 -3
- package/dist/mcp-core.js +43 -4
- package/dist/profile/contracts.d.ts +1 -1
- package/dist/profile/contracts.js +4 -0
- package/dist/profile/index.js +12 -2
- package/dist/profile/schemas.js +60 -0
- package/dist/profile/validation.js +31 -4
- package/dist/server/command-identity.d.ts +1 -1
- package/dist/server/command-identity.js +4 -3
- package/dist/server/gc.d.ts +28 -3
- package/dist/server/gc.js +81 -5
- package/dist/server/management.js +10 -5
- package/dist/server/metrics.d.ts +21 -0
- package/dist/server/metrics.js +6 -0
- package/dist/server/ports.d.ts +7 -0
- package/dist/server/ports.js +7 -0
- package/dist/server/publication-limits.d.ts +8 -0
- package/dist/server/publication-limits.js +8 -0
- package/dist/server/publication.d.ts +5 -0
- package/dist/server/publication.js +6 -0
- package/dist/server/source-read.d.ts +12 -9
- package/dist/server/source-read.js +17 -5
- package/dist/server/upload-page.d.ts +157 -0
- package/dist/server/upload-page.js +438 -0
- package/dist/server/uploads.d.ts +75 -1
- package/dist/server/uploads.js +187 -27
- package/migrations/0009_upload_pages.sql +25 -0
- package/package.json +13 -1
- package/sql/sqlite/0001_artifacts.sql +156 -0
- package/sql/sqlite/0002_activation.sql +73 -0
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,42 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.2.15
|
|
4
|
+
|
|
5
|
+
- R1: every model-visible userRef projection emits the opaque `unknown` value
|
|
6
|
+
when the directory entry is missing instead of falling back to the raw
|
|
7
|
+
internal id (`sub`): `projectUserRef`, `list_access` grants and owner,
|
|
8
|
+
the `set_access` receipt, and the `list_versions` v1 author (plus the v2
|
|
9
|
+
`authorPrincipalId`). No MCP tool definition changes.
|
|
10
|
+
- R5: `assertShareable` enforces the approved-principal gate on `grant` only;
|
|
11
|
+
`revoke` stays allowed for dormant (suspended or deleted) principals as the
|
|
12
|
+
expected cleanup step. Revoking an absent grant is a no-op success.
|
|
13
|
+
|
|
14
|
+
## 0.2.14
|
|
15
|
+
|
|
16
|
+
- Add a durable local SQLite adapter set behind the new `./sqlite` subpath export:
|
|
17
|
+
`sqlite.ts`, `sqlite-store.ts`, `sqlite-commit.ts`, `sqlite-management.ts`,
|
|
18
|
+
`sqlite-activation.ts` and `local-blob.ts` implement the same port interfaces as
|
|
19
|
+
the Postgres adapters and the S3 blob store, backed by the builtin `node:sqlite`
|
|
20
|
+
driver (no new dependency) and the local filesystem with sha256 digest
|
|
21
|
+
verification on put, get and strict delete.
|
|
22
|
+
- Cover bindings, intents, idempotency, ACL, lifecycle, publication state, refcounts,
|
|
23
|
+
the commit coordinator with the same transactional semantics and release CAS, and
|
|
24
|
+
the activation store. Multi-statement units run in one serialized writer
|
|
25
|
+
transaction (`BEGIN IMMEDIATE`); that isolation is stronger than the Postgres
|
|
26
|
+
READ COMMITTED baseline while the observable port behaviour is unchanged.
|
|
27
|
+
- Prove parity with one parameterized conformance suite executed against both the
|
|
28
|
+
Postgres and the SQLite backends, including restart durability, concurrent
|
|
29
|
+
writers, CAS conflicts and the refcount/GC edges.
|
|
30
|
+
- The root and portable entries stay free of `node:sqlite` and `better-sqlite3`;
|
|
31
|
+
import the local adapters only through `@sentropic/artifacts/sqlite`.
|
|
32
|
+
- Artifacts 0.2.14 stays inside the cluster-mesh peer range `>=0.2.0 <0.3.0`;
|
|
33
|
+
the API keeps its pinned APP-P1 profile digest and requalifies the APP-P1
|
|
34
|
+
manifest digest for this version.
|
|
35
|
+
- Union fix on the train: the SQLite management unit, store ACL paths and the
|
|
36
|
+
`artifact_access_events` audit table follow the G2 sharing port
|
|
37
|
+
(`SetAccessOutput.accessMode`/`changed`, `recordEvent`, authoritative
|
|
38
|
+
`access_mode` with `is_public` as projection).
|
|
39
|
+
|
|
3
40
|
## 0.2.13
|
|
4
41
|
|
|
5
42
|
- G2 MCP sharing tools: new read-only tools `artifacts_lookup_people`
|
|
@@ -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
|
+
}
|
|
@@ -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
|
+
}
|
package/dist/adapters/s3.js
CHANGED
|
@@ -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;
|