@hiai-gg/docsmint 2.1.9 → 2.2.2
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/README.md +5 -3
- package/dist/backend/index.js +483 -87
- package/dist/backend-account-runtime-cleanup.js +16 -0
- package/dist/backend-api-key-facade.js +16 -0
- package/dist/backend-pipeline-cancellation.js +16 -0
- package/dist/client.js +5 -1
- package/dist/frontend/FolderNode-Ds0LDfK3.js +290 -0
- package/dist/frontend/Sidebar-DerKtpWB.js +2168 -0
- package/dist/frontend/app-shell.js +1 -1
- package/dist/frontend/components/folder-node.js +1 -1
- package/dist/frontend/components/sidebar.js +1 -1
- package/dist/frontend/{dndzone-C62yjeG3.js → dndzone-B9jA0yIS.js} +21 -9
- package/dist/frontend/utils/dndzone.js +1 -1
- package/dist/frontend-ssr/app-shell.js +1 -1
- package/dist/frontend-ssr/assets/{FolderNode-Dg_5-orQ.js → FolderNode-CyOrLJ2Y.js} +6 -9
- package/dist/frontend-ssr/assets/{Sidebar-fpYk5MGO.js → Sidebar-dTp4DyW4.js} +164 -85
- package/dist/frontend-ssr/assets/{dndzone-Dx3jt_e4.js → dndzone-C7KnICM0.js} +22 -4
- package/dist/frontend-ssr/components/folder-node.js +1 -1
- package/dist/frontend-ssr/components/sidebar.js +1 -1
- package/dist/frontend-ssr/utils/dndzone.js +1 -1
- package/dist/lifecycle-runtime.js +27 -2
- package/dist/mcp-cli.js +107 -40
- package/dist/mcp-server.js +107 -40
- package/dist/types.d.ts +6 -2
- package/package.json +3 -2
- package/packages/cli/src/index.ts +1 -1
- package/packages/db/src/schema.ts +35 -0
- package/server.json +2 -2
- package/dist/frontend/FolderNode-Y7cV9xeX.js +0 -307
- package/dist/frontend/Sidebar-i0kbanpg.js +0 -2123
package/dist/backend/index.js
CHANGED
|
@@ -44089,6 +44089,7 @@ __export(exports_schema, {
|
|
|
44089
44089
|
apiKeys: () => apiKeys,
|
|
44090
44090
|
attachmentRelations: () => attachmentRelations,
|
|
44091
44091
|
attachmentStorageCleanupOutbox: () => attachmentStorageCleanupOutbox,
|
|
44092
|
+
attachmentUploadOperations: () => attachmentUploadOperations,
|
|
44092
44093
|
attachments: () => attachments,
|
|
44093
44094
|
auditLog: () => auditLog,
|
|
44094
44095
|
categories: () => categories,
|
|
@@ -44131,7 +44132,7 @@ __export(exports_schema, {
|
|
|
44131
44132
|
versionRelations: () => versionRelations,
|
|
44132
44133
|
versions: () => versions
|
|
44133
44134
|
});
|
|
44134
|
-
var vector4, tsvector, documentVisibilityEnum, shareRoleEnum, shareAccessModeEnum, shareGrantStatusEnum, embeddingStatusEnum, pipelineStageEnum, pipelineStatusEnum, lifecycleOperationKindEnum, lifecycleOperationStatusEnum, users, sessions, accounts, verifications, folders, folderRelations, documents, documentRelations, documentPipelineRuns, documentPipelineBatches, metadataReembedOutbox, documentKnowledgeSummaries, tags, tagRelations, categories, categoryRelations, documentTags, documentTagRelations, shareLinks, shareLinkRelations, guestAccess, guestAccessRelations, attachments, pendingAttachmentUploads, attachmentStorageCleanupOutbox, pendingAttachmentCleanupAuthorizations, attachmentRelations, versions, documentEmbeddings, documentEmbeddingRelations, apiKeys, apiKeyRelations, auditLog, lifecycleOperations, documentCreateOperations, folderCreateOperations, versionRelations;
|
|
44135
|
+
var vector4, tsvector, documentVisibilityEnum, shareRoleEnum, shareAccessModeEnum, shareGrantStatusEnum, embeddingStatusEnum, pipelineStageEnum, pipelineStatusEnum, lifecycleOperationKindEnum, lifecycleOperationStatusEnum, users, sessions, accounts, verifications, folders, folderRelations, documents, documentRelations, documentPipelineRuns, documentPipelineBatches, metadataReembedOutbox, documentKnowledgeSummaries, tags, tagRelations, categories, categoryRelations, documentTags, documentTagRelations, shareLinks, shareLinkRelations, guestAccess, guestAccessRelations, attachments, pendingAttachmentUploads, attachmentUploadOperations, attachmentStorageCleanupOutbox, pendingAttachmentCleanupAuthorizations, attachmentRelations, versions, documentEmbeddings, documentEmbeddingRelations, apiKeys, apiKeyRelations, auditLog, lifecycleOperations, documentCreateOperations, folderCreateOperations, versionRelations;
|
|
44135
44136
|
var init_schema2 = __esm(() => {
|
|
44136
44137
|
init_pg_core();
|
|
44137
44138
|
init_drizzle_orm();
|
|
@@ -44584,6 +44585,21 @@ var init_schema2 = __esm(() => {
|
|
|
44584
44585
|
index("pending_attachment_uploads_cleanup_lease_idx").on(table.expiresAt, table.leaseExpiresAt, table.id),
|
|
44585
44586
|
check2("pending_attachment_uploads_quota_state_check", sql`${table.quotaState} IN ('not_required', 'reserve_pending', 'reserved', 'finalize_pending', 'committed')`)
|
|
44586
44587
|
]);
|
|
44588
|
+
attachmentUploadOperations = pgTable("attachment_upload_operations", {
|
|
44589
|
+
id: uuid("id").primaryKey().defaultRandom(),
|
|
44590
|
+
workspaceId: text("workspace_id").notNull(),
|
|
44591
|
+
actorUserId: uuid("actor_user_id").notNull().references(() => users.id, { onDelete: "cascade" }),
|
|
44592
|
+
documentId: uuid("document_id").notNull().references(() => documents.id, { onDelete: "cascade" }),
|
|
44593
|
+
idempotencyKey: text("idempotency_key").notNull(),
|
|
44594
|
+
requestFingerprint: text("request_fingerprint").notNull(),
|
|
44595
|
+
sourceSha256: text("source_sha256").notNull(),
|
|
44596
|
+
storageKey: text("storage_key").notNull(),
|
|
44597
|
+
expiresAt: timestamp("expires_at").notNull(),
|
|
44598
|
+
createdAt: timestamp("created_at").defaultNow().notNull()
|
|
44599
|
+
}, (table) => [
|
|
44600
|
+
uniqueIndex("attachment_upload_operations_actor_document_key_unique").on(table.workspaceId, table.actorUserId, table.documentId, table.idempotencyKey),
|
|
44601
|
+
uniqueIndex("attachment_upload_operations_storage_key_unique").on(table.storageKey)
|
|
44602
|
+
]);
|
|
44587
44603
|
attachmentStorageCleanupOutbox = pgTable("attachment_storage_cleanup_outbox", {
|
|
44588
44604
|
id: uuid("id").primaryKey().defaultRandom(),
|
|
44589
44605
|
sourceKind: text("source_kind").notNull(),
|
|
@@ -69584,6 +69600,7 @@ var init_config_schema = __esm(() => {
|
|
|
69584
69600
|
HIAI_DOCS_API_KEY: string2().trim().optional().default("").transform((value) => value || undefined).refine((value) => !!value && !adminApiKeyPlaceholder.test(value), "HIAI_DOCS_API_KEY must be set to a non-placeholder value in production"),
|
|
69585
69601
|
API_KEY_ENCRYPTION_SECRET: string2().min(32, "API_KEY_ENCRYPTION_SECRET must be at least 32 characters").default("change-me-to-random-32-chars-long").refine((value) => value !== "change-me-to-random-32-chars-long", "API_KEY_ENCRYPTION_SECRET must be set in production"),
|
|
69586
69602
|
OWNER_ID: string2().uuid().default("00000000-0000-4000-8000-000000000001"),
|
|
69603
|
+
DOCSMINT_ATTACHMENT_WEBP_ENABLED: _enum(["true", "false"]).default("false").transform((value) => value === "true"),
|
|
69587
69604
|
DOCSMINT_WORKSPACE_ENABLED: string2().optional().default("false").transform((value) => value === "true"),
|
|
69588
69605
|
DOCSMINT_WORKSPACE_ISSUER: string2().trim().optional(),
|
|
69589
69606
|
DOCSMINT_WORKSPACE_SECRET: string2().optional(),
|
|
@@ -183348,6 +183365,17 @@ var nanoid2 = customAlphabet(urlAlphabet);
|
|
|
183348
183365
|
init_dist_es11();
|
|
183349
183366
|
init_schema2();
|
|
183350
183367
|
init_drizzle_orm();
|
|
183368
|
+
|
|
183369
|
+
// ../../backend/src/lib/attachment-image-key.ts
|
|
183370
|
+
var pendingWebpSuffix = ".webp.pending";
|
|
183371
|
+
function pendingWebpAttachmentKey(prefix, uploadId) {
|
|
183372
|
+
return `${prefix}/${uploadId}${pendingWebpSuffix}`;
|
|
183373
|
+
}
|
|
183374
|
+
function committedAttachmentKey(sourceKey) {
|
|
183375
|
+
return sourceKey.endsWith(pendingWebpSuffix) ? sourceKey.slice(0, -".pending".length) : sourceKey;
|
|
183376
|
+
}
|
|
183377
|
+
|
|
183378
|
+
// ../../backend/src/lib/attachment-storage-cleanup.ts
|
|
183351
183379
|
init_logger3();
|
|
183352
183380
|
|
|
183353
183381
|
// ../../backend/src/lib/runtime-options.ts
|
|
@@ -183539,7 +183567,9 @@ async function claimCleanupPage(leaseOwner, now, pageSize, quotaReleaseAvailable
|
|
|
183539
183567
|
AND NOT EXISTS (
|
|
183540
183568
|
SELECT 1
|
|
183541
183569
|
FROM public.pending_attachment_uploads AS pending
|
|
183542
|
-
WHERE pending.storage_key = candidate.storage_key
|
|
183570
|
+
WHERE (pending.storage_key = candidate.storage_key
|
|
183571
|
+
OR (pending.storage_key LIKE '%.webp.pending'
|
|
183572
|
+
AND left(pending.storage_key, length(pending.storage_key) - 8) = candidate.storage_key))
|
|
183543
183573
|
AND pending.lease_owner LIKE 'confirm:%'
|
|
183544
183574
|
AND pending.lease_expires_at IS NOT NULL
|
|
183545
183575
|
AND pending.lease_expires_at > ${nowTimestamp}
|
|
@@ -183581,7 +183611,7 @@ function quotaContext(row, signal) {
|
|
|
183581
183611
|
workspaceId: row.workspace_id,
|
|
183582
183612
|
actorUserId: row.actor_user_id,
|
|
183583
183613
|
documentId: row.document_id,
|
|
183584
|
-
storageKey: row.storage_key,
|
|
183614
|
+
storageKey: committedAttachmentKey(row.storage_key),
|
|
183585
183615
|
proposedSize: row.size,
|
|
183586
183616
|
requestId: row.id,
|
|
183587
183617
|
idempotencyKey: row.quota_operation_key,
|
|
@@ -184050,7 +184080,7 @@ function validClaims(value) {
|
|
|
184050
184080
|
if (typeof value !== "object" || value === null)
|
|
184051
184081
|
return false;
|
|
184052
184082
|
const claims = value;
|
|
184053
|
-
return typeof claims.id === "string" && typeof claims.documentId === "string" && typeof claims.actorUserId === "string" && (claims.workspaceId === null || typeof claims.workspaceId === "string") && typeof claims.storageKey === "string" && typeof claims.expiresAt === "number" && Number.isFinite(claims.expiresAt);
|
|
184083
|
+
return typeof claims.id === "string" && typeof claims.documentId === "string" && typeof claims.actorUserId === "string" && (claims.workspaceId === null || typeof claims.workspaceId === "string") && typeof claims.storageKey === "string" && (claims.sourceSha256 === undefined || typeof claims.sourceSha256 === "string" && /^[a-f0-9]{64}$/.test(claims.sourceSha256)) && typeof claims.expiresAt === "number" && Number.isFinite(claims.expiresAt);
|
|
184054
184084
|
}
|
|
184055
184085
|
function attachmentUploadTokenHash(token) {
|
|
184056
184086
|
return new Bun.CryptoHasher("sha256").update(token).digest("hex");
|
|
@@ -184077,8 +184107,134 @@ async function verifyAttachmentUploadToken(token) {
|
|
|
184077
184107
|
}
|
|
184078
184108
|
}
|
|
184079
184109
|
|
|
184110
|
+
// ../../backend/src/lib/attachment-webp.ts
|
|
184111
|
+
import sharp from "sharp";
|
|
184112
|
+
var maxPixels = 40000000;
|
|
184113
|
+
var maxFrames = 120;
|
|
184114
|
+
var maxConcurrentConversions = 2;
|
|
184115
|
+
var activeConversions = 0;
|
|
184116
|
+
|
|
184117
|
+
class AttachmentImageBusyError extends Error {
|
|
184118
|
+
constructor() {
|
|
184119
|
+
super("Image processing capacity is temporarily exhausted");
|
|
184120
|
+
this.name = "AttachmentImageBusyError";
|
|
184121
|
+
}
|
|
184122
|
+
}
|
|
184123
|
+
var sourceMime = {
|
|
184124
|
+
png: "image/png",
|
|
184125
|
+
jpeg: "image/jpeg",
|
|
184126
|
+
gif: "image/gif",
|
|
184127
|
+
webp: "image/webp"
|
|
184128
|
+
};
|
|
184129
|
+
async function readAttachmentImageSource(source, expectedBytes, maxBytes) {
|
|
184130
|
+
if (!Number.isSafeInteger(expectedBytes) || expectedBytes <= 0 || expectedBytes > maxBytes) {
|
|
184131
|
+
throw new Error("Invalid attachment source size");
|
|
184132
|
+
}
|
|
184133
|
+
const bytes = Buffer.allocUnsafe(expectedBytes);
|
|
184134
|
+
let offset = 0;
|
|
184135
|
+
for await (const chunk of source) {
|
|
184136
|
+
if (chunk.byteLength > expectedBytes - offset) {
|
|
184137
|
+
throw new Error("Attachment source size changed");
|
|
184138
|
+
}
|
|
184139
|
+
bytes.set(chunk, offset);
|
|
184140
|
+
offset += chunk.byteLength;
|
|
184141
|
+
}
|
|
184142
|
+
if (offset !== expectedBytes)
|
|
184143
|
+
throw new Error("Attachment source size changed");
|
|
184144
|
+
return bytes;
|
|
184145
|
+
}
|
|
184146
|
+
async function normalizeAttachmentImage(source, mimeType, filename, maxOutputBytes) {
|
|
184147
|
+
if (activeConversions >= maxConcurrentConversions) {
|
|
184148
|
+
throw new AttachmentImageBusyError;
|
|
184149
|
+
}
|
|
184150
|
+
activeConversions++;
|
|
184151
|
+
try {
|
|
184152
|
+
return await encodeAttachmentImage(source, mimeType, filename, maxOutputBytes);
|
|
184153
|
+
} finally {
|
|
184154
|
+
activeConversions--;
|
|
184155
|
+
}
|
|
184156
|
+
}
|
|
184157
|
+
async function encodeAttachmentImage(source, mimeType, filename, maxOutputBytes) {
|
|
184158
|
+
const image = sharp(source, {
|
|
184159
|
+
animated: true,
|
|
184160
|
+
failOn: "warning",
|
|
184161
|
+
limitInputPixels: maxPixels
|
|
184162
|
+
});
|
|
184163
|
+
const {
|
|
184164
|
+
format,
|
|
184165
|
+
pages = 1,
|
|
184166
|
+
width,
|
|
184167
|
+
height,
|
|
184168
|
+
pageHeight
|
|
184169
|
+
} = await image.metadata();
|
|
184170
|
+
if (!format || !Object.hasOwn(sourceMime, format) || sourceMime[format] !== mimeType) {
|
|
184171
|
+
throw new Error("Unsupported attachment image format");
|
|
184172
|
+
}
|
|
184173
|
+
if (!width || !height || pages > maxFrames || width * (pageHeight ?? height) * pages > maxPixels) {
|
|
184174
|
+
throw new Error("Attachment image exceeds decoded size limits");
|
|
184175
|
+
}
|
|
184176
|
+
const bytes = format === "webp" ? await image.stats().then(() => source) : await image.autoOrient().webp({ lossless: format !== "jpeg", quality: 85 }).toBuffer();
|
|
184177
|
+
if (bytes.length > maxOutputBytes) {
|
|
184178
|
+
throw new Error("Converted attachment exceeds size limit");
|
|
184179
|
+
}
|
|
184180
|
+
return {
|
|
184181
|
+
bytes,
|
|
184182
|
+
mimeType: "image/webp",
|
|
184183
|
+
filename: filename.replace(/\.[^.]+$/, "") + ".webp"
|
|
184184
|
+
};
|
|
184185
|
+
}
|
|
184186
|
+
|
|
184187
|
+
class AttachmentImageValidationError extends Error {
|
|
184188
|
+
constructor() {
|
|
184189
|
+
super("Image could not be validated or converted to WebP");
|
|
184190
|
+
this.name = "AttachmentImageValidationError";
|
|
184191
|
+
}
|
|
184192
|
+
}
|
|
184193
|
+
async function prepareAttachmentWebp(input) {
|
|
184194
|
+
const storageKey = committedAttachmentKey(input.sourceKey);
|
|
184195
|
+
if (storageKey === input.sourceKey) {
|
|
184196
|
+
throw new Error("Converted image requires a separate permanent storage key");
|
|
184197
|
+
}
|
|
184198
|
+
const source = await readAttachmentImageSource(input.source, input.expectedBytes, input.maxBytes);
|
|
184199
|
+
if (input.sourceSha256 !== undefined) {
|
|
184200
|
+
const actual = new Bun.CryptoHasher("sha256").update(source).digest("hex");
|
|
184201
|
+
if (actual !== input.sourceSha256)
|
|
184202
|
+
throw new AttachmentImageValidationError;
|
|
184203
|
+
}
|
|
184204
|
+
let image;
|
|
184205
|
+
try {
|
|
184206
|
+
image = await normalizeAttachmentImage(source, input.mimeType, input.filename, input.maxBytes);
|
|
184207
|
+
} catch (error) {
|
|
184208
|
+
if (error instanceof AttachmentImageBusyError)
|
|
184209
|
+
throw error;
|
|
184210
|
+
throw new AttachmentImageValidationError;
|
|
184211
|
+
}
|
|
184212
|
+
await input.trackOutput(storageKey, image.bytes.length);
|
|
184213
|
+
await input.writeOutput(storageKey, image.bytes, image.mimeType);
|
|
184214
|
+
return {
|
|
184215
|
+
storageKey,
|
|
184216
|
+
filename: image.filename,
|
|
184217
|
+
mimeType: image.mimeType,
|
|
184218
|
+
size: image.bytes.length
|
|
184219
|
+
};
|
|
184220
|
+
}
|
|
184221
|
+
|
|
184080
184222
|
// ../../backend/src/api/routes/attachments.ts
|
|
184081
184223
|
init_config();
|
|
184224
|
+
|
|
184225
|
+
// ../../backend/src/lib/document-create-idempotency.ts
|
|
184226
|
+
var IDEMPOTENCY_KEY_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/;
|
|
184227
|
+
function documentCreateIdempotencyKey(request) {
|
|
184228
|
+
const value = request.headers.get("idempotency-key");
|
|
184229
|
+
if (value === null)
|
|
184230
|
+
return null;
|
|
184231
|
+
return IDEMPOTENCY_KEY_PATTERN.test(value) ? value : "invalid";
|
|
184232
|
+
}
|
|
184233
|
+
function documentCreateWorkspaceIdentity(userId, workspaceId) {
|
|
184234
|
+
return workspaceId ?? `personal:${userId}`;
|
|
184235
|
+
}
|
|
184236
|
+
|
|
184237
|
+
// ../../backend/src/api/routes/attachments.ts
|
|
184082
184238
|
init_logger3();
|
|
184083
184239
|
|
|
184084
184240
|
// ../../backend/src/lib/remote-image.ts
|
|
@@ -184441,7 +184597,7 @@ function attachmentQuotaContext(ctx, actorUserId, documentId, storageKey, propos
|
|
|
184441
184597
|
workspaceId: ctx.workspaceId,
|
|
184442
184598
|
actorUserId,
|
|
184443
184599
|
documentId,
|
|
184444
|
-
storageKey,
|
|
184600
|
+
storageKey: committedAttachmentKey(storageKey),
|
|
184445
184601
|
proposedSize,
|
|
184446
184602
|
requestId,
|
|
184447
184603
|
idempotencyKey
|
|
@@ -184595,6 +184751,17 @@ var attachmentRoutes = new Elysia({ prefix: "/api" }).post("/documents/:id/attac
|
|
|
184595
184751
|
const filename = typeof payload?.filename === "string" ? payload.filename : "";
|
|
184596
184752
|
const contentType = typeof payload?.contentType === "string" ? payload.contentType : "";
|
|
184597
184753
|
const size = typeof payload?.size === "number" ? payload.size : -1;
|
|
184754
|
+
const sourceSha256 = payload?.sourceSha256;
|
|
184755
|
+
if (sourceSha256 !== undefined && (typeof sourceSha256 !== "string" || !/^[a-f0-9]{64}$/.test(sourceSha256))) {
|
|
184756
|
+
set.status = 400;
|
|
184757
|
+
return { error: "sourceSha256 must be a lowercase SHA-256 digest" };
|
|
184758
|
+
}
|
|
184759
|
+
if (sourceSha256 !== undefined && !config3.DOCSMINT_ATTACHMENT_WEBP_ENABLED) {
|
|
184760
|
+
set.status = 400;
|
|
184761
|
+
return {
|
|
184762
|
+
error: "Source checksum validation requires WebP upload finalization"
|
|
184763
|
+
};
|
|
184764
|
+
}
|
|
184598
184765
|
if (!filename || filename.length > 255) {
|
|
184599
184766
|
set.status = 400;
|
|
184600
184767
|
return { error: "filename must be a non-empty string \u2264 255 chars" };
|
|
@@ -184613,22 +184780,30 @@ var attachmentRoutes = new Elysia({ prefix: "/api" }).post("/documents/:id/attac
|
|
|
184613
184780
|
error: `File too large. Maximum size: ${ATTACHMENT_MAX_SIZE_BYTES / 1024 / 1024}MB`
|
|
184614
184781
|
};
|
|
184615
184782
|
}
|
|
184783
|
+
const idempotencyKey = documentCreateIdempotencyKey(request);
|
|
184784
|
+
if (idempotencyKey === "invalid" || idempotencyKey && typeof sourceSha256 !== "string") {
|
|
184785
|
+
set.status = 400;
|
|
184786
|
+
return { error: "A valid Idempotency-Key requires sourceSha256" };
|
|
184787
|
+
}
|
|
184788
|
+
const fingerprint = new Bun.CryptoHasher("sha256").update(JSON.stringify([filename, contentType, size, sourceSha256 ?? null])).digest("hex");
|
|
184616
184789
|
const ext = filename.split(".").pop() ?? "bin";
|
|
184617
|
-
const
|
|
184618
|
-
|
|
184619
|
-
|
|
184620
|
-
|
|
184621
|
-
|
|
184790
|
+
const prefix = attachmentKeyPrefix(ctx, userId, documentId);
|
|
184791
|
+
let key = config3.DOCSMINT_ATTACHMENT_WEBP_ENABLED ? pendingWebpAttachmentKey(prefix, nanoid2()) : `${prefix}/${nanoid2()}.${ext}`;
|
|
184792
|
+
let admissionId = crypto.randomUUID();
|
|
184793
|
+
let expiresAt = new Date(Date.now() + PRESIGN_EXPIRY_SECONDS * 1000);
|
|
184794
|
+
let quotaOperationKey = `attachment:${documentId}:${committedAttachmentKey(key)}`;
|
|
184795
|
+
const presignLeaseOwner = `presign:${crypto.randomUUID()}`;
|
|
184622
184796
|
const presignLeaseExpiresAt = new Date(Date.now() + 60000);
|
|
184623
|
-
|
|
184797
|
+
let uploadToken = await signAttachmentUploadToken({
|
|
184624
184798
|
id: admissionId,
|
|
184625
184799
|
documentId,
|
|
184626
184800
|
actorUserId: userId,
|
|
184627
184801
|
workspaceId: ctx.workspaceId ?? null,
|
|
184628
184802
|
storageKey: key,
|
|
184629
|
-
expiresAt: expiresAt.getTime()
|
|
184803
|
+
expiresAt: expiresAt.getTime(),
|
|
184804
|
+
...typeof sourceSha256 === "string" ? { sourceSha256 } : {}
|
|
184630
184805
|
});
|
|
184631
|
-
|
|
184806
|
+
let quotaContext = attachmentQuotaContext(ctx, userId, documentId, key, size, admissionId, quotaOperationKey);
|
|
184632
184807
|
const admission = attachmentQuotaAdmission(set);
|
|
184633
184808
|
if (admission === undefined) {
|
|
184634
184809
|
return { error: "Attachment storage quota admission is unavailable" };
|
|
@@ -184641,7 +184816,40 @@ var attachmentRoutes = new Elysia({ prefix: "/api" }).post("/documents/:id/attac
|
|
|
184641
184816
|
}
|
|
184642
184817
|
let reservationId;
|
|
184643
184818
|
try {
|
|
184644
|
-
await withTenant(ctx, async (tx) => {
|
|
184819
|
+
const replay = await withTenant(ctx, async (tx) => {
|
|
184820
|
+
if (idempotencyKey) {
|
|
184821
|
+
const workspaceIdentity = documentCreateWorkspaceIdentity(userId, ctx.workspaceId);
|
|
184822
|
+
await tx.execute(sql`SELECT pg_advisory_xact_lock(hashtextextended(${JSON.stringify([workspaceIdentity, userId, documentId, idempotencyKey])}, 0))`);
|
|
184823
|
+
const [operation] = await tx.select().from(attachmentUploadOperations).where(and(eq(attachmentUploadOperations.workspaceId, workspaceIdentity), eq(attachmentUploadOperations.actorUserId, userId), eq(attachmentUploadOperations.documentId, documentId), eq(attachmentUploadOperations.idempotencyKey, idempotencyKey))).limit(1);
|
|
184824
|
+
if (operation) {
|
|
184825
|
+
if (operation.requestFingerprint !== fingerprint)
|
|
184826
|
+
return { error: "conflict" };
|
|
184827
|
+
const [existing] = await tx.select().from(attachments).where(and(eq(attachments.documentId, documentId), eq(attachments.storageKey, committedAttachmentKey(operation.storageKey)))).limit(1);
|
|
184828
|
+
if (existing)
|
|
184829
|
+
return { operation, completed: true };
|
|
184830
|
+
const [pending] = await tx.select().from(pendingAttachmentUploads).where(eq(pendingAttachmentUploads.id, operation.id)).limit(1).for("update");
|
|
184831
|
+
if (!pending || operation.expiresAt.getTime() <= Date.now())
|
|
184832
|
+
return { error: "expired" };
|
|
184833
|
+
if (pending.leaseExpiresAt && pending.leaseExpiresAt.getTime() > Date.now())
|
|
184834
|
+
return { error: "busy" };
|
|
184835
|
+
await tx.update(pendingAttachmentUploads).set({
|
|
184836
|
+
leaseOwner: presignLeaseOwner,
|
|
184837
|
+
leaseExpiresAt: presignLeaseExpiresAt
|
|
184838
|
+
}).where(eq(pendingAttachmentUploads.id, operation.id));
|
|
184839
|
+
return { operation, pending, completed: false };
|
|
184840
|
+
}
|
|
184841
|
+
await tx.insert(attachmentUploadOperations).values({
|
|
184842
|
+
id: admissionId,
|
|
184843
|
+
workspaceId: workspaceIdentity,
|
|
184844
|
+
actorUserId: userId,
|
|
184845
|
+
documentId,
|
|
184846
|
+
idempotencyKey,
|
|
184847
|
+
requestFingerprint: fingerprint,
|
|
184848
|
+
sourceSha256,
|
|
184849
|
+
storageKey: key,
|
|
184850
|
+
expiresAt
|
|
184851
|
+
});
|
|
184852
|
+
}
|
|
184645
184853
|
await tx.insert(pendingAttachmentUploads).values({
|
|
184646
184854
|
id: admissionId,
|
|
184647
184855
|
documentId,
|
|
@@ -184658,8 +184866,43 @@ var attachmentRoutes = new Elysia({ prefix: "/api" }).post("/documents/:id/attac
|
|
|
184658
184866
|
leaseExpiresAt: presignLeaseExpiresAt,
|
|
184659
184867
|
expiresAt
|
|
184660
184868
|
});
|
|
184869
|
+
return null;
|
|
184661
184870
|
});
|
|
184662
|
-
if (
|
|
184871
|
+
if (replay && "error" in replay) {
|
|
184872
|
+
set.status = replay.error === "expired" ? 410 : 409;
|
|
184873
|
+
if (replay.error === "busy")
|
|
184874
|
+
set.headers["Retry-After"] = "1";
|
|
184875
|
+
return {
|
|
184876
|
+
error: replay.error === "conflict" ? "Idempotency-Key was already used for different image bytes or metadata" : replay.error === "expired" ? "The upload operation expired or was removed; use a new operation key" : "The upload operation is in progress; retry with the same Idempotency-Key"
|
|
184877
|
+
};
|
|
184878
|
+
}
|
|
184879
|
+
if (replay && "operation" in replay) {
|
|
184880
|
+
key = replay.operation.storageKey;
|
|
184881
|
+
admissionId = replay.operation.id;
|
|
184882
|
+
expiresAt = replay.operation.expiresAt;
|
|
184883
|
+
quotaOperationKey = `attachment:${documentId}:${committedAttachmentKey(key)}`;
|
|
184884
|
+
uploadToken = await signAttachmentUploadToken({
|
|
184885
|
+
id: admissionId,
|
|
184886
|
+
documentId,
|
|
184887
|
+
actorUserId: userId,
|
|
184888
|
+
workspaceId: ctx.workspaceId ?? null,
|
|
184889
|
+
storageKey: key,
|
|
184890
|
+
expiresAt: expiresAt.getTime(),
|
|
184891
|
+
...typeof sourceSha256 === "string" ? { sourceSha256 } : {}
|
|
184892
|
+
});
|
|
184893
|
+
if (replay.completed)
|
|
184894
|
+
return {
|
|
184895
|
+
url: "",
|
|
184896
|
+
key,
|
|
184897
|
+
uploadToken,
|
|
184898
|
+
alreadyConfirmed: true,
|
|
184899
|
+
maxSize: ATTACHMENT_MAX_SIZE_BYTES,
|
|
184900
|
+
expiresIn: 0
|
|
184901
|
+
};
|
|
184902
|
+
reservationId = replay.pending.quotaReservationId ?? undefined;
|
|
184903
|
+
quotaContext = attachmentQuotaContext(ctx, userId, documentId, key, size, admissionId, quotaOperationKey);
|
|
184904
|
+
}
|
|
184905
|
+
if (admission && quotaContext && !reservationId) {
|
|
184663
184906
|
try {
|
|
184664
184907
|
reservationId = (await admission.reserve(quotaContext)).id;
|
|
184665
184908
|
} catch (error) {
|
|
@@ -184669,7 +184912,7 @@ var attachmentRoutes = new Elysia({ prefix: "/api" }).post("/documents/:id/attac
|
|
|
184669
184912
|
leaseExpiresAt: new Date,
|
|
184670
184913
|
lastError: retryable ? "quota_reserve_retryable" : "quota_reserve_terminal",
|
|
184671
184914
|
quotaState: retryable ? "reserve_pending" : "not_required"
|
|
184672
|
-
}).where(eq(pendingAttachmentUploads.id, admissionId))).catch(() => {
|
|
184915
|
+
}).where(and(eq(pendingAttachmentUploads.id, admissionId), eq(pendingAttachmentUploads.leaseOwner, presignLeaseOwner)))).catch(() => {
|
|
184673
184916
|
return;
|
|
184674
184917
|
});
|
|
184675
184918
|
logger3.warn({ err: error, documentId, retryable }, "Attachment storage quota reservation rejected");
|
|
@@ -184685,7 +184928,9 @@ var attachmentRoutes = new Elysia({ prefix: "/api" }).post("/documents/:id/attac
|
|
|
184685
184928
|
if (reservedRows.length !== 1)
|
|
184686
184929
|
throw new Error("attachment_admission_lease_lost");
|
|
184687
184930
|
}
|
|
184688
|
-
const url = await getSignedUrl(storagePublic, new PutObjectCommand({ Bucket: BUCKET, Key: key }), {
|
|
184931
|
+
const url = await getSignedUrl(storagePublic, new PutObjectCommand({ Bucket: BUCKET, Key: key }), {
|
|
184932
|
+
expiresIn: Math.max(1, Math.ceil((expiresAt.getTime() - Date.now()) / 1000))
|
|
184933
|
+
});
|
|
184689
184934
|
const issuedRows = await withTenant(ctx, (tx) => tx.update(pendingAttachmentUploads).set({
|
|
184690
184935
|
urlIssuedAt: new Date,
|
|
184691
184936
|
leaseOwner: null,
|
|
@@ -184699,10 +184944,10 @@ var attachmentRoutes = new Elysia({ prefix: "/api" }).post("/documents/:id/attac
|
|
|
184699
184944
|
uploadToken,
|
|
184700
184945
|
...reservationId ? { quotaReservationId: reservationId } : {},
|
|
184701
184946
|
maxSize: ATTACHMENT_MAX_SIZE_BYTES,
|
|
184702
|
-
expiresIn:
|
|
184947
|
+
expiresIn: Math.max(0, Math.ceil((expiresAt.getTime() - Date.now()) / 1000))
|
|
184703
184948
|
};
|
|
184704
184949
|
} catch (err) {
|
|
184705
|
-
await withTenant(ctx, (tx) => tx.update(pendingAttachmentUploads).set({ leaseOwner: null, leaseExpiresAt: new Date }).where(eq(pendingAttachmentUploads.id, admissionId))).catch(() => {
|
|
184950
|
+
await withTenant(ctx, (tx) => tx.update(pendingAttachmentUploads).set({ leaseOwner: null, leaseExpiresAt: new Date }).where(and(eq(pendingAttachmentUploads.id, admissionId), eq(pendingAttachmentUploads.leaseOwner, presignLeaseOwner)))).catch(() => {
|
|
184706
184951
|
return;
|
|
184707
184952
|
});
|
|
184708
184953
|
if (isAccountPurgeFencedError(err)) {
|
|
@@ -184760,7 +185005,7 @@ var attachmentRoutes = new Elysia({ prefix: "/api" }).post("/documents/:id/attac
|
|
|
184760
185005
|
return accountPurgeFencedResponse();
|
|
184761
185006
|
}
|
|
184762
185007
|
if (!claimed) {
|
|
184763
|
-
const [existing] = await withTenant(claimCtx, (tx) => tx.select().from(attachments).where(eq(attachments.storageKey, key)).limit(1));
|
|
185008
|
+
const [existing] = await withTenant(claimCtx, (tx) => tx.select().from(attachments).where(eq(attachments.storageKey, committedAttachmentKey(key))).limit(1));
|
|
184764
185009
|
if (existing && authorization.authorized) {
|
|
184765
185010
|
set.status = 201;
|
|
184766
185011
|
return {
|
|
@@ -184834,7 +185079,7 @@ var attachmentRoutes = new Elysia({ prefix: "/api" }).post("/documents/:id/attac
|
|
|
184834
185079
|
set.status = 409;
|
|
184835
185080
|
return { error: "Upload not found in storage \u2014 please retry upload" };
|
|
184836
185081
|
}
|
|
184837
|
-
|
|
185082
|
+
let storedSize = headOutput.ContentLength;
|
|
184838
185083
|
if (typeof storedSize !== "number" || !Number.isFinite(storedSize) || storedSize <= 0) {
|
|
184839
185084
|
set.status = 409;
|
|
184840
185085
|
return { error: "Upload size could not be verified" };
|
|
@@ -184845,6 +185090,66 @@ var attachmentRoutes = new Elysia({ prefix: "/api" }).post("/documents/:id/attac
|
|
|
184845
185090
|
error: `Uploaded file exceeds the ${config3.ATTACHMENT_MAX_SIZE_MB}MB limit`
|
|
184846
185091
|
};
|
|
184847
185092
|
}
|
|
185093
|
+
let prepared = {
|
|
185094
|
+
storageKey: key,
|
|
185095
|
+
filename: claimed.filename,
|
|
185096
|
+
mimeType: claimed.mimeType
|
|
185097
|
+
};
|
|
185098
|
+
if (committedAttachmentKey(key) !== key) {
|
|
185099
|
+
const outputId = claimed.id;
|
|
185100
|
+
try {
|
|
185101
|
+
const source = await storage.send(new GetObjectCommand({ Bucket: BUCKET, Key: key }));
|
|
185102
|
+
if (!source.Body || typeof source.Body[Symbol.asyncIterator] !== "function") {
|
|
185103
|
+
throw new Error("Image source stream is unavailable");
|
|
185104
|
+
}
|
|
185105
|
+
const image = await prepareAttachmentWebp({
|
|
185106
|
+
source: source.Body,
|
|
185107
|
+
expectedBytes: storedSize,
|
|
185108
|
+
maxBytes: ATTACHMENT_MAX_SIZE_BYTES,
|
|
185109
|
+
mimeType: claimed.mimeType,
|
|
185110
|
+
filename: claimed.filename,
|
|
185111
|
+
sourceKey: key,
|
|
185112
|
+
sourceSha256: claims.sourceSha256,
|
|
185113
|
+
trackOutput: (storageKey, size) => withTenant(claimCtx, (tx) => stageAttachmentStorageCleanup(tx, {
|
|
185114
|
+
sourceKind: "uncommitted_upload",
|
|
185115
|
+
sourceId: outputId,
|
|
185116
|
+
storageKey,
|
|
185117
|
+
size,
|
|
185118
|
+
documentId,
|
|
185119
|
+
actorUserId: claims.actorUserId,
|
|
185120
|
+
ownerUserId: claimed.ownerUserId,
|
|
185121
|
+
requestedByUserId: claims.actorUserId,
|
|
185122
|
+
workspaceId: claims.workspaceId,
|
|
185123
|
+
quotaOperationKey: claimed.quotaOperationKey,
|
|
185124
|
+
quotaReleaseKind: "none",
|
|
185125
|
+
notBefore: storageWriteHoldNotBefore()
|
|
185126
|
+
})),
|
|
185127
|
+
writeOutput: async (storageKey, bytes, mimeType) => {
|
|
185128
|
+
await storage.send(new PutObjectCommand({
|
|
185129
|
+
Bucket: BUCKET,
|
|
185130
|
+
Key: storageKey,
|
|
185131
|
+
Body: bytes,
|
|
185132
|
+
ContentType: mimeType,
|
|
185133
|
+
ContentLength: bytes.length
|
|
185134
|
+
}));
|
|
185135
|
+
}
|
|
185136
|
+
});
|
|
185137
|
+
prepared = image;
|
|
185138
|
+
storedSize = image.size;
|
|
185139
|
+
} catch (error) {
|
|
185140
|
+
logger3.warn({ err: error, admissionId: claimed.id }, "Image conversion failed");
|
|
185141
|
+
if (error instanceof AttachmentImageValidationError) {
|
|
185142
|
+
set.status = 422;
|
|
185143
|
+
return { error: "Image could not be converted to WebP" };
|
|
185144
|
+
}
|
|
185145
|
+
abandonRejectedConfirm = false;
|
|
185146
|
+
set.headers["Retry-After"] = "1";
|
|
185147
|
+
set.status = 503;
|
|
185148
|
+
return {
|
|
185149
|
+
error: "Image processing is temporarily unavailable; retry confirmation"
|
|
185150
|
+
};
|
|
185151
|
+
}
|
|
185152
|
+
}
|
|
184848
185153
|
if (admission && quotaContext && claimed.quotaReservationId) {
|
|
184849
185154
|
try {
|
|
184850
185155
|
const finalizeRows = await withTenant(claimCtx, (tx) => tx.update(pendingAttachmentUploads).set({
|
|
@@ -184886,24 +185191,41 @@ var attachmentRoutes = new Elysia({ prefix: "/api" }).post("/documents/:id/attac
|
|
|
184886
185191
|
});
|
|
184887
185192
|
if (!activeClaim)
|
|
184888
185193
|
return null;
|
|
184889
|
-
const [raced] = await tx.select().from(attachments).where(eq(attachments.storageKey, key)).limit(1);
|
|
185194
|
+
const [raced] = await tx.select().from(attachments).where(eq(attachments.storageKey, committedAttachmentKey(key))).limit(1);
|
|
184890
185195
|
let result = raced;
|
|
184891
185196
|
if (!result) {
|
|
184892
185197
|
[result] = await tx.insert(attachments).values({
|
|
184893
185198
|
documentId,
|
|
184894
185199
|
workspaceId: claims.workspaceId,
|
|
184895
185200
|
uploadedBy: claims.actorUserId,
|
|
184896
|
-
filename:
|
|
184897
|
-
mimeType:
|
|
185201
|
+
filename: prepared.filename,
|
|
185202
|
+
mimeType: prepared.mimeType,
|
|
184898
185203
|
size: storedSize,
|
|
184899
|
-
storageKey:
|
|
185204
|
+
storageKey: prepared.storageKey
|
|
184900
185205
|
}).onConflictDoNothing({ target: attachments.storageKey }).returning();
|
|
184901
185206
|
}
|
|
184902
185207
|
if (!result) {
|
|
184903
|
-
[result] = await tx.select().from(attachments).where(eq(attachments.storageKey, key)).limit(1);
|
|
185208
|
+
[result] = await tx.select().from(attachments).where(eq(attachments.storageKey, committedAttachmentKey(key))).limit(1);
|
|
184904
185209
|
}
|
|
184905
185210
|
if (!result)
|
|
184906
185211
|
return null;
|
|
185212
|
+
if (prepared.storageKey !== key) {
|
|
185213
|
+
await tx.delete(attachmentStorageCleanupOutbox).where(and(eq(attachmentStorageCleanupOutbox.sourceKind, "uncommitted_upload"), eq(attachmentStorageCleanupOutbox.sourceId, claimed.id)));
|
|
185214
|
+
await stageAttachmentStorageCleanup(tx, {
|
|
185215
|
+
sourceKind: "uncommitted_upload",
|
|
185216
|
+
sourceId: crypto.randomUUID(),
|
|
185217
|
+
storageKey: key,
|
|
185218
|
+
documentId,
|
|
185219
|
+
actorUserId: claims.actorUserId,
|
|
185220
|
+
ownerUserId: claimed.ownerUserId,
|
|
185221
|
+
requestedByUserId: claims.actorUserId,
|
|
185222
|
+
workspaceId: claims.workspaceId,
|
|
185223
|
+
size: claimed.declaredSize,
|
|
185224
|
+
quotaOperationKey: claimed.quotaOperationKey,
|
|
185225
|
+
quotaReleaseKind: "none",
|
|
185226
|
+
retainUntil: claimed.expiresAt
|
|
185227
|
+
});
|
|
185228
|
+
}
|
|
184907
185229
|
await tx.delete(pendingAttachmentUploads).where(and(eq(pendingAttachmentUploads.id, claims.id), eq(pendingAttachmentUploads.tokenHash, tokenHash), eq(pendingAttachmentUploads.leaseOwner, claimed.leaseOwner)));
|
|
184908
185230
|
return result;
|
|
184909
185231
|
});
|
|
@@ -184991,7 +185313,28 @@ var attachmentRoutes = new Elysia({ prefix: "/api" }).post("/documents/:id/attac
|
|
|
184991
185313
|
error: `File too large. Maximum size: ${LEGACY_MAX_FILE_SIZE / 1024 / 1024}MB. New uploads should use the presigned URL flow.`
|
|
184992
185314
|
};
|
|
184993
185315
|
}
|
|
184994
|
-
const
|
|
185316
|
+
const source = Buffer.from(await file.arrayBuffer());
|
|
185317
|
+
let image = {
|
|
185318
|
+
bytes: source,
|
|
185319
|
+
mimeType: file.type,
|
|
185320
|
+
filename: file.name
|
|
185321
|
+
};
|
|
185322
|
+
if (config3.DOCSMINT_ATTACHMENT_WEBP_ENABLED) {
|
|
185323
|
+
try {
|
|
185324
|
+
image = await normalizeAttachmentImage(source, file.type, file.name, LEGACY_MAX_FILE_SIZE);
|
|
185325
|
+
} catch (error) {
|
|
185326
|
+
if (error instanceof AttachmentImageBusyError) {
|
|
185327
|
+
set.status = 503;
|
|
185328
|
+
set.headers["Retry-After"] = "1";
|
|
185329
|
+
return {
|
|
185330
|
+
error: "Image processing capacity is temporarily exhausted"
|
|
185331
|
+
};
|
|
185332
|
+
}
|
|
185333
|
+
set.status = 422;
|
|
185334
|
+
return { error: "Image could not be converted to WebP" };
|
|
185335
|
+
}
|
|
185336
|
+
}
|
|
185337
|
+
const ext = image.filename.split(".").pop() ?? "bin";
|
|
184995
185338
|
const key = `${attachmentKeyPrefix(ctx, userId, documentId)}/${nanoid2()}.${ext}`;
|
|
184996
185339
|
const cleanupSourceId = crypto.randomUUID();
|
|
184997
185340
|
try {
|
|
@@ -185004,19 +185347,18 @@ var attachmentRoutes = new Elysia({ prefix: "/api" }).post("/documents/:id/attac
|
|
|
185004
185347
|
ownerUserId: userId,
|
|
185005
185348
|
requestedByUserId: userId,
|
|
185006
185349
|
workspaceId: null,
|
|
185007
|
-
size:
|
|
185350
|
+
size: image.bytes.length,
|
|
185008
185351
|
quotaOperationKey: `attachment:${documentId}:${key}`,
|
|
185009
185352
|
quotaReleaseKind: "none",
|
|
185010
185353
|
notBefore: storageWriteHoldNotBefore()
|
|
185011
185354
|
}));
|
|
185012
|
-
const
|
|
185013
|
-
const buffer = Buffer.from(arrayBuffer);
|
|
185355
|
+
const buffer = image.bytes;
|
|
185014
185356
|
await storage.send(new PutObjectCommand({
|
|
185015
185357
|
Bucket: BUCKET,
|
|
185016
185358
|
Key: key,
|
|
185017
185359
|
Body: buffer,
|
|
185018
|
-
ContentType:
|
|
185019
|
-
ContentLength:
|
|
185360
|
+
ContentType: image.mimeType,
|
|
185361
|
+
ContentLength: image.bytes.length
|
|
185020
185362
|
}));
|
|
185021
185363
|
const integrityOk = await verifyUploadIntegrity(buffer, key);
|
|
185022
185364
|
if (!integrityOk) {
|
|
@@ -185030,9 +185372,9 @@ var attachmentRoutes = new Elysia({ prefix: "/api" }).post("/documents/:id/attac
|
|
|
185030
185372
|
documentId,
|
|
185031
185373
|
workspaceId: ctx.workspaceId ?? null,
|
|
185032
185374
|
uploadedBy: userId,
|
|
185033
|
-
filename:
|
|
185034
|
-
mimeType:
|
|
185035
|
-
size:
|
|
185375
|
+
filename: image.filename,
|
|
185376
|
+
mimeType: image.mimeType,
|
|
185377
|
+
size: image.bytes.length,
|
|
185036
185378
|
storageKey: key
|
|
185037
185379
|
}).returning();
|
|
185038
185380
|
await tx.delete(attachmentStorageCleanupOutbox).where(and(eq(attachmentStorageCleanupOutbox.sourceKind, "uncommitted_upload"), eq(attachmentStorageCleanupOutbox.sourceId, cleanupSourceId)));
|
|
@@ -213542,18 +213884,6 @@ var recordAuditEvent = createAuditRecorder({
|
|
|
213542
213884
|
// ../../backend/src/api/routes/documents.ts
|
|
213543
213885
|
init_config();
|
|
213544
213886
|
|
|
213545
|
-
// ../../backend/src/lib/document-create-idempotency.ts
|
|
213546
|
-
var IDEMPOTENCY_KEY_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/;
|
|
213547
|
-
function documentCreateIdempotencyKey(request) {
|
|
213548
|
-
const value = request.headers.get("idempotency-key");
|
|
213549
|
-
if (value === null)
|
|
213550
|
-
return null;
|
|
213551
|
-
return IDEMPOTENCY_KEY_PATTERN.test(value) ? value : "invalid";
|
|
213552
|
-
}
|
|
213553
|
-
function documentCreateWorkspaceIdentity(userId, workspaceId) {
|
|
213554
|
-
return workspaceId ?? `personal:${userId}`;
|
|
213555
|
-
}
|
|
213556
|
-
|
|
213557
213887
|
// ../../backend/src/lib/document-list-query.ts
|
|
213558
213888
|
init_schema2();
|
|
213559
213889
|
init_drizzle_orm();
|
|
@@ -217619,8 +217949,11 @@ class DocsClient {
|
|
|
217619
217949
|
headers.set("Cookie", requestContext.cookie);
|
|
217620
217950
|
if (requestContext?.requestId)
|
|
217621
217951
|
headers.set("X-Request-Id", requestContext.requestId);
|
|
217622
|
-
if (requestContext?.idempotencyKey)
|
|
217952
|
+
if (requestContext?.idempotencyKey === null) {
|
|
217953
|
+
headers.delete("Idempotency-Key");
|
|
217954
|
+
} else if (requestContext?.idempotencyKey) {
|
|
217623
217955
|
headers.set("Idempotency-Key", requestContext.idempotencyKey);
|
|
217956
|
+
}
|
|
217624
217957
|
if (method === "POST" && path === "/api/documents" && !headers.has("Idempotency-Key")) {
|
|
217625
217958
|
headers.set("Idempotency-Key", crypto.randomUUID());
|
|
217626
217959
|
}
|
|
@@ -234260,6 +234593,8 @@ init_zod();
|
|
|
234260
234593
|
init_zod();
|
|
234261
234594
|
init_zod();
|
|
234262
234595
|
init_zod();
|
|
234596
|
+
import { createHash as createHash22 } from "crypto";
|
|
234597
|
+
import { createHash as createHash9 } from "crypto";
|
|
234263
234598
|
import { AsyncLocalStorage } from "async_hooks";
|
|
234264
234599
|
var contracts = new WeakMap;
|
|
234265
234600
|
function object2(value) {
|
|
@@ -234855,8 +235190,11 @@ class DocsClient2 {
|
|
|
234855
235190
|
headers.set("Cookie", requestContext.cookie);
|
|
234856
235191
|
if (requestContext?.requestId)
|
|
234857
235192
|
headers.set("X-Request-Id", requestContext.requestId);
|
|
234858
|
-
if (requestContext?.idempotencyKey)
|
|
235193
|
+
if (requestContext?.idempotencyKey === null) {
|
|
235194
|
+
headers.delete("Idempotency-Key");
|
|
235195
|
+
} else if (requestContext?.idempotencyKey) {
|
|
234859
235196
|
headers.set("Idempotency-Key", requestContext.idempotencyKey);
|
|
235197
|
+
}
|
|
234860
235198
|
if (method === "POST" && path === "/api/documents" && !headers.has("Idempotency-Key")) {
|
|
234861
235199
|
headers.set("Idempotency-Key", crypto.randomUUID());
|
|
234862
235200
|
}
|
|
@@ -235294,6 +235632,7 @@ var operationOutputSchemas = {
|
|
|
235294
235632
|
var variant = (operation, result) => object({ operation: literal(operation), result });
|
|
235295
235633
|
var attachment = object({
|
|
235296
235634
|
id: string2().uuid(),
|
|
235635
|
+
documentId: string2().uuid().optional(),
|
|
235297
235636
|
filename: string2(),
|
|
235298
235637
|
mimeType: string2(),
|
|
235299
235638
|
size: number2().int().nonnegative(),
|
|
@@ -235323,7 +235662,12 @@ var singleToolOutputSchemas = {
|
|
|
235323
235662
|
upload_document_image: attachment,
|
|
235324
235663
|
check_document_attachments: strictObject({
|
|
235325
235664
|
items: array2(attachment),
|
|
235326
|
-
verifiedAttachmentId: string2().uuid().optional()
|
|
235665
|
+
verifiedAttachmentId: string2().uuid().optional(),
|
|
235666
|
+
verification: strictObject({
|
|
235667
|
+
size: number2().int().positive(),
|
|
235668
|
+
mimeType: string2(),
|
|
235669
|
+
sha256: string2().regex(/^[a-f0-9]{64}$/)
|
|
235670
|
+
}).optional()
|
|
235327
235671
|
}),
|
|
235328
235672
|
save_document: union2([
|
|
235329
235673
|
variant("create", operationOutputSchemas.create_document),
|
|
@@ -235389,6 +235733,50 @@ var toolOutputSchemas = {
|
|
|
235389
235733
|
list_workspace_structure: union2([...singleToolOutputSchemas.list_workspace_structure.options, scopedSchemas.list_workspace_structure]),
|
|
235390
235734
|
list_trash: union2([singleToolOutputSchemas.list_trash, scopedSchemas.list_trash])
|
|
235391
235735
|
};
|
|
235736
|
+
var MAX_VERIFIED_IMAGE_BYTES = 16 * 1024 * 1024;
|
|
235737
|
+
async function verifyAttachmentResponse(response, attachment) {
|
|
235738
|
+
const reader = response.body?.getReader();
|
|
235739
|
+
if (!reader)
|
|
235740
|
+
throw new Error("The attachment response has no body.");
|
|
235741
|
+
try {
|
|
235742
|
+
const mimeType = response.headers.get("content-type")?.split(";")[0]?.trim().toLowerCase();
|
|
235743
|
+
if (!response.ok || mimeType !== attachment.mimeType.toLowerCase())
|
|
235744
|
+
throw new Error("The stored attachment MIME type does not match its record.");
|
|
235745
|
+
if (!Number.isSafeInteger(attachment.size) || attachment.size <= 0 || attachment.size > MAX_VERIFIED_IMAGE_BYTES)
|
|
235746
|
+
throw new Error("The attachment exceeds the verification size limit.");
|
|
235747
|
+
const declaredLength = response.headers.get("content-length");
|
|
235748
|
+
if (declaredLength !== null && (!/^[0-9]+$/.test(declaredLength) || Number(declaredLength) !== attachment.size))
|
|
235749
|
+
throw new Error("The stored attachment length does not match its record.");
|
|
235750
|
+
const hash = createHash9("sha256");
|
|
235751
|
+
let size = 0;
|
|
235752
|
+
let prefix = Buffer.alloc(0);
|
|
235753
|
+
for (;; ) {
|
|
235754
|
+
const { done, value } = await reader.read();
|
|
235755
|
+
if (done)
|
|
235756
|
+
break;
|
|
235757
|
+
size += value.byteLength;
|
|
235758
|
+
if (size > attachment.size || size > MAX_VERIFIED_IMAGE_BYTES)
|
|
235759
|
+
throw new Error("The attachment response exceeds its recorded size.");
|
|
235760
|
+
if (prefix.length < 12)
|
|
235761
|
+
prefix = Buffer.concat([
|
|
235762
|
+
prefix,
|
|
235763
|
+
Buffer.from(value.subarray(0, 12 - prefix.length))
|
|
235764
|
+
]);
|
|
235765
|
+
hash.update(value);
|
|
235766
|
+
}
|
|
235767
|
+
if (size !== attachment.size)
|
|
235768
|
+
throw new Error("The attachment response is incomplete.");
|
|
235769
|
+
const imageMatches = mimeType === "image/webp" && prefix.toString("ascii", 0, 4) === "RIFF" && prefix.toString("ascii", 8, 12) === "WEBP" || mimeType === "image/png" && prefix.subarray(0, 8).equals(Buffer.from([137, 80, 78, 71, 13, 10, 26, 10])) || mimeType === "image/jpeg" && prefix[0] === 255 && prefix[1] === 216 && prefix[2] === 255 || mimeType === "image/gif" && ["GIF87a", "GIF89a"].includes(prefix.toString("ascii", 0, 6));
|
|
235770
|
+
if (!imageMatches)
|
|
235771
|
+
throw new Error("The attachment bytes do not match its image MIME type.");
|
|
235772
|
+
return { size, mimeType, sha256: hash.digest("hex") };
|
|
235773
|
+
} finally {
|
|
235774
|
+
await reader.cancel().catch(() => {
|
|
235775
|
+
return;
|
|
235776
|
+
});
|
|
235777
|
+
reader.releaseLock();
|
|
235778
|
+
}
|
|
235779
|
+
}
|
|
235392
235780
|
var DEFAULT_BASE_URL = "http://localhost:50700";
|
|
235393
235781
|
function readConfig() {
|
|
235394
235782
|
const baseUrl = (process.env.HIAI_DOCS_URL ?? DEFAULT_BASE_URL).replace(/\/+$/, "");
|
|
@@ -235426,39 +235814,44 @@ function sanitizeMcpRequestContext(context) {
|
|
|
235426
235814
|
function createMcpDocsClient(docsClient, requestContext) {
|
|
235427
235815
|
const context = sanitizeMcpRequestContext(requestContext);
|
|
235428
235816
|
return {
|
|
235429
|
-
uploadDocumentImage: async (id, filename, mimeType, bytes) => {
|
|
235430
|
-
const descriptor = {
|
|
235431
|
-
|
|
235432
|
-
|
|
235433
|
-
|
|
235434
|
-
|
|
235435
|
-
|
|
235436
|
-
|
|
235437
|
-
|
|
235438
|
-
|
|
235439
|
-
|
|
235440
|
-
|
|
235441
|
-
|
|
235442
|
-
|
|
235817
|
+
uploadDocumentImage: async (id, filename, mimeType, bytes, operationId) => {
|
|
235818
|
+
const descriptor = {
|
|
235819
|
+
filename,
|
|
235820
|
+
contentType: mimeType,
|
|
235821
|
+
size: bytes.byteLength,
|
|
235822
|
+
...operationId ? { sourceSha256: createHash22("sha256").update(bytes).digest("hex") } : {}
|
|
235823
|
+
};
|
|
235824
|
+
const signal = context?.signal ? AbortSignal.any([context.signal, AbortSignal.timeout(30000)]) : AbortSignal.timeout(30000);
|
|
235825
|
+
const uploadContext = { ...context, signal, idempotencyKey: operationId ?? null };
|
|
235826
|
+
const upload = await docsClient.presignAttachment(id, descriptor, uploadContext);
|
|
235827
|
+
if (!upload.alreadyConfirmed) {
|
|
235828
|
+
const response = await fetch(upload.url, {
|
|
235829
|
+
method: "PUT",
|
|
235830
|
+
body: new Blob([Uint8Array.from(bytes)], { type: mimeType }),
|
|
235831
|
+
redirect: "error",
|
|
235832
|
+
signal
|
|
235833
|
+
}).catch(() => {
|
|
235834
|
+
throw new HiaiDocsError("Could not send image bytes to DocsMint storage.", 502, null, "IMAGE_STORAGE_UNAVAILABLE");
|
|
235835
|
+
});
|
|
235836
|
+
await response.body?.cancel();
|
|
235837
|
+
if (!response.ok)
|
|
235838
|
+
throw new HiaiDocsError(`DocsMint storage rejected the image (${response.status}).`, response.status, null, "IMAGE_STORAGE_REJECTED");
|
|
235839
|
+
}
|
|
235443
235840
|
return docsClient.confirmAttachment(id, {
|
|
235444
235841
|
...descriptor,
|
|
235445
235842
|
key: upload.key,
|
|
235446
235843
|
uploadToken: upload.uploadToken,
|
|
235447
235844
|
quotaReservationId: upload.quotaReservationId
|
|
235448
|
-
},
|
|
235845
|
+
}, uploadContext);
|
|
235449
235846
|
},
|
|
235450
235847
|
listAttachments: (id) => docsClient.listAttachments(id, context),
|
|
235451
|
-
verifyAttachment: async (
|
|
235452
|
-
const
|
|
235453
|
-
const
|
|
235454
|
-
|
|
235455
|
-
|
|
235456
|
-
|
|
235457
|
-
|
|
235458
|
-
throw new Error("The attachment is empty.");
|
|
235459
|
-
} finally {
|
|
235460
|
-
await reader.cancel();
|
|
235461
|
-
}
|
|
235848
|
+
verifyAttachment: async (attachment) => {
|
|
235849
|
+
const signal = context?.signal ? AbortSignal.any([context.signal, AbortSignal.timeout(30000)]) : AbortSignal.timeout(30000);
|
|
235850
|
+
const response = await docsClient.fetchAttachment(attachment.id, {
|
|
235851
|
+
...context,
|
|
235852
|
+
signal
|
|
235853
|
+
});
|
|
235854
|
+
return verifyAttachmentResponse(response, attachment);
|
|
235462
235855
|
},
|
|
235463
235856
|
getFolder: (id) => docsClient.getFolder(id, context),
|
|
235464
235857
|
createTag: (input) => docsClient.createTag(input, context),
|
|
@@ -235770,26 +236163,29 @@ function registerCompactCapabilities(server, client, wrap) {
|
|
|
235770
236163
|
documentId: uuid22,
|
|
235771
236164
|
filename: string2().min(1).max(255).regex(/^[^/\\\u0000-\u001f\u007f]+$/).describe("Image file name with extension and without path segments."),
|
|
235772
236165
|
mimeType: _enum(["image/png", "image/jpeg", "image/webp"]).describe("MIME type of the source image."),
|
|
236166
|
+
operationId: string2().regex(/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/).optional().describe("Stable upload operation ID. Reuse with identical bytes and metadata after timeout to prevent duplicates. Requires WebP finalization on the server."),
|
|
235773
236167
|
contentBase64: base642().min(4).max(Math.ceil(maxImageBytes / 3) * 4).describe("Base64 file bytes without a data: prefix.")
|
|
235774
|
-
}), write2, async ({ documentId, filename, mimeType, contentBase64 }) => {
|
|
236168
|
+
}), write2, async ({ documentId, filename, mimeType, contentBase64, operationId }) => {
|
|
235775
236169
|
const bytes = Buffer.from(contentBase64, "base64");
|
|
235776
236170
|
if (!bytes.length || bytes.length > maxImageBytes)
|
|
235777
|
-
throw new
|
|
236171
|
+
throw new HiaiDocsError("Image must be between 1 byte and 2 MiB.", 413, null, "IMAGE_TOO_LARGE");
|
|
235778
236172
|
if (!matchesImageType(bytes, mimeType))
|
|
235779
|
-
throw new
|
|
235780
|
-
return required22(client.uploadDocumentImage, "upload_document_image")(documentId, filename, mimeType, bytes);
|
|
236173
|
+
throw new HiaiDocsError("Image bytes do not match the declared MIME type.", 415, null, "IMAGE_MIME_MISMATCH");
|
|
236174
|
+
return { ...await required22(client.uploadDocumentImage, "upload_document_image")(documentId, filename, mimeType, bytes, operationId), documentId };
|
|
235781
236175
|
});
|
|
235782
236176
|
register("check_document_attachments", "List attachments on a readable document. Supply attachmentId to verify that this attachment belongs to the document and that its stored bytes can be opened with the current access.", strictObject({
|
|
235783
236177
|
documentId: uuid22,
|
|
235784
236178
|
attachmentId: uuid22.optional()
|
|
235785
236179
|
}), read2, async ({ documentId, attachmentId }) => {
|
|
235786
|
-
const
|
|
236180
|
+
const response = await required22(client.listAttachments, "check_document_attachments")(documentId);
|
|
236181
|
+
const items = response.items.map((item) => ({ ...item, documentId }));
|
|
235787
236182
|
if (!attachmentId)
|
|
235788
236183
|
return { items };
|
|
235789
|
-
|
|
235790
|
-
|
|
235791
|
-
|
|
235792
|
-
|
|
236184
|
+
const attachment = items.find((item) => item.id === attachmentId);
|
|
236185
|
+
if (!attachment)
|
|
236186
|
+
throw new HiaiDocsError("Attachment not found in this document.", 404, null, "ATTACHMENT_NOT_FOUND");
|
|
236187
|
+
const verification = await required22(client.verifyAttachment, "check_document_attachments")(attachment);
|
|
236188
|
+
return { items, verifiedAttachmentId: attachmentId, verification };
|
|
235793
236189
|
});
|
|
235794
236190
|
register("delete_document", "Move one document to trash without purging content or versions. Use batch_documents(action=trash) for multiple explicit IDs. Requires write access and an explicit delete request; permanently_delete_document is a separate irreversible action.", strictObject({ id: uuid22 }), destructive, async ({ id }) => {
|
|
235795
236191
|
await required22(client.deleteDocument, "delete_document")(id);
|
|
@@ -236067,7 +236463,7 @@ function registerDocsmintMcpCapabilities(server, client, workspaceRouting, decor
|
|
|
236067
236463
|
registerPromptsAndResources(server, client);
|
|
236068
236464
|
}
|
|
236069
236465
|
function createDocsmintMcpServer(options = {}) {
|
|
236070
|
-
const server = new DocsMintMcpServer({ name: "docsmint", version: "2.
|
|
236466
|
+
const server = new DocsMintMcpServer({ name: "docsmint", version: "2.2.2" });
|
|
236071
236467
|
const client = options.docsClient ? createMcpDocsClient(options.docsClient, options.requestContext) : options.client ?? createMcpDocsClient(createDefaultDocsClient(), options.requestContext);
|
|
236072
236468
|
registerDocsmintMcpCapabilities(server, client, options.workspaceRouting, options.decorateResult);
|
|
236073
236469
|
return server;
|
|
@@ -242661,7 +243057,7 @@ var swaggerConfig = {
|
|
|
242661
243057
|
},
|
|
242662
243058
|
info: {
|
|
242663
243059
|
title: "DocsMint API",
|
|
242664
|
-
version: "2.
|
|
243060
|
+
version: "2.2.2",
|
|
242665
243061
|
description: "Self-hosted AI-native knowledge workspace and installable PWA with hybrid search, GraphRAG, REST, SDK, CLI, and MCP access for people and AI agents.",
|
|
242666
243062
|
contact: { name: "HiAi-gg", url: "https://github.com/HiAi-gg/docsmint" },
|
|
242667
243063
|
license: {
|