@hiai-gg/docsmint 2.1.5 → 2.2.1
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 +6 -4
- package/dist/backend/index.js +659 -71
- package/dist/backend-account-runtime-cleanup.js +29 -0
- package/dist/backend-api-key-facade.js +29 -0
- package/dist/backend-pipeline-cancellation.js +29 -0
- package/dist/client.d.ts +6 -1
- package/dist/client.js +20 -1
- package/dist/lifecycle-runtime.js +40 -2
- package/dist/mcp-cli.js +169 -4
- package/dist/mcp-server.js +173 -4
- package/dist/types.d.ts +17 -2
- package/package.json +3 -2
- package/packages/cli/src/index.ts +1 -1
- package/packages/db/src/schema.ts +54 -0
- package/server.json +3 -3
- package/skills/docsmint-document-manager/SKILL.md +7 -0
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,
|
|
@@ -44105,6 +44106,7 @@ __export(exports_schema, {
|
|
|
44105
44106
|
documentVisibilityEnum: () => documentVisibilityEnum,
|
|
44106
44107
|
documents: () => documents,
|
|
44107
44108
|
embeddingStatusEnum: () => embeddingStatusEnum,
|
|
44109
|
+
folderCreateOperations: () => folderCreateOperations,
|
|
44108
44110
|
folderRelations: () => folderRelations,
|
|
44109
44111
|
folders: () => folders,
|
|
44110
44112
|
guestAccess: () => guestAccess,
|
|
@@ -44130,7 +44132,7 @@ __export(exports_schema, {
|
|
|
44130
44132
|
versionRelations: () => versionRelations,
|
|
44131
44133
|
versions: () => versions
|
|
44132
44134
|
});
|
|
44133
|
-
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, 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;
|
|
44134
44136
|
var init_schema2 = __esm(() => {
|
|
44135
44137
|
init_pg_core();
|
|
44136
44138
|
init_drizzle_orm();
|
|
@@ -44583,6 +44585,21 @@ var init_schema2 = __esm(() => {
|
|
|
44583
44585
|
index("pending_attachment_uploads_cleanup_lease_idx").on(table.expiresAt, table.leaseExpiresAt, table.id),
|
|
44584
44586
|
check2("pending_attachment_uploads_quota_state_check", sql`${table.quotaState} IN ('not_required', 'reserve_pending', 'reserved', 'finalize_pending', 'committed')`)
|
|
44585
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
|
+
]);
|
|
44586
44603
|
attachmentStorageCleanupOutbox = pgTable("attachment_storage_cleanup_outbox", {
|
|
44587
44604
|
id: uuid("id").primaryKey().defaultRandom(),
|
|
44588
44605
|
sourceKind: text("source_kind").notNull(),
|
|
@@ -44755,6 +44772,18 @@ var init_schema2 = __esm(() => {
|
|
|
44755
44772
|
uniqueIndex("document_create_operations_workspace_actor_key_idx").on(table.workspaceId, table.actorUserId, table.idempotencyKey),
|
|
44756
44773
|
uniqueIndex("document_create_operations_document_idx").on(table.documentId)
|
|
44757
44774
|
]);
|
|
44775
|
+
folderCreateOperations = pgTable("folder_create_operations", {
|
|
44776
|
+
id: uuid("id").primaryKey().defaultRandom(),
|
|
44777
|
+
workspaceId: text("workspace_id").notNull(),
|
|
44778
|
+
actorUserId: uuid("actor_user_id").notNull().references(() => users.id, { onDelete: "cascade" }),
|
|
44779
|
+
idempotencyKey: text("idempotency_key").notNull(),
|
|
44780
|
+
folderId: uuid("folder_id").notNull(),
|
|
44781
|
+
requestFingerprint: text("request_fingerprint").notNull(),
|
|
44782
|
+
createdAt: timestamp("created_at").defaultNow().notNull()
|
|
44783
|
+
}, (table) => [
|
|
44784
|
+
uniqueIndex("folder_create_operations_workspace_actor_key_unique").on(table.workspaceId, table.actorUserId, table.idempotencyKey),
|
|
44785
|
+
uniqueIndex("folder_create_operations_folder_idx").on(table.folderId)
|
|
44786
|
+
]);
|
|
44758
44787
|
versionRelations = relations(versions, ({ one }) => ({
|
|
44759
44788
|
document: one(documents, {
|
|
44760
44789
|
fields: [versions.documentId],
|
|
@@ -50475,6 +50504,9 @@ function ipv42(params) {
|
|
|
50475
50504
|
function ipv62(params) {
|
|
50476
50505
|
return _ipv6(ZodIPv6, params);
|
|
50477
50506
|
}
|
|
50507
|
+
function base642(params) {
|
|
50508
|
+
return _base64(ZodBase64, params);
|
|
50509
|
+
}
|
|
50478
50510
|
function number2(params) {
|
|
50479
50511
|
return _number(ZodNumber, params);
|
|
50480
50512
|
}
|
|
@@ -52839,10 +52871,10 @@ function base64Decode(data, alphabet) {
|
|
|
52839
52871
|
}
|
|
52840
52872
|
return Uint8Array.from(result);
|
|
52841
52873
|
}
|
|
52842
|
-
var
|
|
52874
|
+
var base643, base64Url;
|
|
52843
52875
|
var init_base64 = __esm(() => {
|
|
52844
52876
|
init_bytes();
|
|
52845
|
-
|
|
52877
|
+
base643 = {
|
|
52846
52878
|
encode(data, options = {}) {
|
|
52847
52879
|
const alphabet = getAlphabet(false);
|
|
52848
52880
|
return base64Encode(toUint8Array3(data), alphabet, options.padding ?? true);
|
|
@@ -69568,6 +69600,7 @@ var init_config_schema = __esm(() => {
|
|
|
69568
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"),
|
|
69569
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"),
|
|
69570
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"),
|
|
69571
69604
|
DOCSMINT_WORKSPACE_ENABLED: string2().optional().default("false").transform((value) => value === "true"),
|
|
69572
69605
|
DOCSMINT_WORKSPACE_ISSUER: string2().trim().optional(),
|
|
69573
69606
|
DOCSMINT_WORKSPACE_SECRET: string2().optional(),
|
|
@@ -165937,7 +165970,7 @@ var createHMAC = (algorithm = "SHA-256", encoding = "none") => {
|
|
|
165937
165970
|
if (encoding === "hex")
|
|
165938
165971
|
return hex.encode(signature);
|
|
165939
165972
|
if (encoding === "base64")
|
|
165940
|
-
return
|
|
165973
|
+
return base643.encode(signature);
|
|
165941
165974
|
if (encoding === "base64url" || encoding === "base64urlnopad")
|
|
165942
165975
|
return base64Url.encode(signature, { padding: encoding !== "base64urlnopad" });
|
|
165943
165976
|
return signature;
|
|
@@ -165948,7 +165981,7 @@ var createHMAC = (algorithm = "SHA-256", encoding = "none") => {
|
|
|
165948
165981
|
if (encoding === "hex")
|
|
165949
165982
|
signature = typeof signature === "string" ? hex.toBytes(signature) : signature;
|
|
165950
165983
|
if (encoding === "base64" || encoding === "base64url" || encoding === "base64urlnopad")
|
|
165951
|
-
signature = await
|
|
165984
|
+
signature = await base643.decode(signature);
|
|
165952
165985
|
return getWebcryptoSubtle().verify("HMAC", hmacKey, toBufferSource(signature), toBufferSource(data));
|
|
165953
165986
|
}
|
|
165954
165987
|
};
|
|
@@ -166674,7 +166707,7 @@ function createHash4(algorithm, encoding) {
|
|
|
166674
166707
|
if (encoding === "base64" || encoding === "base64url" || encoding === "base64urlnopad") {
|
|
166675
166708
|
if (encoding.includes("url"))
|
|
166676
166709
|
return base64Url.encode(hashBuffer, { padding: encoding !== "base64urlnopad" });
|
|
166677
|
-
return
|
|
166710
|
+
return base643.encode(hashBuffer);
|
|
166678
166711
|
}
|
|
166679
166712
|
return hashBuffer;
|
|
166680
166713
|
} };
|
|
@@ -169865,7 +169898,7 @@ function formUrlEncode(value) {
|
|
|
169865
169898
|
}
|
|
169866
169899
|
function encodeBasicCredentials(clientId, clientSecret) {
|
|
169867
169900
|
const payload = `${formUrlEncode(clientId)}:${formUrlEncode(clientSecret)}`;
|
|
169868
|
-
return `Basic ${
|
|
169901
|
+
return `Basic ${base643.encode(payload)}`;
|
|
169869
169902
|
}
|
|
169870
169903
|
|
|
169871
169904
|
// ../../node_modules/.bun/@better-auth+core@1.7.15+1bcdd7fa41f3b4db/node_modules/@better-auth/core/dist/oauth2/client-assertion.mjs
|
|
@@ -173048,7 +173081,7 @@ var microsoft = (options) => {
|
|
|
173048
173081
|
return;
|
|
173049
173082
|
try {
|
|
173050
173083
|
const pictureBuffer = await context.response.clone().arrayBuffer();
|
|
173051
|
-
const pictureBase64 =
|
|
173084
|
+
const pictureBase64 = base643.encode(pictureBuffer);
|
|
173052
173085
|
user.picture = `data:image/jpeg;base64, ${pictureBase64}`;
|
|
173053
173086
|
} catch (e) {
|
|
173054
173087
|
logger2.error(e && typeof e === "object" && "name" in e ? e.name : "", e);
|
|
@@ -178828,7 +178861,7 @@ function detectEnvironment() {
|
|
|
178828
178861
|
}
|
|
178829
178862
|
async function hashToBase64(data) {
|
|
178830
178863
|
const buffer = await createHash4("SHA-256").digest(data);
|
|
178831
|
-
return
|
|
178864
|
+
return base643.encode(buffer);
|
|
178832
178865
|
}
|
|
178833
178866
|
var generateId2 = (size) => {
|
|
178834
178867
|
return createRandomStringGenerator("a-z", "A-Z", "0-9")(size || 32);
|
|
@@ -183332,6 +183365,17 @@ var nanoid2 = customAlphabet(urlAlphabet);
|
|
|
183332
183365
|
init_dist_es11();
|
|
183333
183366
|
init_schema2();
|
|
183334
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
|
|
183335
183379
|
init_logger3();
|
|
183336
183380
|
|
|
183337
183381
|
// ../../backend/src/lib/runtime-options.ts
|
|
@@ -183523,7 +183567,9 @@ async function claimCleanupPage(leaseOwner, now, pageSize, quotaReleaseAvailable
|
|
|
183523
183567
|
AND NOT EXISTS (
|
|
183524
183568
|
SELECT 1
|
|
183525
183569
|
FROM public.pending_attachment_uploads AS pending
|
|
183526
|
-
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))
|
|
183527
183573
|
AND pending.lease_owner LIKE 'confirm:%'
|
|
183528
183574
|
AND pending.lease_expires_at IS NOT NULL
|
|
183529
183575
|
AND pending.lease_expires_at > ${nowTimestamp}
|
|
@@ -183565,7 +183611,7 @@ function quotaContext(row, signal) {
|
|
|
183565
183611
|
workspaceId: row.workspace_id,
|
|
183566
183612
|
actorUserId: row.actor_user_id,
|
|
183567
183613
|
documentId: row.document_id,
|
|
183568
|
-
storageKey: row.storage_key,
|
|
183614
|
+
storageKey: committedAttachmentKey(row.storage_key),
|
|
183569
183615
|
proposedSize: row.size,
|
|
183570
183616
|
requestId: row.id,
|
|
183571
183617
|
idempotencyKey: row.quota_operation_key,
|
|
@@ -184034,7 +184080,7 @@ function validClaims(value) {
|
|
|
184034
184080
|
if (typeof value !== "object" || value === null)
|
|
184035
184081
|
return false;
|
|
184036
184082
|
const claims = value;
|
|
184037
|
-
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);
|
|
184038
184084
|
}
|
|
184039
184085
|
function attachmentUploadTokenHash(token) {
|
|
184040
184086
|
return new Bun.CryptoHasher("sha256").update(token).digest("hex");
|
|
@@ -184061,8 +184107,134 @@ async function verifyAttachmentUploadToken(token) {
|
|
|
184061
184107
|
}
|
|
184062
184108
|
}
|
|
184063
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
|
+
|
|
184064
184222
|
// ../../backend/src/api/routes/attachments.ts
|
|
184065
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
|
|
184066
184238
|
init_logger3();
|
|
184067
184239
|
|
|
184068
184240
|
// ../../backend/src/lib/remote-image.ts
|
|
@@ -184425,7 +184597,7 @@ function attachmentQuotaContext(ctx, actorUserId, documentId, storageKey, propos
|
|
|
184425
184597
|
workspaceId: ctx.workspaceId,
|
|
184426
184598
|
actorUserId,
|
|
184427
184599
|
documentId,
|
|
184428
|
-
storageKey,
|
|
184600
|
+
storageKey: committedAttachmentKey(storageKey),
|
|
184429
184601
|
proposedSize,
|
|
184430
184602
|
requestId,
|
|
184431
184603
|
idempotencyKey
|
|
@@ -184579,6 +184751,17 @@ var attachmentRoutes = new Elysia({ prefix: "/api" }).post("/documents/:id/attac
|
|
|
184579
184751
|
const filename = typeof payload?.filename === "string" ? payload.filename : "";
|
|
184580
184752
|
const contentType = typeof payload?.contentType === "string" ? payload.contentType : "";
|
|
184581
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
|
+
}
|
|
184582
184765
|
if (!filename || filename.length > 255) {
|
|
184583
184766
|
set.status = 400;
|
|
184584
184767
|
return { error: "filename must be a non-empty string \u2264 255 chars" };
|
|
@@ -184597,22 +184780,30 @@ var attachmentRoutes = new Elysia({ prefix: "/api" }).post("/documents/:id/attac
|
|
|
184597
184780
|
error: `File too large. Maximum size: ${ATTACHMENT_MAX_SIZE_BYTES / 1024 / 1024}MB`
|
|
184598
184781
|
};
|
|
184599
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");
|
|
184600
184789
|
const ext = filename.split(".").pop() ?? "bin";
|
|
184601
|
-
const
|
|
184602
|
-
|
|
184603
|
-
|
|
184604
|
-
|
|
184605
|
-
|
|
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()}`;
|
|
184606
184796
|
const presignLeaseExpiresAt = new Date(Date.now() + 60000);
|
|
184607
|
-
|
|
184797
|
+
let uploadToken = await signAttachmentUploadToken({
|
|
184608
184798
|
id: admissionId,
|
|
184609
184799
|
documentId,
|
|
184610
184800
|
actorUserId: userId,
|
|
184611
184801
|
workspaceId: ctx.workspaceId ?? null,
|
|
184612
184802
|
storageKey: key,
|
|
184613
|
-
expiresAt: expiresAt.getTime()
|
|
184803
|
+
expiresAt: expiresAt.getTime(),
|
|
184804
|
+
...typeof sourceSha256 === "string" ? { sourceSha256 } : {}
|
|
184614
184805
|
});
|
|
184615
|
-
|
|
184806
|
+
let quotaContext = attachmentQuotaContext(ctx, userId, documentId, key, size, admissionId, quotaOperationKey);
|
|
184616
184807
|
const admission = attachmentQuotaAdmission(set);
|
|
184617
184808
|
if (admission === undefined) {
|
|
184618
184809
|
return { error: "Attachment storage quota admission is unavailable" };
|
|
@@ -184625,7 +184816,40 @@ var attachmentRoutes = new Elysia({ prefix: "/api" }).post("/documents/:id/attac
|
|
|
184625
184816
|
}
|
|
184626
184817
|
let reservationId;
|
|
184627
184818
|
try {
|
|
184628
|
-
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
|
+
}
|
|
184629
184853
|
await tx.insert(pendingAttachmentUploads).values({
|
|
184630
184854
|
id: admissionId,
|
|
184631
184855
|
documentId,
|
|
@@ -184642,8 +184866,43 @@ var attachmentRoutes = new Elysia({ prefix: "/api" }).post("/documents/:id/attac
|
|
|
184642
184866
|
leaseExpiresAt: presignLeaseExpiresAt,
|
|
184643
184867
|
expiresAt
|
|
184644
184868
|
});
|
|
184869
|
+
return null;
|
|
184645
184870
|
});
|
|
184646
|
-
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) {
|
|
184647
184906
|
try {
|
|
184648
184907
|
reservationId = (await admission.reserve(quotaContext)).id;
|
|
184649
184908
|
} catch (error) {
|
|
@@ -184653,7 +184912,7 @@ var attachmentRoutes = new Elysia({ prefix: "/api" }).post("/documents/:id/attac
|
|
|
184653
184912
|
leaseExpiresAt: new Date,
|
|
184654
184913
|
lastError: retryable ? "quota_reserve_retryable" : "quota_reserve_terminal",
|
|
184655
184914
|
quotaState: retryable ? "reserve_pending" : "not_required"
|
|
184656
|
-
}).where(eq(pendingAttachmentUploads.id, admissionId))).catch(() => {
|
|
184915
|
+
}).where(and(eq(pendingAttachmentUploads.id, admissionId), eq(pendingAttachmentUploads.leaseOwner, presignLeaseOwner)))).catch(() => {
|
|
184657
184916
|
return;
|
|
184658
184917
|
});
|
|
184659
184918
|
logger3.warn({ err: error, documentId, retryable }, "Attachment storage quota reservation rejected");
|
|
@@ -184669,7 +184928,9 @@ var attachmentRoutes = new Elysia({ prefix: "/api" }).post("/documents/:id/attac
|
|
|
184669
184928
|
if (reservedRows.length !== 1)
|
|
184670
184929
|
throw new Error("attachment_admission_lease_lost");
|
|
184671
184930
|
}
|
|
184672
|
-
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
|
+
});
|
|
184673
184934
|
const issuedRows = await withTenant(ctx, (tx) => tx.update(pendingAttachmentUploads).set({
|
|
184674
184935
|
urlIssuedAt: new Date,
|
|
184675
184936
|
leaseOwner: null,
|
|
@@ -184683,10 +184944,10 @@ var attachmentRoutes = new Elysia({ prefix: "/api" }).post("/documents/:id/attac
|
|
|
184683
184944
|
uploadToken,
|
|
184684
184945
|
...reservationId ? { quotaReservationId: reservationId } : {},
|
|
184685
184946
|
maxSize: ATTACHMENT_MAX_SIZE_BYTES,
|
|
184686
|
-
expiresIn:
|
|
184947
|
+
expiresIn: Math.max(0, Math.ceil((expiresAt.getTime() - Date.now()) / 1000))
|
|
184687
184948
|
};
|
|
184688
184949
|
} catch (err) {
|
|
184689
|
-
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(() => {
|
|
184690
184951
|
return;
|
|
184691
184952
|
});
|
|
184692
184953
|
if (isAccountPurgeFencedError(err)) {
|
|
@@ -184744,7 +185005,7 @@ var attachmentRoutes = new Elysia({ prefix: "/api" }).post("/documents/:id/attac
|
|
|
184744
185005
|
return accountPurgeFencedResponse();
|
|
184745
185006
|
}
|
|
184746
185007
|
if (!claimed) {
|
|
184747
|
-
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));
|
|
184748
185009
|
if (existing && authorization.authorized) {
|
|
184749
185010
|
set.status = 201;
|
|
184750
185011
|
return {
|
|
@@ -184818,7 +185079,7 @@ var attachmentRoutes = new Elysia({ prefix: "/api" }).post("/documents/:id/attac
|
|
|
184818
185079
|
set.status = 409;
|
|
184819
185080
|
return { error: "Upload not found in storage \u2014 please retry upload" };
|
|
184820
185081
|
}
|
|
184821
|
-
|
|
185082
|
+
let storedSize = headOutput.ContentLength;
|
|
184822
185083
|
if (typeof storedSize !== "number" || !Number.isFinite(storedSize) || storedSize <= 0) {
|
|
184823
185084
|
set.status = 409;
|
|
184824
185085
|
return { error: "Upload size could not be verified" };
|
|
@@ -184829,6 +185090,66 @@ var attachmentRoutes = new Elysia({ prefix: "/api" }).post("/documents/:id/attac
|
|
|
184829
185090
|
error: `Uploaded file exceeds the ${config3.ATTACHMENT_MAX_SIZE_MB}MB limit`
|
|
184830
185091
|
};
|
|
184831
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
|
+
}
|
|
184832
185153
|
if (admission && quotaContext && claimed.quotaReservationId) {
|
|
184833
185154
|
try {
|
|
184834
185155
|
const finalizeRows = await withTenant(claimCtx, (tx) => tx.update(pendingAttachmentUploads).set({
|
|
@@ -184870,24 +185191,41 @@ var attachmentRoutes = new Elysia({ prefix: "/api" }).post("/documents/:id/attac
|
|
|
184870
185191
|
});
|
|
184871
185192
|
if (!activeClaim)
|
|
184872
185193
|
return null;
|
|
184873
|
-
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);
|
|
184874
185195
|
let result = raced;
|
|
184875
185196
|
if (!result) {
|
|
184876
185197
|
[result] = await tx.insert(attachments).values({
|
|
184877
185198
|
documentId,
|
|
184878
185199
|
workspaceId: claims.workspaceId,
|
|
184879
185200
|
uploadedBy: claims.actorUserId,
|
|
184880
|
-
filename:
|
|
184881
|
-
mimeType:
|
|
185201
|
+
filename: prepared.filename,
|
|
185202
|
+
mimeType: prepared.mimeType,
|
|
184882
185203
|
size: storedSize,
|
|
184883
|
-
storageKey:
|
|
185204
|
+
storageKey: prepared.storageKey
|
|
184884
185205
|
}).onConflictDoNothing({ target: attachments.storageKey }).returning();
|
|
184885
185206
|
}
|
|
184886
185207
|
if (!result) {
|
|
184887
|
-
[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);
|
|
184888
185209
|
}
|
|
184889
185210
|
if (!result)
|
|
184890
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
|
+
}
|
|
184891
185229
|
await tx.delete(pendingAttachmentUploads).where(and(eq(pendingAttachmentUploads.id, claims.id), eq(pendingAttachmentUploads.tokenHash, tokenHash), eq(pendingAttachmentUploads.leaseOwner, claimed.leaseOwner)));
|
|
184892
185230
|
return result;
|
|
184893
185231
|
});
|
|
@@ -184975,7 +185313,28 @@ var attachmentRoutes = new Elysia({ prefix: "/api" }).post("/documents/:id/attac
|
|
|
184975
185313
|
error: `File too large. Maximum size: ${LEGACY_MAX_FILE_SIZE / 1024 / 1024}MB. New uploads should use the presigned URL flow.`
|
|
184976
185314
|
};
|
|
184977
185315
|
}
|
|
184978
|
-
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";
|
|
184979
185338
|
const key = `${attachmentKeyPrefix(ctx, userId, documentId)}/${nanoid2()}.${ext}`;
|
|
184980
185339
|
const cleanupSourceId = crypto.randomUUID();
|
|
184981
185340
|
try {
|
|
@@ -184988,19 +185347,18 @@ var attachmentRoutes = new Elysia({ prefix: "/api" }).post("/documents/:id/attac
|
|
|
184988
185347
|
ownerUserId: userId,
|
|
184989
185348
|
requestedByUserId: userId,
|
|
184990
185349
|
workspaceId: null,
|
|
184991
|
-
size:
|
|
185350
|
+
size: image.bytes.length,
|
|
184992
185351
|
quotaOperationKey: `attachment:${documentId}:${key}`,
|
|
184993
185352
|
quotaReleaseKind: "none",
|
|
184994
185353
|
notBefore: storageWriteHoldNotBefore()
|
|
184995
185354
|
}));
|
|
184996
|
-
const
|
|
184997
|
-
const buffer = Buffer.from(arrayBuffer);
|
|
185355
|
+
const buffer = image.bytes;
|
|
184998
185356
|
await storage.send(new PutObjectCommand({
|
|
184999
185357
|
Bucket: BUCKET,
|
|
185000
185358
|
Key: key,
|
|
185001
185359
|
Body: buffer,
|
|
185002
|
-
ContentType:
|
|
185003
|
-
ContentLength:
|
|
185360
|
+
ContentType: image.mimeType,
|
|
185361
|
+
ContentLength: image.bytes.length
|
|
185004
185362
|
}));
|
|
185005
185363
|
const integrityOk = await verifyUploadIntegrity(buffer, key);
|
|
185006
185364
|
if (!integrityOk) {
|
|
@@ -185014,9 +185372,9 @@ var attachmentRoutes = new Elysia({ prefix: "/api" }).post("/documents/:id/attac
|
|
|
185014
185372
|
documentId,
|
|
185015
185373
|
workspaceId: ctx.workspaceId ?? null,
|
|
185016
185374
|
uploadedBy: userId,
|
|
185017
|
-
filename:
|
|
185018
|
-
mimeType:
|
|
185019
|
-
size:
|
|
185375
|
+
filename: image.filename,
|
|
185376
|
+
mimeType: image.mimeType,
|
|
185377
|
+
size: image.bytes.length,
|
|
185020
185378
|
storageKey: key
|
|
185021
185379
|
}).returning();
|
|
185022
185380
|
await tx.delete(attachmentStorageCleanupOutbox).where(and(eq(attachmentStorageCleanupOutbox.sourceKind, "uncommitted_upload"), eq(attachmentStorageCleanupOutbox.sourceId, cleanupSourceId)));
|
|
@@ -213526,18 +213884,6 @@ var recordAuditEvent = createAuditRecorder({
|
|
|
213526
213884
|
// ../../backend/src/api/routes/documents.ts
|
|
213527
213885
|
init_config();
|
|
213528
213886
|
|
|
213529
|
-
// ../../backend/src/lib/document-create-idempotency.ts
|
|
213530
|
-
var IDEMPOTENCY_KEY_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/;
|
|
213531
|
-
function documentCreateIdempotencyKey(request) {
|
|
213532
|
-
const value = request.headers.get("idempotency-key");
|
|
213533
|
-
if (value === null)
|
|
213534
|
-
return null;
|
|
213535
|
-
return IDEMPOTENCY_KEY_PATTERN.test(value) ? value : "invalid";
|
|
213536
|
-
}
|
|
213537
|
-
function documentCreateWorkspaceIdentity(userId, workspaceId) {
|
|
213538
|
-
return workspaceId ?? `personal:${userId}`;
|
|
213539
|
-
}
|
|
213540
|
-
|
|
213541
213887
|
// ../../backend/src/lib/document-list-query.ts
|
|
213542
213888
|
init_schema2();
|
|
213543
213889
|
init_drizzle_orm();
|
|
@@ -213830,6 +214176,8 @@ var listQuerySchema2 = documentListQuerySchema;
|
|
|
213830
214176
|
var cursorListQuerySchema = object({
|
|
213831
214177
|
...documentListQueryFields,
|
|
213832
214178
|
cursor: string2().min(1).optional(),
|
|
214179
|
+
view: _enum(["catalog"]).optional(),
|
|
214180
|
+
includeTotal: _enum(["true", "false"]).optional(),
|
|
213833
214181
|
limit: exports_coerce.number().int().min(1).max(100).default(50),
|
|
213834
214182
|
sortBy: _enum([
|
|
213835
214183
|
"title",
|
|
@@ -214160,28 +214508,49 @@ var documentRoutes = new Elysia({ prefix: "/api" }).get("/documents", async ({ q
|
|
|
214160
214508
|
}
|
|
214161
214509
|
}
|
|
214162
214510
|
try {
|
|
214163
|
-
const
|
|
214164
|
-
|
|
214165
|
-
|
|
214511
|
+
const includeTotal = parsed.data.includeTotal !== "false";
|
|
214512
|
+
const joinedSort = sortBy === "category" || sortBy === "folder";
|
|
214513
|
+
const [countResult, rows] = await withTenant(ctx, (tx) => {
|
|
214514
|
+
const projection = {
|
|
214166
214515
|
id: documents.id,
|
|
214167
214516
|
title: documents.title,
|
|
214168
214517
|
content: sql`LEFT(${documents.content}, 200)`.as("content"),
|
|
214169
214518
|
folderId: documents.folderId,
|
|
214170
|
-
folderName: folders.name,
|
|
214171
214519
|
categoryId: documents.categoryId,
|
|
214172
|
-
effectiveCategoryId: effectiveDocumentCategoryValue(documents.categoryId, documents.folderId, ctx).as("effective_category_id"),
|
|
214173
|
-
categoryName: categories.name,
|
|
214520
|
+
effectiveCategoryId: (effectiveCategoryId ? sql`${effectiveCategoryId}::uuid` : effectiveDocumentCategoryValue(documents.categoryId, documents.folderId, ctx)).as("effective_category_id"),
|
|
214174
214521
|
createdAt: documents.createdAt,
|
|
214175
214522
|
updatedAt: documents.updatedAt
|
|
214176
|
-
}
|
|
214177
|
-
|
|
214523
|
+
};
|
|
214524
|
+
const order = [
|
|
214525
|
+
sortOrder === "asc" ? sql`${sortValue} asc nulls last` : sql`${sortValue} desc nulls last`,
|
|
214526
|
+
sortOrder === "asc" ? asc(documents.id) : desc(documents.id)
|
|
214527
|
+
];
|
|
214528
|
+
const selected = tx.select(projection).from(documents).where(and(...conditions)).orderBy(...order).limit(limit + 1);
|
|
214529
|
+
const pageQuery = joinedSort ? tx.select({
|
|
214530
|
+
...projection,
|
|
214531
|
+
folderName: folders.name,
|
|
214532
|
+
categoryName: categories.name
|
|
214533
|
+
}).from(documents).leftJoin(folders, eq(folders.id, documents.folderId)).leftJoin(categories, eq(categories.id, documents.categoryId)).where(and(...conditions)).orderBy(...order).limit(limit + 1) : selected;
|
|
214534
|
+
return Promise.all([
|
|
214535
|
+
includeTotal ? tx.select({ total: count() }).from(documents).where(and(...filteredConditions)) : Promise.resolve([]),
|
|
214536
|
+
pageQuery
|
|
214537
|
+
]);
|
|
214538
|
+
});
|
|
214178
214539
|
const hasMore = rows.length > limit;
|
|
214179
214540
|
const page = rows.slice(0, limit);
|
|
214180
214541
|
const last = page.at(-1);
|
|
214181
|
-
const lastValue = last ? sortBy === "title" ? last.title.toLocaleLowerCase() : sortBy === "category" ? last.categoryName?.toLocaleLowerCase() ?? null : sortBy === "folder" ? last.folderName?.toLocaleLowerCase() ?? null : new Date(sortBy === "createdAt" ? last.createdAt : last.updatedAt).toISOString() : null;
|
|
214542
|
+
const lastValue = last ? sortBy === "title" ? last.title.toLocaleLowerCase() : sortBy === "category" ? ("categoryName" in last ? last.categoryName : null)?.toLocaleLowerCase() ?? null : sortBy === "folder" ? ("folderName" in last ? last.folderName : null)?.toLocaleLowerCase() ?? null : new Date(sortBy === "createdAt" ? last.createdAt : last.updatedAt).toISOString() : null;
|
|
214543
|
+
const compact = parsed.data.view === "catalog";
|
|
214544
|
+
const items = (await withDocumentLocationNames(ctx, compact ? page : await withTags(ctx, page))).map((row) => withDocumentPreview(row, ctx.workspaceId, config3.PUBLIC_APP_URL));
|
|
214182
214545
|
return {
|
|
214183
|
-
total: countResult[0]?.total ?? 0,
|
|
214184
|
-
items:
|
|
214546
|
+
...includeTotal ? { total: countResult[0]?.total ?? 0 } : {},
|
|
214547
|
+
items: compact ? items.map(({ id, title, preview, folderId, folderName }) => ({
|
|
214548
|
+
id,
|
|
214549
|
+
title,
|
|
214550
|
+
preview,
|
|
214551
|
+
folderId,
|
|
214552
|
+
folderName
|
|
214553
|
+
})) : items,
|
|
214185
214554
|
nextCursor: hasMore && last ? encodeDocumentCursor({
|
|
214186
214555
|
v: 2,
|
|
214187
214556
|
sortBy,
|
|
@@ -216015,6 +216384,7 @@ var documentRoutes = new Elysia({ prefix: "/api" }).get("/documents", async ({ q
|
|
|
216015
216384
|
// ../../backend/src/api/routes/folders.ts
|
|
216016
216385
|
init_schema2();
|
|
216017
216386
|
init_drizzle_orm();
|
|
216387
|
+
import { createHash as createHash8 } from "crypto";
|
|
216018
216388
|
init_zod();
|
|
216019
216389
|
|
|
216020
216390
|
// ../../backend/src/lib/folder-name.ts
|
|
@@ -216280,6 +216650,12 @@ var folderRoutes = new Elysia({ prefix: "/api/folders" }).get("/:id", async ({ p
|
|
|
216280
216650
|
set.status = 400;
|
|
216281
216651
|
return { error: "Invalid input", details: parsed.error.flatten() };
|
|
216282
216652
|
}
|
|
216653
|
+
const idempotencyKey = documentCreateIdempotencyKey(request);
|
|
216654
|
+
if (idempotencyKey === "invalid") {
|
|
216655
|
+
set.status = 400;
|
|
216656
|
+
return { error: "Invalid Idempotency-Key" };
|
|
216657
|
+
}
|
|
216658
|
+
const workspaceIdentity = documentCreateWorkspaceIdentity(userId, ctx.workspaceId);
|
|
216283
216659
|
try {
|
|
216284
216660
|
const created = await withTenant(ctx, async (tx) => {
|
|
216285
216661
|
await acquireTenantTopologyLock(tx, ctx);
|
|
@@ -216301,6 +216677,23 @@ var folderRoutes = new Elysia({ prefix: "/api/folders" }).get("/:id", async ({ p
|
|
|
216301
216677
|
return { categoryNotFound: true };
|
|
216302
216678
|
}
|
|
216303
216679
|
}
|
|
216680
|
+
const requestFingerprint = createHash8("sha256").update(JSON.stringify([parsed.data.name, parentId, categoryId])).digest("hex");
|
|
216681
|
+
if (idempotencyKey) {
|
|
216682
|
+
const [operation] = await tx.select().from(folderCreateOperations).where(and(eq(folderCreateOperations.workspaceId, workspaceIdentity), eq(folderCreateOperations.actorUserId, userId), eq(folderCreateOperations.idempotencyKey, idempotencyKey))).limit(1);
|
|
216683
|
+
if (operation) {
|
|
216684
|
+
if (operation.requestFingerprint !== requestFingerprint) {
|
|
216685
|
+
return { idempotencyConflict: true };
|
|
216686
|
+
}
|
|
216687
|
+
const [row] = await tx.select().from(folders).where(and(eq(folders.id, operation.folderId), tenantOwnerCondition(folders.ownerId, folders.workspaceId, ctx))).limit(1);
|
|
216688
|
+
if (!row)
|
|
216689
|
+
return { idempotencyConflict: true };
|
|
216690
|
+
const currentCategory = await resolveFolderEffectiveCategory(tx, ctx, row.id);
|
|
216691
|
+
if (!isAuthorizedCategory(access, currentCategory ?? null)) {
|
|
216692
|
+
return { forbidden: true };
|
|
216693
|
+
}
|
|
216694
|
+
return { row, replay: true };
|
|
216695
|
+
}
|
|
216696
|
+
}
|
|
216304
216697
|
const scopeKey = parentId ? `${userId}:parent:${parentId}` : `${userId}:category:${categoryId ?? "none"}`;
|
|
216305
216698
|
await tx.execute(sql`SELECT pg_advisory_xact_lock(hashtextextended(${scopeKey}, 0))`);
|
|
216306
216699
|
const scopeConditions = [
|
|
@@ -216320,8 +216713,25 @@ var folderRoutes = new Elysia({ prefix: "/api/folders" }).get("/:id", async ({ p
|
|
|
216320
216713
|
parentId,
|
|
216321
216714
|
categoryId
|
|
216322
216715
|
}).returning();
|
|
216716
|
+
if (!row)
|
|
216717
|
+
throw new Error("Folder insert returned no row");
|
|
216718
|
+
if (idempotencyKey) {
|
|
216719
|
+
await tx.insert(folderCreateOperations).values({
|
|
216720
|
+
workspaceId: workspaceIdentity,
|
|
216721
|
+
actorUserId: userId,
|
|
216722
|
+
idempotencyKey,
|
|
216723
|
+
folderId: row.id,
|
|
216724
|
+
requestFingerprint
|
|
216725
|
+
});
|
|
216726
|
+
}
|
|
216323
216727
|
return { row };
|
|
216324
216728
|
});
|
|
216729
|
+
if ("idempotencyConflict" in created) {
|
|
216730
|
+
set.status = 409;
|
|
216731
|
+
return {
|
|
216732
|
+
error: "Folder creation request conflicts with a previous operation"
|
|
216733
|
+
};
|
|
216734
|
+
}
|
|
216325
216735
|
if ("notFound" in created) {
|
|
216326
216736
|
set.status = 404;
|
|
216327
216737
|
return { error: "Parent folder not found" };
|
|
@@ -216334,7 +216744,7 @@ var folderRoutes = new Elysia({ prefix: "/api/folders" }).get("/:id", async ({ p
|
|
|
216334
216744
|
set.status = 404;
|
|
216335
216745
|
return { error: "Category not found" };
|
|
216336
216746
|
}
|
|
216337
|
-
set.status = 201;
|
|
216747
|
+
set.status = "replay" in created ? 200 : 201;
|
|
216338
216748
|
return created.row;
|
|
216339
216749
|
} catch (err) {
|
|
216340
216750
|
const purgeFence = translateAccountPurgeFencedError(err, set);
|
|
@@ -217240,6 +217650,12 @@ class DocsClient {
|
|
|
217240
217650
|
}, context);
|
|
217241
217651
|
}
|
|
217242
217652
|
async listDocuments(options = {}, context) {
|
|
217653
|
+
return this.listDocumentCursor(options, context);
|
|
217654
|
+
}
|
|
217655
|
+
async listCatalogDocuments(options = {}, context) {
|
|
217656
|
+
return this.listDocumentCursor(options, context, "catalog");
|
|
217657
|
+
}
|
|
217658
|
+
async listDocumentCursor(options, context, view) {
|
|
217243
217659
|
return this.request("GET", "/api/documents/cursor", {
|
|
217244
217660
|
query: this.cleanQuery({
|
|
217245
217661
|
categoryId: options.categoryId,
|
|
@@ -217254,6 +217670,8 @@ class DocsClient {
|
|
|
217254
217670
|
updatedTo: options.updatedTo,
|
|
217255
217671
|
cursor: options.cursor,
|
|
217256
217672
|
limit: options.limit,
|
|
217673
|
+
view,
|
|
217674
|
+
includeTotal: options.includeTotal === undefined ? undefined : String(options.includeTotal),
|
|
217257
217675
|
sortBy: options.sortBy,
|
|
217258
217676
|
sortOrder: options.sortOrder
|
|
217259
217677
|
})
|
|
@@ -217464,6 +217882,12 @@ class DocsClient {
|
|
|
217464
217882
|
async listAttachments(documentId, context) {
|
|
217465
217883
|
return this.request("GET", `/api/documents/${encodeURIComponent(documentId)}/attachments`, undefined, context);
|
|
217466
217884
|
}
|
|
217885
|
+
async fetchAttachment(id, context) {
|
|
217886
|
+
const response = await this.fetchRaw("GET", `/api/attachments/${encodeURIComponent(id)}/raw`, {}, context);
|
|
217887
|
+
if (!response.ok)
|
|
217888
|
+
throw await this.toApiError(response);
|
|
217889
|
+
return response;
|
|
217890
|
+
}
|
|
217467
217891
|
async deleteAttachment(id, context) {
|
|
217468
217892
|
await this.request("DELETE", `/api/attachments/${encodeURIComponent(id)}`, undefined, context);
|
|
217469
217893
|
}
|
|
@@ -217525,8 +217949,11 @@ class DocsClient {
|
|
|
217525
217949
|
headers.set("Cookie", requestContext.cookie);
|
|
217526
217950
|
if (requestContext?.requestId)
|
|
217527
217951
|
headers.set("X-Request-Id", requestContext.requestId);
|
|
217528
|
-
if (requestContext?.idempotencyKey)
|
|
217952
|
+
if (requestContext?.idempotencyKey === null) {
|
|
217953
|
+
headers.delete("Idempotency-Key");
|
|
217954
|
+
} else if (requestContext?.idempotencyKey) {
|
|
217529
217955
|
headers.set("Idempotency-Key", requestContext.idempotencyKey);
|
|
217956
|
+
}
|
|
217530
217957
|
if (method === "POST" && path === "/api/documents" && !headers.has("Idempotency-Key")) {
|
|
217531
217958
|
headers.set("Idempotency-Key", crypto.randomUUID());
|
|
217532
217959
|
}
|
|
@@ -234166,6 +234593,8 @@ init_zod();
|
|
|
234166
234593
|
init_zod();
|
|
234167
234594
|
init_zod();
|
|
234168
234595
|
init_zod();
|
|
234596
|
+
import { createHash as createHash22 } from "crypto";
|
|
234597
|
+
import { createHash as createHash9 } from "crypto";
|
|
234169
234598
|
import { AsyncLocalStorage } from "async_hooks";
|
|
234170
234599
|
var contracts = new WeakMap;
|
|
234171
234600
|
function object2(value) {
|
|
@@ -234462,6 +234891,12 @@ class DocsClient2 {
|
|
|
234462
234891
|
}, context);
|
|
234463
234892
|
}
|
|
234464
234893
|
async listDocuments(options = {}, context) {
|
|
234894
|
+
return this.listDocumentCursor(options, context);
|
|
234895
|
+
}
|
|
234896
|
+
async listCatalogDocuments(options = {}, context) {
|
|
234897
|
+
return this.listDocumentCursor(options, context, "catalog");
|
|
234898
|
+
}
|
|
234899
|
+
async listDocumentCursor(options, context, view) {
|
|
234465
234900
|
return this.request("GET", "/api/documents/cursor", {
|
|
234466
234901
|
query: this.cleanQuery({
|
|
234467
234902
|
categoryId: options.categoryId,
|
|
@@ -234476,6 +234911,8 @@ class DocsClient2 {
|
|
|
234476
234911
|
updatedTo: options.updatedTo,
|
|
234477
234912
|
cursor: options.cursor,
|
|
234478
234913
|
limit: options.limit,
|
|
234914
|
+
view,
|
|
234915
|
+
includeTotal: options.includeTotal === undefined ? undefined : String(options.includeTotal),
|
|
234479
234916
|
sortBy: options.sortBy,
|
|
234480
234917
|
sortOrder: options.sortOrder
|
|
234481
234918
|
})
|
|
@@ -234686,6 +235123,12 @@ class DocsClient2 {
|
|
|
234686
235123
|
async listAttachments(documentId, context) {
|
|
234687
235124
|
return this.request("GET", `/api/documents/${encodeURIComponent(documentId)}/attachments`, undefined, context);
|
|
234688
235125
|
}
|
|
235126
|
+
async fetchAttachment(id, context) {
|
|
235127
|
+
const response = await this.fetchRaw("GET", `/api/attachments/${encodeURIComponent(id)}/raw`, {}, context);
|
|
235128
|
+
if (!response.ok)
|
|
235129
|
+
throw await this.toApiError(response);
|
|
235130
|
+
return response;
|
|
235131
|
+
}
|
|
234689
235132
|
async deleteAttachment(id, context) {
|
|
234690
235133
|
await this.request("DELETE", `/api/attachments/${encodeURIComponent(id)}`, undefined, context);
|
|
234691
235134
|
}
|
|
@@ -234747,8 +235190,11 @@ class DocsClient2 {
|
|
|
234747
235190
|
headers.set("Cookie", requestContext.cookie);
|
|
234748
235191
|
if (requestContext?.requestId)
|
|
234749
235192
|
headers.set("X-Request-Id", requestContext.requestId);
|
|
234750
|
-
if (requestContext?.idempotencyKey)
|
|
235193
|
+
if (requestContext?.idempotencyKey === null) {
|
|
235194
|
+
headers.delete("Idempotency-Key");
|
|
235195
|
+
} else if (requestContext?.idempotencyKey) {
|
|
234751
235196
|
headers.set("Idempotency-Key", requestContext.idempotencyKey);
|
|
235197
|
+
}
|
|
234752
235198
|
if (method === "POST" && path === "/api/documents" && !headers.has("Idempotency-Key")) {
|
|
234753
235199
|
headers.set("Idempotency-Key", crypto.randomUUID());
|
|
234754
235200
|
}
|
|
@@ -235184,6 +235630,14 @@ var operationOutputSchemas = {
|
|
|
235184
235630
|
permanently_delete_document: deleteAcknowledgmentSchema
|
|
235185
235631
|
};
|
|
235186
235632
|
var variant = (operation, result) => object({ operation: literal(operation), result });
|
|
235633
|
+
var attachment = object({
|
|
235634
|
+
id: string2().uuid(),
|
|
235635
|
+
documentId: string2().uuid().optional(),
|
|
235636
|
+
filename: string2(),
|
|
235637
|
+
mimeType: string2(),
|
|
235638
|
+
size: number2().int().nonnegative(),
|
|
235639
|
+
url: string2()
|
|
235640
|
+
});
|
|
235187
235641
|
var singleToolOutputSchemas = {
|
|
235188
235642
|
delete_document: operationOutputSchemas.delete_document,
|
|
235189
235643
|
delete_folder: operationOutputSchemas.delete_folder,
|
|
@@ -235205,6 +235659,16 @@ var singleToolOutputSchemas = {
|
|
|
235205
235659
|
variant("markdown", operationOutputSchemas.export_document),
|
|
235206
235660
|
variant("versions", operationOutputSchemas.get_version_history)
|
|
235207
235661
|
]),
|
|
235662
|
+
upload_document_image: attachment,
|
|
235663
|
+
check_document_attachments: strictObject({
|
|
235664
|
+
items: array2(attachment),
|
|
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()
|
|
235671
|
+
}),
|
|
235208
235672
|
save_document: union2([
|
|
235209
235673
|
variant("create", operationOutputSchemas.create_document),
|
|
235210
235674
|
variant("update", operationOutputSchemas.update_document)
|
|
@@ -235269,6 +235733,50 @@ var toolOutputSchemas = {
|
|
|
235269
235733
|
list_workspace_structure: union2([...singleToolOutputSchemas.list_workspace_structure.options, scopedSchemas.list_workspace_structure]),
|
|
235270
235734
|
list_trash: union2([singleToolOutputSchemas.list_trash, scopedSchemas.list_trash])
|
|
235271
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
|
+
}
|
|
235272
235780
|
var DEFAULT_BASE_URL = "http://localhost:50700";
|
|
235273
235781
|
function readConfig() {
|
|
235274
235782
|
const baseUrl = (process.env.HIAI_DOCS_URL ?? DEFAULT_BASE_URL).replace(/\/+$/, "");
|
|
@@ -235306,6 +235814,45 @@ function sanitizeMcpRequestContext(context) {
|
|
|
235306
235814
|
function createMcpDocsClient(docsClient, requestContext) {
|
|
235307
235815
|
const context = sanitizeMcpRequestContext(requestContext);
|
|
235308
235816
|
return {
|
|
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
|
+
}
|
|
235840
|
+
return docsClient.confirmAttachment(id, {
|
|
235841
|
+
...descriptor,
|
|
235842
|
+
key: upload.key,
|
|
235843
|
+
uploadToken: upload.uploadToken,
|
|
235844
|
+
quotaReservationId: upload.quotaReservationId
|
|
235845
|
+
}, uploadContext);
|
|
235846
|
+
},
|
|
235847
|
+
listAttachments: (id) => docsClient.listAttachments(id, context),
|
|
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);
|
|
235855
|
+
},
|
|
235309
235856
|
getFolder: (id) => docsClient.getFolder(id, context),
|
|
235310
235857
|
createTag: (input) => docsClient.createTag(input, context),
|
|
235311
235858
|
updateTag: (id, input) => docsClient.updateTag(id, input, context),
|
|
@@ -235564,6 +236111,18 @@ var content50 = string2().describe("Markdown document content; an empty string c
|
|
|
235564
236111
|
var read2 = { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false };
|
|
235565
236112
|
var write2 = { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false };
|
|
235566
236113
|
var destructive = { ...write2, destructiveHint: true };
|
|
236114
|
+
function matchesImageType(bytes, mimeType) {
|
|
236115
|
+
switch (mimeType) {
|
|
236116
|
+
case "image/png":
|
|
236117
|
+
return bytes.subarray(0, 8).equals(Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]));
|
|
236118
|
+
case "image/jpeg":
|
|
236119
|
+
return bytes[0] === 255 && bytes[1] === 216 && bytes[2] === 255;
|
|
236120
|
+
case "image/webp":
|
|
236121
|
+
return bytes.toString("ascii", 0, 4) === "RIFF" && bytes.toString("ascii", 8, 12) === "WEBP";
|
|
236122
|
+
default:
|
|
236123
|
+
return false;
|
|
236124
|
+
}
|
|
236125
|
+
}
|
|
235567
236126
|
function required22(value, name) {
|
|
235568
236127
|
if (!value)
|
|
235569
236128
|
throw new Error(`The injected legacy MCP client does not support ${name}; use a public DocsClient.`);
|
|
@@ -235599,6 +236158,35 @@ function registerCompactCapabilities(server, client, wrap) {
|
|
|
235599
236158
|
const { action: _action, id, ...data } = input;
|
|
235600
236159
|
return { operation: "update", result: await client.updateDocument(id, data) };
|
|
235601
236160
|
});
|
|
236161
|
+
const maxImageBytes = 2 * 1024 * 1024;
|
|
236162
|
+
register("upload_document_image", "Upload one PNG, JPEG or WebP image to an existing editable document. Send the file bytes as base64, up to 2 MiB before encoding. Insert the returned url as an image using save_document. If the result is lost, check attachments before uploading again.", strictObject({
|
|
236163
|
+
documentId: uuid22,
|
|
236164
|
+
filename: string2().min(1).max(255).regex(/^[^/\\\u0000-\u001f\u007f]+$/).describe("Image file name with extension and without path segments."),
|
|
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."),
|
|
236167
|
+
contentBase64: base642().min(4).max(Math.ceil(maxImageBytes / 3) * 4).describe("Base64 file bytes without a data: prefix.")
|
|
236168
|
+
}), write2, async ({ documentId, filename, mimeType, contentBase64, operationId }) => {
|
|
236169
|
+
const bytes = Buffer.from(contentBase64, "base64");
|
|
236170
|
+
if (!bytes.length || bytes.length > maxImageBytes)
|
|
236171
|
+
throw new HiaiDocsError("Image must be between 1 byte and 2 MiB.", 413, null, "IMAGE_TOO_LARGE");
|
|
236172
|
+
if (!matchesImageType(bytes, mimeType))
|
|
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 };
|
|
236175
|
+
});
|
|
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({
|
|
236177
|
+
documentId: uuid22,
|
|
236178
|
+
attachmentId: uuid22.optional()
|
|
236179
|
+
}), read2, async ({ documentId, attachmentId }) => {
|
|
236180
|
+
const response = await required22(client.listAttachments, "check_document_attachments")(documentId);
|
|
236181
|
+
const items = response.items.map((item) => ({ ...item, documentId }));
|
|
236182
|
+
if (!attachmentId)
|
|
236183
|
+
return { items };
|
|
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 };
|
|
236189
|
+
});
|
|
235602
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 }) => {
|
|
235603
236191
|
await required22(client.deleteDocument, "delete_document")(id);
|
|
235604
236192
|
return { id, deleted: true };
|
|
@@ -235875,7 +236463,7 @@ function registerDocsmintMcpCapabilities(server, client, workspaceRouting, decor
|
|
|
235875
236463
|
registerPromptsAndResources(server, client);
|
|
235876
236464
|
}
|
|
235877
236465
|
function createDocsmintMcpServer(options = {}) {
|
|
235878
|
-
const server = new DocsMintMcpServer({ name: "docsmint", version: "2.1
|
|
236466
|
+
const server = new DocsMintMcpServer({ name: "docsmint", version: "2.2.1" });
|
|
235879
236467
|
const client = options.docsClient ? createMcpDocsClient(options.docsClient, options.requestContext) : options.client ?? createMcpDocsClient(createDefaultDocsClient(), options.requestContext);
|
|
235880
236468
|
registerDocsmintMcpCapabilities(server, client, options.workspaceRouting, options.decorateResult);
|
|
235881
236469
|
return server;
|
|
@@ -242469,7 +243057,7 @@ var swaggerConfig = {
|
|
|
242469
243057
|
},
|
|
242470
243058
|
info: {
|
|
242471
243059
|
title: "DocsMint API",
|
|
242472
|
-
version: "2.1
|
|
243060
|
+
version: "2.2.1",
|
|
242473
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.",
|
|
242474
243062
|
contact: { name: "HiAi-gg", url: "https://github.com/HiAi-gg/docsmint" },
|
|
242475
243063
|
license: {
|