@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.
- package/CHANGELOG.md +93 -0
- package/README.md +45 -10
- package/dist/adapters/local-blob.d.ts +3 -0
- package/dist/adapters/local-blob.js +93 -0
- package/dist/adapters/postgres-management.js +3 -2
- package/dist/adapters/postgres-reader-consent.d.ts +11 -0
- package/dist/adapters/postgres-reader-consent.js +109 -0
- package/dist/adapters/postgres-uploads.d.ts +14 -0
- package/dist/adapters/postgres-uploads.js +174 -0
- package/dist/adapters/postgres.js +4 -3
- package/dist/adapters/s3-uploads.d.ts +33 -0
- package/dist/adapters/s3-uploads.js +105 -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/content/headers.js +12 -0
- package/dist/http.d.ts +32 -2
- package/dist/http.js +615 -13
- package/dist/mcp-core.d.ts +3 -3
- package/dist/mcp-core.js +90 -4
- package/dist/profile/contracts.d.ts +1 -1
- package/dist/profile/contracts.js +7 -0
- package/dist/profile/index.js +43 -2
- package/dist/profile/radar.js +7 -0
- package/dist/profile/schemas.js +119 -0
- package/dist/profile/validation.d.ts +11 -0
- package/dist/profile/validation.js +98 -6
- package/dist/server/access.d.ts +2 -0
- package/dist/server/command-identity.d.ts +1 -1
- package/dist/server/command-identity.js +6 -3
- package/dist/server/consent.d.ts +65 -0
- package/dist/server/consent.js +42 -0
- package/dist/server/gc.d.ts +42 -0
- package/dist/server/gc.js +98 -0
- package/dist/server/management.d.ts +3 -1
- package/dist/server/management.js +48 -7
- package/dist/server/metrics.d.ts +21 -0
- package/dist/server/metrics.js +6 -0
- package/dist/server/mime.d.ts +26 -2
- package/dist/server/mime.js +124 -2
- package/dist/server/ports.d.ts +29 -0
- package/dist/server/ports.js +11 -0
- package/dist/server/publication-limits.d.ts +20 -0
- package/dist/server/publication-limits.js +27 -1
- package/dist/server/publication.d.ts +14 -0
- package/dist/server/publication.js +10 -2
- package/dist/server/reader-store.d.ts +58 -0
- package/dist/server/reader-store.js +109 -0
- package/dist/server/source-read.d.ts +12 -9
- package/dist/server/source-read.js +17 -5
- package/dist/server/templates.js +50 -2
- package/dist/server/upload-page.d.ts +157 -0
- package/dist/server/upload-page.js +438 -0
- package/dist/server/uploads.d.ts +229 -19
- package/dist/server/uploads.js +387 -80
- package/migrations/0007_uploads.sql +43 -0
- package/migrations/0008_reader_consent.sql +48 -0
- package/migrations/0009_upload_pages.sql +25 -0
- package/package.json +34 -1
- package/sql/reader-consent.sql +47 -0
- package/sql/sqlite/0001_artifacts.sql +156 -0
- package/sql/sqlite/0002_activation.sql +73 -0
|
@@ -2,6 +2,21 @@ import { isArtifactId } from '../contracts.js';
|
|
|
2
2
|
import { ArtifactProfileInputError } from './contracts.js';
|
|
3
3
|
import { copyJson, freezeDeep, isRecord } from './json.js';
|
|
4
4
|
import { operationProfile } from './schemas.js';
|
|
5
|
+
import { SERVER_MAX_FILE_BYTES, SERVER_MAX_FILES_PER_RELEASE, SERVER_MAX_TOTAL_BYTES } from '../server/publication-limits.js';
|
|
6
|
+
/** Release budget of a bundle publication: the publish operation's release* keys
|
|
7
|
+
* override its inline values; absent keys default to the inline values, and the
|
|
8
|
+
* server maxima are hard ceilings either way (profile/index.ts enforces them).
|
|
9
|
+
* Exported for the HTTP layer (create_upload/commit_upload/publish_bundle). */
|
|
10
|
+
export function releaseBudget(profile) {
|
|
11
|
+
const publishLimits = profile.operations.find((entry) => entry.operation === 'publish')?.limits;
|
|
12
|
+
return {
|
|
13
|
+
filesMax: publishLimits?.releaseFilesMax ?? publishLimits?.publishFilesMax ?? SERVER_MAX_FILES_PER_RELEASE,
|
|
14
|
+
fileBytesMax: publishLimits?.releaseFileBytesMax ?? publishLimits?.maxDecodedFileBytes ?? SERVER_MAX_FILE_BYTES,
|
|
15
|
+
totalBytesMax: publishLimits?.releaseTotalBytesMax ?? publishLimits?.maxDecodedTotalBytes ?? SERVER_MAX_TOTAL_BYTES,
|
|
16
|
+
inlineFileBytesMax: publishLimits?.maxDecodedFileBytes ?? SERVER_MAX_FILE_BYTES,
|
|
17
|
+
inlineTotalBytesMax: publishLimits?.maxDecodedTotalBytes ?? SERVER_MAX_TOTAL_BYTES,
|
|
18
|
+
};
|
|
19
|
+
}
|
|
5
20
|
function requireInput(condition) {
|
|
6
21
|
if (!condition)
|
|
7
22
|
throw new ArtifactProfileInputError();
|
|
@@ -87,7 +102,8 @@ export function normalizeArguments(profile, name, input, schema, envelopeKey, op
|
|
|
87
102
|
const operation = name.slice('artifacts_'.length);
|
|
88
103
|
const { defaults, limits } = operationProfile(profile, operation);
|
|
89
104
|
const normalized = { ...copyJson(defaults), ...args };
|
|
90
|
-
if (['ensure', 'publish', 'commit_upload', '
|
|
105
|
+
if (['ensure', 'publish', 'commit_upload', 'publish_bundle', 'publish_bundle_v2',
|
|
106
|
+
'set_access', 'delete', 'revert'].includes(operation)) {
|
|
91
107
|
const key = args.idempotencyKey;
|
|
92
108
|
requireInput(typeof key === 'string' && key.trim().length > 0 && key.length <= limits.idempotencyKeyMaxUnits);
|
|
93
109
|
requireInput(envelopeKey === undefined || envelopeKey === key);
|
|
@@ -104,24 +120,100 @@ export function normalizeArguments(profile, name, input, schema, envelopeKey, op
|
|
|
104
120
|
requireInput(isArtifactId(args.releaseId));
|
|
105
121
|
if (Object.hasOwn(args, 'expectedCurrentReleaseId'))
|
|
106
122
|
requireInput(args.expectedCurrentReleaseId === null || isArtifactId(args.expectedCurrentReleaseId));
|
|
107
|
-
|
|
123
|
+
const isBundle = operation === 'publish_bundle' || operation === 'publish_bundle_v2';
|
|
124
|
+
if (operation === 'publish' || isBundle) {
|
|
108
125
|
const hasFiles = Object.hasOwn(args, 'files');
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
126
|
+
if (operation === 'publish') {
|
|
127
|
+
const hasEdits = Object.hasOwn(args, 'edits');
|
|
128
|
+
// Exactly one content source: a full file set, or small edits on the current release.
|
|
129
|
+
requireInput(hasFiles !== hasEdits);
|
|
130
|
+
}
|
|
131
|
+
else {
|
|
132
|
+
// A bundle needs at least one content source: inline files and/or assets.
|
|
133
|
+
requireInput(hasFiles || Object.hasOwn(args, 'assets'));
|
|
134
|
+
}
|
|
112
135
|
if (hasFiles) {
|
|
113
136
|
const paths = new Set();
|
|
114
137
|
let total = 0;
|
|
138
|
+
const inlineFileBytesMax = operation === 'publish' ? limits.maxDecodedFileBytes : releaseBudget(profile).inlineFileBytesMax;
|
|
139
|
+
const inlineTotalBytesMax = operation === 'publish' ? limits.maxDecodedTotalBytes : releaseBudget(profile).inlineTotalBytesMax;
|
|
115
140
|
normalized.files = args.files.map((file) => {
|
|
116
141
|
const path = file.path;
|
|
117
142
|
requireInput(!paths.has(path) && Buffer.byteLength(path, 'utf8') <= profile.rules.pathMaxBytes);
|
|
118
143
|
paths.add(path);
|
|
119
144
|
const bytes = Object.hasOwn(file, 'text') ? Array.from(Buffer.from(file.text, 'utf8')) : file.bytes;
|
|
120
145
|
total += bytes.length;
|
|
121
|
-
requireInput(bytes.length <=
|
|
146
|
+
requireInput(bytes.length <= inlineFileBytesMax && total <= inlineTotalBytesMax);
|
|
122
147
|
return { path, mimeType: file.mimeType, bytes };
|
|
123
148
|
});
|
|
149
|
+
if (isBundle && Object.hasOwn(args, 'assets')) {
|
|
150
|
+
// Duplicate path refused across the files/assets union.
|
|
151
|
+
for (const asset of args.assets) {
|
|
152
|
+
requireInput(!paths.has(asset.path));
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
if (isBundle && Object.hasOwn(args, 'assets')) {
|
|
157
|
+
const paths = new Set();
|
|
158
|
+
if (hasFiles)
|
|
159
|
+
for (const file of args.files)
|
|
160
|
+
paths.add(file.path);
|
|
161
|
+
normalized.assets = args.assets.map((asset) => {
|
|
162
|
+
const path = asset.path;
|
|
163
|
+
requireInput(!paths.has(path) && Buffer.byteLength(path, 'utf8') <= profile.rules.pathMaxBytes);
|
|
164
|
+
paths.add(path);
|
|
165
|
+
if (Object.hasOwn(asset, 'uploadId')) {
|
|
166
|
+
requireInput(isArtifactId(asset.uploadId));
|
|
167
|
+
return { path, uploadId: asset.uploadId };
|
|
168
|
+
}
|
|
169
|
+
// LOT 2 v2 asset forms: copy from another artifact, or carry from a
|
|
170
|
+
// release of this artifact. The MIME type is taken from the source
|
|
171
|
+
// manifest at resolution time, never from the caller.
|
|
172
|
+
if (Object.hasOwn(asset, 'sourceArtifactId')) {
|
|
173
|
+
requireInput(isArtifactId(asset.sourceArtifactId));
|
|
174
|
+
if (Object.hasOwn(asset, 'sourcePath')) {
|
|
175
|
+
requireInput(typeof asset.sourcePath === 'string' &&
|
|
176
|
+
Buffer.byteLength(asset.sourcePath, 'utf8') <= profile.rules.pathMaxBytes);
|
|
177
|
+
}
|
|
178
|
+
if (Object.hasOwn(asset, 'sourceReleaseId')) {
|
|
179
|
+
requireInput(isArtifactId(asset.sourceReleaseId));
|
|
180
|
+
}
|
|
181
|
+
return { path, sourceArtifactId: asset.sourceArtifactId,
|
|
182
|
+
...(Object.hasOwn(asset, 'sourcePath') ? { sourcePath: asset.sourcePath } : {}),
|
|
183
|
+
...(Object.hasOwn(asset, 'sourceReleaseId') ? { sourceReleaseId: asset.sourceReleaseId } : {}) };
|
|
184
|
+
}
|
|
185
|
+
if (Object.hasOwn(asset, 'carryFromReleaseId')) {
|
|
186
|
+
requireInput(isArtifactId(asset.carryFromReleaseId));
|
|
187
|
+
if (Object.hasOwn(asset, 'sourcePath')) {
|
|
188
|
+
requireInput(typeof asset.sourcePath === 'string' &&
|
|
189
|
+
Buffer.byteLength(asset.sourcePath, 'utf8') <= profile.rules.pathMaxBytes);
|
|
190
|
+
}
|
|
191
|
+
return { path, carryFromReleaseId: asset.carryFromReleaseId,
|
|
192
|
+
...(Object.hasOwn(asset, 'sourcePath') ? { sourcePath: asset.sourcePath } : {}) };
|
|
193
|
+
}
|
|
194
|
+
const digest = asset.digest;
|
|
195
|
+
requireInput(/^sha256:[0-9a-f]{64}$/.test(digest) && Number.isSafeInteger(asset.size) && asset.size >= 1 &&
|
|
196
|
+
profile.rules.mimeTypes.includes(asset.mimeType));
|
|
197
|
+
return { path, digest, size: asset.size, mimeType: asset.mimeType };
|
|
198
|
+
});
|
|
124
199
|
}
|
|
125
200
|
}
|
|
201
|
+
if (operation === 'create_upload') {
|
|
202
|
+
// MIME must be inside the profile allowlist (itself within the server ceiling).
|
|
203
|
+
requireInput(profile.rules.mimeTypes.includes(args.mimeType));
|
|
204
|
+
if (Object.hasOwn(args, 'maxSize')) {
|
|
205
|
+
requireInput(Number.isSafeInteger(args.maxSize) && args.maxSize >= 1 &&
|
|
206
|
+
args.maxSize <= releaseBudget(profile).fileBytesMax);
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
if (operation === 'commit_upload') {
|
|
210
|
+
const path = args.path;
|
|
211
|
+
requireInput(Buffer.byteLength(path, 'utf8') <= profile.rules.pathMaxBytes);
|
|
212
|
+
requireInput(profile.rules.mimeTypes.includes(args.mimeType));
|
|
213
|
+
requireInput(/^sha256:[0-9a-f]{64}$/.test(args.digest));
|
|
214
|
+
requireInput(Number.isSafeInteger(args.size) && args.size >= 1 &&
|
|
215
|
+
args.size <= releaseBudget(profile).fileBytesMax);
|
|
216
|
+
requireInput(isArtifactId(args.uploadId));
|
|
217
|
+
}
|
|
126
218
|
return freezeDeep(normalized);
|
|
127
219
|
}
|
package/dist/server/access.d.ts
CHANGED
|
@@ -44,6 +44,8 @@ export interface AccessEvent {
|
|
|
44
44
|
export interface GrantRecord {
|
|
45
45
|
principalId: string;
|
|
46
46
|
grant: AccessGrant;
|
|
47
|
+
/** Grant creation stamp (migration 0006 `created_at`); absent on legacy rows. */
|
|
48
|
+
createdAt?: string;
|
|
47
49
|
}
|
|
48
50
|
/** Display metadata of one artifact (title/description/icon); cosmetic, owner-set. */
|
|
49
51
|
export interface ArtifactMetadata {
|
|
@@ -8,7 +8,7 @@ export type CallerIdempotencyKey = string & {
|
|
|
8
8
|
export type InternalIdempotencyKey = string & {
|
|
9
9
|
readonly __brand: 'internal-key';
|
|
10
10
|
};
|
|
11
|
-
export type ArtifactCommandOperation = 'ensure' | 'publish' | 'set_access' | 'delete' | 'revert';
|
|
11
|
+
export type ArtifactCommandOperation = 'ensure' | 'publish' | 'set_access' | 'delete' | 'revert' | 'commit_upload' | 'publish_bundle' | 'publish_bundle_v2';
|
|
12
12
|
export interface CommandIdentity {
|
|
13
13
|
readonly internalKey: InternalIdempotencyKey;
|
|
14
14
|
readonly commandHash: string;
|
|
@@ -20,7 +20,8 @@ export function createRadarKeyDerivation(config) {
|
|
|
20
20
|
if (other === actor || !other.startsWith(`${actor}|`))
|
|
21
21
|
continue;
|
|
22
22
|
const [operation, objectId] = other.slice(actor.length + 1).split('|');
|
|
23
|
-
if ((operation === 'ensure' && objectId === '') ||
|
|
23
|
+
if ((operation === 'ensure' && objectId === '') ||
|
|
24
|
+
(['publish', 'set_access', 'delete', 'revert', 'commit_upload', 'publish_bundle', 'publish_bundle_v2'].includes(operation) && isArtifactId(objectId))) {
|
|
24
25
|
throw new Error('ambiguous Radar actor domain');
|
|
25
26
|
}
|
|
26
27
|
}
|
|
@@ -30,7 +31,7 @@ export function createRadarKeyDerivation(config) {
|
|
|
30
31
|
derive(input) {
|
|
31
32
|
const { storageScopeId, actorId, operation, objectId, callerKey } = input;
|
|
32
33
|
if (storageScopeId !== scope || !actors.has(actorId) ||
|
|
33
|
-
!['ensure', 'publish', 'set_access', 'delete', 'revert'].includes(operation) ||
|
|
34
|
+
!['ensure', 'publish', 'set_access', 'delete', 'revert', 'commit_upload', 'publish_bundle', 'publish_bundle_v2'].includes(operation) ||
|
|
34
35
|
(operation === 'ensure' ? objectId !== '' : !isArtifactId(objectId)))
|
|
35
36
|
throw new ArtifactProfileInputError();
|
|
36
37
|
assertWellFormed(callerKey);
|
|
@@ -48,7 +49,9 @@ export function createArtifactCommand(profile, name, args, authority, derivation
|
|
|
48
49
|
if (derivation.algorithm !== profile.profile.rules.keyDerivationAlgorithm)
|
|
49
50
|
throw new Error('profile/derivation mismatch');
|
|
50
51
|
const normalized = profile.validate(name, args, envelopeKey, options);
|
|
51
|
-
if (!['artifacts_ensure', 'artifacts_publish', 'artifacts_set_access', 'artifacts_delete', 'artifacts_revert'
|
|
52
|
+
if (!['artifacts_ensure', 'artifacts_publish', 'artifacts_set_access', 'artifacts_delete', 'artifacts_revert',
|
|
53
|
+
'artifacts_commit_upload', 'artifacts_publish_bundle',
|
|
54
|
+
'artifacts_publish_bundle_v2'].includes(name))
|
|
52
55
|
throw new ArtifactProfileInputError(true);
|
|
53
56
|
const operation = name.slice('artifacts_'.length);
|
|
54
57
|
const { idempotencyKey, confirmationRef: _proof, ...payload } = normalized;
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Lot 1a — persistent reader consent, pure evaluation (design-merged §3.1,
|
|
3
|
+
* §3.2). A consent row authorizes one data class at one scope version; it
|
|
4
|
+
* never substitutes fresh rights. Validity is live row plus current scope
|
|
5
|
+
* version plus fresh rights, evaluated per call. No release, session, device
|
|
6
|
+
* or TTL column exists: the row outlives sessions and releases until revoked.
|
|
7
|
+
*/
|
|
8
|
+
export interface ConsentKey {
|
|
9
|
+
storageScopeId: string;
|
|
10
|
+
readerAccountId: string;
|
|
11
|
+
artifactId: string;
|
|
12
|
+
scopeId: string;
|
|
13
|
+
scopeVersion: string;
|
|
14
|
+
}
|
|
15
|
+
export interface ReaderConsentRecord extends ConsentKey {
|
|
16
|
+
/** UUID, one row per grant episode; re-grant after revoke mints a new row. */
|
|
17
|
+
consentId: string;
|
|
18
|
+
/** ISO-8601 text, aligned with cluster-mesh consent records. */
|
|
19
|
+
grantedAt: string;
|
|
20
|
+
/** Lot 1a: a first-party gesture on the control-origin screen mints consent; the model never grants. */
|
|
21
|
+
grantedVia: 'reader_screen';
|
|
22
|
+
revokedAt?: string;
|
|
23
|
+
revokedBy?: 'self' | 'admin' | 'cascade';
|
|
24
|
+
}
|
|
25
|
+
export interface ReaderConsentEvent {
|
|
26
|
+
consentId: string;
|
|
27
|
+
storageScopeId: string;
|
|
28
|
+
readerAccountId: string;
|
|
29
|
+
artifactId: string;
|
|
30
|
+
scopeId: string;
|
|
31
|
+
scopeVersion: string;
|
|
32
|
+
action: 'grant' | 'revoke';
|
|
33
|
+
actor: string;
|
|
34
|
+
surface: 'screen' | 'api' | 'mcp' | 'cascade';
|
|
35
|
+
at: string;
|
|
36
|
+
}
|
|
37
|
+
export declare function assertConsentScopeId(scopeId: string): void;
|
|
38
|
+
export declare function assertConsentScopeVersion(scopeVersion: string): void;
|
|
39
|
+
/** Live row at the host's current scope version; absence of TTL is the owner requirement. */
|
|
40
|
+
export declare function consentAllows(record: ReaderConsentRecord | undefined, currentScopeVersion: string): record is ReaderConsentRecord;
|
|
41
|
+
/** Fresh-rights input of Gate B: approved account plus ACL read, re-evaluated on this call. */
|
|
42
|
+
export type FreshRights = 'ok' | 'suspended' | 'withdrawn' | 'gone';
|
|
43
|
+
export type GateBDecision = {
|
|
44
|
+
allowed: true;
|
|
45
|
+
} | {
|
|
46
|
+
allowed: false;
|
|
47
|
+
refusal: 'reader_consent_required';
|
|
48
|
+
scopeId: string;
|
|
49
|
+
} | {
|
|
50
|
+
allowed: false;
|
|
51
|
+
refusal: 'refused';
|
|
52
|
+
status: 401 | 404;
|
|
53
|
+
};
|
|
54
|
+
/**
|
|
55
|
+
* Gate B (§3.2): the business call executes only with a live consent at the
|
|
56
|
+
* current scope version AND fresh rights. A suspended account or a withdrawn
|
|
57
|
+
* share is refused with the row kept dormant, so reactivation or re-share
|
|
58
|
+
* resumes without a screen. A non-reader never sees the consent page.
|
|
59
|
+
*/
|
|
60
|
+
export declare function decideGateB(input: {
|
|
61
|
+
consent: ReaderConsentRecord | undefined;
|
|
62
|
+
currentScopeVersion: string;
|
|
63
|
+
rights: FreshRights;
|
|
64
|
+
scopeId: string;
|
|
65
|
+
}): GateBDecision;
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Lot 1a — persistent reader consent, pure evaluation (design-merged §3.1,
|
|
3
|
+
* §3.2). A consent row authorizes one data class at one scope version; it
|
|
4
|
+
* never substitutes fresh rights. Validity is live row plus current scope
|
|
5
|
+
* version plus fresh rights, evaluated per call. No release, session, device
|
|
6
|
+
* or TTL column exists: the row outlives sessions and releases until revoked.
|
|
7
|
+
*/
|
|
8
|
+
/** Host-declared scope ids are package-opaque: letter start, dots/dashes/underscores, at most 128. */
|
|
9
|
+
const SCOPE_ID_PATTERN = /^[a-z][a-z0-9._-]{0,127}$/;
|
|
10
|
+
/** Scope versions are host content; widening bumps them, narrowing keeps them (§3.1). */
|
|
11
|
+
const SCOPE_VERSION_PATTERN = /^[A-Za-z0-9._-]{1,64}$/;
|
|
12
|
+
export function assertConsentScopeId(scopeId) {
|
|
13
|
+
if (!SCOPE_ID_PATTERN.test(scopeId) || scopeId.startsWith('sentropic:')) {
|
|
14
|
+
throw new Error(`invalid consent scope id: ${scopeId}`);
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
export function assertConsentScopeVersion(scopeVersion) {
|
|
18
|
+
if (!SCOPE_VERSION_PATTERN.test(scopeVersion))
|
|
19
|
+
throw new Error(`invalid consent scope version: ${scopeVersion}`);
|
|
20
|
+
}
|
|
21
|
+
/** Live row at the host's current scope version; absence of TTL is the owner requirement. */
|
|
22
|
+
export function consentAllows(record, currentScopeVersion) {
|
|
23
|
+
return record !== undefined && record.revokedAt === undefined && record.scopeVersion === currentScopeVersion;
|
|
24
|
+
}
|
|
25
|
+
/**
|
|
26
|
+
* Gate B (§3.2): the business call executes only with a live consent at the
|
|
27
|
+
* current scope version AND fresh rights. A suspended account or a withdrawn
|
|
28
|
+
* share is refused with the row kept dormant, so reactivation or re-share
|
|
29
|
+
* resumes without a screen. A non-reader never sees the consent page.
|
|
30
|
+
*/
|
|
31
|
+
export function decideGateB(input) {
|
|
32
|
+
if (input.rights === 'gone')
|
|
33
|
+
return { allowed: false, refusal: 'refused', status: 404 };
|
|
34
|
+
if (input.rights === 'suspended')
|
|
35
|
+
return { allowed: false, refusal: 'refused', status: 401 };
|
|
36
|
+
if (input.rights === 'withdrawn')
|
|
37
|
+
return { allowed: false, refusal: 'refused', status: 404 };
|
|
38
|
+
if (!consentAllows(input.consent, input.currentScopeVersion)) {
|
|
39
|
+
return { allowed: false, refusal: 'reader_consent_required', scopeId: input.scopeId };
|
|
40
|
+
}
|
|
41
|
+
return { allowed: true };
|
|
42
|
+
}
|
package/dist/server/gc.d.ts
CHANGED
|
@@ -1,5 +1,8 @@
|
|
|
1
1
|
import type { CommitExecutor, FinalizeTxClient } from './commit/types.js';
|
|
2
2
|
import { type PublicationBlobStore } from './publication.js';
|
|
3
|
+
import { type StagingStore, type UploadSessionStore } from './uploads.js';
|
|
4
|
+
import type { ArtifactsMetrics } from './metrics.js';
|
|
5
|
+
import type { UploadPageStore } from './upload-page.js';
|
|
3
6
|
export interface RefcountStore {
|
|
4
7
|
addRef(digest: string, holder: string): Promise<void>;
|
|
5
8
|
releaseRef(digest: string, holder: string): Promise<void>;
|
|
@@ -62,4 +65,43 @@ export declare function createMemoryDeletionClaimStore(): InspectableDeletionCla
|
|
|
62
65
|
export declare function createClaimGuardedRefs(refs: RefcountStore, claims: DeletionClaimStore): RefcountStore;
|
|
63
66
|
/** Create a GC service over an injected refcount store (no driver imports). */
|
|
64
67
|
export declare function createGcService(refs: RefcountStore): GcService;
|
|
68
|
+
export interface UploadSweepReport {
|
|
69
|
+
expired: string[];
|
|
70
|
+
deletedKeys: string[];
|
|
71
|
+
failures: {
|
|
72
|
+
uploadId: string;
|
|
73
|
+
error: string;
|
|
74
|
+
}[];
|
|
75
|
+
/** LOT 2 §D.1: staged rows past the staged-file TTL (deleted + unpinned). */
|
|
76
|
+
stagedExpired: string[];
|
|
77
|
+
/** LOT 2 §D.1: digests whose consumed upload pin the sweeper released. */
|
|
78
|
+
unpinned: string[];
|
|
79
|
+
/** LOT 2 §D.1: orphan staging keys deleted past the grace (bounded per run). */
|
|
80
|
+
orphanKeys: string[];
|
|
81
|
+
/** LOT 2 §A.3: page rows past expires_at (flipped to expired, kept for audit). */
|
|
82
|
+
pagesExpired: string[];
|
|
83
|
+
}
|
|
84
|
+
export interface UploadSweeper {
|
|
85
|
+
sweep(now?: Date, options?: {
|
|
86
|
+
scopes?: string[];
|
|
87
|
+
}): Promise<UploadSweepReport>;
|
|
88
|
+
}
|
|
89
|
+
/**
|
|
90
|
+
* Create the enforced staging sweeper over the injected session/staging
|
|
91
|
+
* ports. LOT 2 adds staged-file TTL, orphan staging keys, page expiry and
|
|
92
|
+
* sweep summaries; refs/pages/metrics are optional (absent ⇒ the pass that
|
|
93
|
+
* needs them is skipped, except summaries which simply have no sink).
|
|
94
|
+
*/
|
|
95
|
+
export declare function createUploadSweeper(deps: {
|
|
96
|
+
sessions: UploadSessionStore;
|
|
97
|
+
staging: Pick<StagingStore, 'delete' | 'listKeys'> & Pick<StagingStore, 'listEntries'>;
|
|
98
|
+
refs?: RefcountStore;
|
|
99
|
+
pages?: UploadPageStore;
|
|
100
|
+
metrics?: ArtifactsMetrics;
|
|
101
|
+
}, options?: {
|
|
102
|
+
now?: () => Date;
|
|
103
|
+
stagedFileTtlMs?: number;
|
|
104
|
+
orphanGraceMs?: number;
|
|
105
|
+
orphanKeyLimit?: number;
|
|
106
|
+
}): UploadSweeper;
|
|
65
107
|
export {};
|
package/dist/server/gc.js
CHANGED
|
@@ -12,6 +12,7 @@
|
|
|
12
12
|
*/
|
|
13
13
|
import { createKeyMutex } from './ports.js';
|
|
14
14
|
import { blobDigestOfKey } from './publication.js';
|
|
15
|
+
import { ORPHAN_STAGING_GRACE_MS, ORPHAN_SWEEP_MAX_KEYS, STAGED_FILE_TTL_MAX_MS, STAGED_FILE_TTL_MS, stagingKey, stagingPrefix } from './uploads.js';
|
|
15
16
|
/** In-memory RefcountStore double (yields mid-update to expose races). */
|
|
16
17
|
export function createMemoryRefcountStore() {
|
|
17
18
|
const holders = new Map();
|
|
@@ -251,3 +252,100 @@ export function createGcService(refs) {
|
|
|
251
252
|
},
|
|
252
253
|
};
|
|
253
254
|
}
|
|
255
|
+
/**
|
|
256
|
+
* Create the enforced staging sweeper over the injected session/staging
|
|
257
|
+
* ports. LOT 2 adds staged-file TTL, orphan staging keys, page expiry and
|
|
258
|
+
* sweep summaries; refs/pages/metrics are optional (absent ⇒ the pass that
|
|
259
|
+
* needs them is skipped, except summaries which simply have no sink).
|
|
260
|
+
*/
|
|
261
|
+
export function createUploadSweeper(deps, options) {
|
|
262
|
+
const stagedFileTtlMs = options?.stagedFileTtlMs ?? STAGED_FILE_TTL_MS;
|
|
263
|
+
const orphanGraceMs = options?.orphanGraceMs ?? ORPHAN_STAGING_GRACE_MS;
|
|
264
|
+
const orphanKeyLimit = options?.orphanKeyLimit ?? ORPHAN_SWEEP_MAX_KEYS;
|
|
265
|
+
if (!Number.isSafeInteger(stagedFileTtlMs) || stagedFileTtlMs < 1 ||
|
|
266
|
+
stagedFileTtlMs > STAGED_FILE_TTL_MAX_MS) {
|
|
267
|
+
throw new Error('invalid staged file TTL');
|
|
268
|
+
}
|
|
269
|
+
const emitSummary = (name, value) => {
|
|
270
|
+
if (deps.metrics !== undefined)
|
|
271
|
+
deps.metrics.emit({ name, value });
|
|
272
|
+
};
|
|
273
|
+
return {
|
|
274
|
+
async sweep(at = options?.now?.() ?? new Date(), sweepOptions) {
|
|
275
|
+
const report = { expired: [], deletedKeys: [], failures: [],
|
|
276
|
+
stagedExpired: [], unpinned: [], orphanKeys: [], pagesExpired: [] };
|
|
277
|
+
for (const session of await deps.sessions.listExpiredOpen(at)) {
|
|
278
|
+
const key = stagingKey(session.storageScopeId, session.uploadId);
|
|
279
|
+
try {
|
|
280
|
+
await deps.staging.delete(key);
|
|
281
|
+
await deps.sessions.markExpired(session.uploadId);
|
|
282
|
+
report.expired.push(session.uploadId);
|
|
283
|
+
report.deletedKeys.push(key);
|
|
284
|
+
}
|
|
285
|
+
catch (error) {
|
|
286
|
+
report.failures.push({ uploadId: session.uploadId, error: String(error) });
|
|
287
|
+
}
|
|
288
|
+
}
|
|
289
|
+
// Pass 2: staged files past the TTL. Unpin first, then delete the row;
|
|
290
|
+
// an unpin failure keeps the row for the next run and is reported.
|
|
291
|
+
for (const record of await deps.sessions.listExpiredStaged(at, stagedFileTtlMs)) {
|
|
292
|
+
try {
|
|
293
|
+
if (deps.refs !== undefined) {
|
|
294
|
+
await deps.refs.unpin(record.digest, `upload:${record.uploadId}`);
|
|
295
|
+
report.unpinned.push(record.digest);
|
|
296
|
+
}
|
|
297
|
+
await deps.sessions.deleteStagedFile(record.uploadId);
|
|
298
|
+
report.stagedExpired.push(record.uploadId);
|
|
299
|
+
}
|
|
300
|
+
catch (error) {
|
|
301
|
+
report.failures.push({ uploadId: record.uploadId, error: String(error) });
|
|
302
|
+
}
|
|
303
|
+
}
|
|
304
|
+
emitSummary('staged_files_expired', report.stagedExpired.length);
|
|
305
|
+
// Pass 3: orphan staging keys (no session row in open|committed) past
|
|
306
|
+
// the grace, bounded per run. Stores without listEntries skip the pass.
|
|
307
|
+
if (deps.staging.listEntries !== undefined && sweepOptions?.scopes !== undefined) {
|
|
308
|
+
let remaining = orphanKeyLimit;
|
|
309
|
+
for (const scope of sweepOptions.scopes) {
|
|
310
|
+
if (remaining <= 0)
|
|
311
|
+
break;
|
|
312
|
+
const entries = await deps.staging.listEntries(stagingPrefix(scope));
|
|
313
|
+
for (const entry of entries) {
|
|
314
|
+
if (remaining <= 0)
|
|
315
|
+
break;
|
|
316
|
+
const uploadId = entry.key.slice(entry.key.lastIndexOf('/') + 1);
|
|
317
|
+
const session = await deps.sessions.get(uploadId);
|
|
318
|
+
if (session !== undefined && (session.state === 'open' || session.state === 'committed')) {
|
|
319
|
+
continue;
|
|
320
|
+
}
|
|
321
|
+
if (new Date(entry.lastModified).getTime() + orphanGraceMs > at.getTime())
|
|
322
|
+
continue;
|
|
323
|
+
try {
|
|
324
|
+
await deps.staging.delete(entry.key);
|
|
325
|
+
report.orphanKeys.push(entry.key);
|
|
326
|
+
remaining -= 1;
|
|
327
|
+
}
|
|
328
|
+
catch (error) {
|
|
329
|
+
report.failures.push({ uploadId, error: String(error) });
|
|
330
|
+
}
|
|
331
|
+
}
|
|
332
|
+
}
|
|
333
|
+
}
|
|
334
|
+
emitSummary('staging_orphans_deleted', report.orphanKeys.length);
|
|
335
|
+
// Pass 4: browser pages past expires_at (rows kept for audit).
|
|
336
|
+
if (deps.pages !== undefined) {
|
|
337
|
+
for (const row of await deps.pages.listExpiredPages(at)) {
|
|
338
|
+
try {
|
|
339
|
+
await deps.pages.markExpired(row.pageSessionId);
|
|
340
|
+
report.pagesExpired.push(row.pageSessionId);
|
|
341
|
+
}
|
|
342
|
+
catch (error) {
|
|
343
|
+
report.failures.push({ uploadId: row.pageSessionId, error: String(error) });
|
|
344
|
+
}
|
|
345
|
+
}
|
|
346
|
+
}
|
|
347
|
+
emitSummary('upload_pages_expired', report.pagesExpired.length);
|
|
348
|
+
return report;
|
|
349
|
+
},
|
|
350
|
+
};
|
|
351
|
+
}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { type AccessEvent, type AccessMode, type ArtifactAcl, type GrantRecord } from './access.js';
|
|
2
|
-
import { type SharingPolicyPort } from './ports.js';
|
|
2
|
+
import { type PrincipalDirectoryPort, type SharingPolicyPort } from './ports.js';
|
|
3
3
|
import type { ArtifactInvocationContext, ArtifactCommitCoordinator, FinalizeTxClient } from './commit/types.js';
|
|
4
4
|
import type { EffectiveArtifactCommand } from './command-identity.js';
|
|
5
5
|
import { ArtifactOperationError, type ArtifactOutcome } from './failures.js';
|
|
@@ -55,4 +55,6 @@ export declare function manageArtifact(deps: {
|
|
|
55
55
|
profileAllowPublicSharing?: boolean;
|
|
56
56
|
/** G1: server-resolved platform admin predicate (never a tool argument). */
|
|
57
57
|
actorIsAdmin?: (actorId: string, storageScopeId: string) => boolean | Promise<boolean>;
|
|
58
|
+
/** G2: host principal directory; required for userRef resolution and output projection. */
|
|
59
|
+
directory?: PrincipalDirectoryPort;
|
|
58
60
|
}, invocation: ArtifactInvocationContext, command: EffectiveArtifactCommand, proof?: string): Promise<ArtifactOutcome<unknown>>;
|
|
@@ -15,6 +15,11 @@ function policyRefused() {
|
|
|
15
15
|
return new ArtifactOperationError('unauthorized_at_commit', { refusal: { allowed: false,
|
|
16
16
|
reason: 'denied', status: 403, publicCode: 'public_sharing_disabled', retriable: false } });
|
|
17
17
|
}
|
|
18
|
+
/** G2 §2.3 step (4): the single merged non-shareable refusal (422), like the policy refusal above. */
|
|
19
|
+
function shareableRefused() {
|
|
20
|
+
return new ArtifactOperationError('unauthorized_at_commit', { refusal: { allowed: false,
|
|
21
|
+
reason: 'denied', status: 422, publicCode: 'person_not_shareable', retriable: false } });
|
|
22
|
+
}
|
|
18
23
|
/** Targeted writes and proof consumption share the existing coordinator receipt transaction. */
|
|
19
24
|
export async function manageArtifact(deps, invocation, command, proof) {
|
|
20
25
|
const artifactId = command.payload.artifactId;
|
|
@@ -51,6 +56,38 @@ export async function manageArtifact(deps, invocation, command, proof) {
|
|
|
51
56
|
return target;
|
|
52
57
|
};
|
|
53
58
|
const sharingPolicy = async () => combineSharingPolicy(deps.profileAllowPublicSharing, await resolveSharingPolicy(deps.sharingPolicy, invocation.storageScopeId));
|
|
59
|
+
// G2 §2.3 step (4): resolve the opaque userRef to the internal principal
|
|
60
|
+
// inside the transaction, after visibility and the management right — the
|
|
61
|
+
// commandHash was computed on the payload as provided (userRef), so no
|
|
62
|
+
// resolution can leak to a non-reader. Without a directory port, legacy
|
|
63
|
+
// trusted callers keep passing internal principals directly (G1 behaviour).
|
|
64
|
+
const resolveTarget = async (principalId) => {
|
|
65
|
+
if (deps.directory === undefined)
|
|
66
|
+
return principalId;
|
|
67
|
+
return await deps.directory.resolvePrincipal(invocation.storageScopeId, principalId) ?? principalId;
|
|
68
|
+
};
|
|
69
|
+
// Unknown, inactive, unapproved and out-of-scope targets merge into the
|
|
70
|
+
// single `person_not_shareable` so no account status can be probed.
|
|
71
|
+
const assertShareable = async (internal, action) => {
|
|
72
|
+
if (deps.directory === undefined) {
|
|
73
|
+
if (action === 'grant' && !await deps.isApprovedPrincipal(internal))
|
|
74
|
+
throw refused('access_denied');
|
|
75
|
+
return;
|
|
76
|
+
}
|
|
77
|
+
if (!await deps.isApprovedPrincipal(internal))
|
|
78
|
+
throw shareableRefused();
|
|
79
|
+
};
|
|
80
|
+
// The receipt is model-visible: project internal principals to userRefs
|
|
81
|
+
// (audit events keep the internal form).
|
|
82
|
+
const projectGrants = async (grants) => {
|
|
83
|
+
if (deps.directory === undefined)
|
|
84
|
+
return grants;
|
|
85
|
+
return Promise.all(grants.map(async (grant) => ({
|
|
86
|
+
...grant,
|
|
87
|
+
principalId: (await deps.directory.describePrincipal(invocation.storageScopeId, grant.principalId))?.userRef
|
|
88
|
+
?? grant.principalId,
|
|
89
|
+
})));
|
|
90
|
+
};
|
|
54
91
|
const request = {
|
|
55
92
|
...command.identity, scopeId: invocation.storageScopeId, actorId: invocation.actorId,
|
|
56
93
|
invocationId: invocation.invocationId, operation: command.operation, artifactId,
|
|
@@ -87,17 +124,19 @@ export async function manageArtifact(deps, invocation, command, proof) {
|
|
|
87
124
|
else {
|
|
88
125
|
const { action, principalId } = access;
|
|
89
126
|
const audience = audienceOf(principalId);
|
|
90
|
-
|
|
91
|
-
|
|
127
|
+
const internal = audience === 'user' ? await resolveTarget(principalId) : principalId;
|
|
128
|
+
if (audience === 'user')
|
|
129
|
+
await assertShareable(internal, action);
|
|
92
130
|
// Double lock (profile capability AND runtime port) resolved in the
|
|
93
131
|
// transaction; the revision rides the receipt/audit, never the commandHash.
|
|
94
132
|
const policy = await sharingPolicy();
|
|
95
133
|
if (action === 'grant' && principalId === PUBLIC_PRINCIPAL && !policy.allowPublicSharing)
|
|
96
134
|
throw policyRefused();
|
|
97
|
-
const output = await unit.setAccess(artifactId,
|
|
135
|
+
const output = await unit.setAccess(artifactId, internal, action, now);
|
|
98
136
|
await unit.recordEvent({ artifactId, actorId: invocation.actorId, action, audience,
|
|
99
|
-
principalId: audience === 'user' ?
|
|
100
|
-
Object.assign(receipt, { artifactId, ...output,
|
|
137
|
+
principalId: audience === 'user' ? internal : null, policyRevision: policy.policyRevision });
|
|
138
|
+
Object.assign(receipt, { artifactId, ...output, grants: await projectGrants(output.grants),
|
|
139
|
+
policyRevision: policy.policyRevision });
|
|
101
140
|
}
|
|
102
141
|
},
|
|
103
142
|
guard: async (ctx, tx) => {
|
|
@@ -107,8 +146,10 @@ export async function manageArtifact(deps, invocation, command, proof) {
|
|
|
107
146
|
if (!deleting) {
|
|
108
147
|
const { action, principalId } = access;
|
|
109
148
|
const audience = audienceOf(principalId);
|
|
110
|
-
if (audience === 'user'
|
|
111
|
-
|
|
149
|
+
if (audience === 'user') {
|
|
150
|
+
const internal = await resolveTarget(principalId);
|
|
151
|
+
await assertShareable(internal, action);
|
|
152
|
+
}
|
|
112
153
|
const policy = await sharingPolicy();
|
|
113
154
|
if (action === 'grant' && principalId === PUBLIC_PRINCIPAL && !policy.allowPublicSharing)
|
|
114
155
|
throw policyRefused();
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Files parity LOT 2 §D.3 — upload/storage metering (signatures; body in Lot 4).
|
|
3
|
+
*
|
|
4
|
+
* Optional `metrics(event)` callback on upload/page/content deps; absent ⇒
|
|
5
|
+
* no-op. No metrics library in the package, no `artifactId` or `ownerId` in
|
|
6
|
+
* labels. Sweep summaries are emitted once per run.
|
|
7
|
+
*/
|
|
8
|
+
export interface ArtifactsMetricEvent {
|
|
9
|
+
/** e.g. `upload_sessions_created`; see §D.3 for the closed event set. */
|
|
10
|
+
readonly name: string;
|
|
11
|
+
/** Low-cardinality labels only (channel, result, reason, origin). */
|
|
12
|
+
readonly labels?: Readonly<Record<string, string>>;
|
|
13
|
+
/** Numeric magnitude (e.g. committed bytes); never an identifier. */
|
|
14
|
+
readonly value?: number;
|
|
15
|
+
}
|
|
16
|
+
export interface ArtifactsMetrics {
|
|
17
|
+
emit(event: ArtifactsMetricEvent): void;
|
|
18
|
+
}
|
|
19
|
+
/** No-op sink used when the host wires no metrics port. */
|
|
20
|
+
export declare const NO_METRICS: ArtifactsMetrics;
|
|
21
|
+
export declare function emitMetric(metrics: ArtifactsMetrics | undefined, event: ArtifactsMetricEvent): void;
|
package/dist/server/mime.d.ts
CHANGED
|
@@ -1,7 +1,31 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Canonical text-mime pattern shared by publication input rules and source
|
|
3
|
-
* reads
|
|
4
|
-
*
|
|
3
|
+
* reads, plus the generic MIME ceiling and byte validation (files parity
|
|
4
|
+
* LOT 1). Leaf module: `http.ts`, `server/source-read.ts`, `server/uploads.ts`
|
|
5
|
+
* and `profile/index.ts` import it without an import cycle.
|
|
6
|
+
*
|
|
7
|
+
* The ceiling is the generic server maximum: a profile `mimeTypes` list must
|
|
8
|
+
* be a subset of it (checked at profile compile time). Validation at commit
|
|
9
|
+
* (upload commit and inline publish alike): magic bytes for binary types,
|
|
10
|
+
* strict UTF-8 for text types, and a script/handler/external-reference-free
|
|
11
|
+
* SVG. Declared type stays authoritative at serve time because it was
|
|
12
|
+
* verified against the bytes at commit (sniffing stays banned).
|
|
5
13
|
*/
|
|
6
14
|
export declare const TEXT_MIME_PATTERN = "^(?:text/[a-z0-9!#$&^_.+-]+|application/(?:javascript|ecmascript|json|xml|[a-z0-9!#$&^_.+-]+\\+(?:json|xml))|image/svg\\+xml)(?![\\s\\S])";
|
|
7
15
|
export declare const TEXT_MIME_RE: RegExp;
|
|
16
|
+
/**
|
|
17
|
+
* Generic MIME ceiling (server maximum). Profiles may only narrow it.
|
|
18
|
+
* No executables, no archives: the posture rests on this closed allowlist
|
|
19
|
+
* plus magic-byte verification, declared-type serving with `nosniff` on the
|
|
20
|
+
* single-label content origin, and sandbox CSP on SVG/PDF.
|
|
21
|
+
*/
|
|
22
|
+
export declare const SERVER_MIME_CEILING: readonly string[];
|
|
23
|
+
/** True when the MIME type is inside the generic ceiling. */
|
|
24
|
+
export declare function isWithinMimeCeiling(mimeType: string): boolean;
|
|
25
|
+
/**
|
|
26
|
+
* Validate file bytes against the declared MIME type. Throws on mismatch;
|
|
27
|
+
* callers map the failure to `verification_failed` (422) with no pin and no
|
|
28
|
+
* release. Text types must decode as strict UTF-8; SVG must be XML text
|
|
29
|
+
* without scripts, event handlers or external references.
|
|
30
|
+
*/
|
|
31
|
+
export declare function validateFileBytes(mimeType: string, bytes: Uint8Array): void;
|