@sparkelf/dsh-knowledge-base 0.5.1 → 0.5.3

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/lib/index.js CHANGED
@@ -4462,9 +4462,9 @@ function assertIndexOutsideTrees(indexPath, trees) {
4462
4462
  /** Derive the scope columns from a view-relative path. */
4463
4463
  function scopeForPath(relPath) {
4464
4464
  const parts = relPath.split("/").filter((part) => part !== "");
4465
- if (parts[0] === "personal" && parts.length >= 3) return {
4465
+ if (parts[0] === "personal" && parts.length >= 2) return {
4466
4466
  scope: "personal",
4467
- ownerId: parts[1] ?? null,
4467
+ ownerId: parts.length >= 3 ? parts[1] ?? null : null,
4468
4468
  departmentCode: null
4469
4469
  };
4470
4470
  if (parts[0] === "department" && parts.length >= 3) return {
@@ -21387,6 +21387,32 @@ function personalPathRefusal(config, relPath) {
21387
21387
  return isTeamDeployment(config) ? void 0 : checkLocalPath(relPath);
21388
21388
  }
21389
21389
  /**
21390
+ * Normalize a PERSONAL write path to the caller's own subtree.
21391
+ *
21392
+ * The page's upload destination is the virtual bucket `personal`, so a file dropped
21393
+ * there arrives as `personal/<file>`. That spelling has no owner segment; writing it
21394
+ * literally would put the document beside the owners and force the permission layer
21395
+ * to grant the whole `personal` bucket, which resolves as shared across users.
21396
+ * Rewriting it to `personal/<callerId>/<file>` keeps the owner in the path, makes the
21397
+ * existing `personal/<userId>` grants sufficient, and keeps every user's personal
21398
+ * bucket disjoint. An explicit `personal/<uuid>/…` is left untouched so a cross-user
21399
+ * write still reaches the permission layer and is refused rather than silently
21400
+ * redirected.
21401
+ *
21402
+ * @param relPath - the path as the caller sent it.
21403
+ * @param callerId - the authenticated caller's user id.
21404
+ * @returns the caller-scoped personal path, or the input when it is not personal.
21405
+ */
21406
+ function normalizePersonalWritePath(relPath, callerId) {
21407
+ const normalized = resolveScopeAlias(relPath);
21408
+ if (!normalized.startsWith("personal/")) return normalized;
21409
+ if (normalized === `personal/${callerId}` || normalized.startsWith(`personal/${callerId}/`)) return normalized;
21410
+ const rest = normalized.slice(9);
21411
+ const head = rest.split("/")[0] ?? "";
21412
+ if (/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/iu.test(head)) return normalized;
21413
+ return `personal/${callerId}/${rest}`;
21414
+ }
21415
+ /**
21390
21416
  * The resolved layout, derived on the Host.
21391
21417
  *
21392
21418
  * There is no backend counterpart to ask: DataOps serves no knowledge config
@@ -22302,12 +22328,17 @@ async function canReadPath(ctx, config, relPath) {
22302
22328
  relPath = resolveScopeAlias(relPath);
22303
22329
  if (!isTeamDeployment(config)) return checkLocalPath(relPath) === void 0;
22304
22330
  try {
22331
+ let permissionPath = relPath;
22332
+ if (relPath.startsWith("personal/")) {
22333
+ const who = await fetchCaller(ctx, config).catch(() => void 0);
22334
+ if (who !== void 0 && isSafeUserId(who.userId)) permissionPath = normalizePersonalWritePath(relPath, who.userId);
22335
+ }
22305
22336
  return (await request(ctx, config, ENDPOINTS.resolve, {
22306
22337
  method: "POST",
22307
22338
  body: {
22308
22339
  resourceType: KB_RESOURCE_TYPE,
22309
- resourceId: relPath,
22310
- ancestors: knowledgeAncestorsFor(relPath)
22340
+ resourceId: permissionPath,
22341
+ ancestors: knowledgeAncestorsFor(permissionPath)
22311
22342
  }
22312
22343
  })).canRead === true;
22313
22344
  } catch {
@@ -22335,12 +22366,17 @@ async function canWritePath(ctx, config, relPath) {
22335
22366
  relPath = resolveScopeAlias(relPath);
22336
22367
  if (!isTeamDeployment(config)) return checkLocalPath(relPath) === void 0;
22337
22368
  try {
22369
+ let permissionPath = relPath;
22370
+ if (relPath.startsWith("personal/")) {
22371
+ const who = await fetchCaller(ctx, config).catch(() => void 0);
22372
+ if (who !== void 0 && isSafeUserId(who.userId)) permissionPath = normalizePersonalWritePath(relPath, who.userId);
22373
+ }
22338
22374
  return (await request(ctx, config, ENDPOINTS.resolve, {
22339
22375
  method: "POST",
22340
22376
  body: {
22341
22377
  resourceType: KB_RESOURCE_TYPE,
22342
- resourceId: relPath,
22343
- ancestors: knowledgeAncestorsFor(relPath)
22378
+ resourceId: permissionPath,
22379
+ ancestors: knowledgeAncestorsFor(permissionPath)
22344
22380
  }
22345
22381
  })).canWrite === true;
22346
22382
  } catch {
@@ -23847,17 +23883,30 @@ function apply(ctx, deploymentConfig) {
23847
23883
  try {
23848
23884
  const config = withStoredStorage(deploymentConfig, await readStorageSettings(deploymentConfig.mountPoint));
23849
23885
  const requiredPermission = permissionForKbRoute(method);
23850
- if (requiredPermission !== void 0 && isTeamDeployment(config)) try {
23851
- const permissionContext = await Promise.race([managementHost.context().catch(() => void 0), new Promise((resolve) => setTimeout(() => {
23852
- resolve(void 0);
23853
- }, 750))]);
23854
- if (permissionContext !== void 0) await toolDisclosure?.syncToolDisclosure(permissionContext);
23855
- if (permissionContext !== void 0 && permissionContext.permissions.length > 0 && !hasPermission(permissionContext, requiredPermission)) return writeJson(res, 403, {
23886
+ if (requiredPermission !== void 0 && isTeamDeployment(config)) {
23887
+ let permissionContext;
23888
+ try {
23889
+ permissionContext = await Promise.race([managementHost.context().catch(() => void 0), new Promise((resolve) => setTimeout(() => {
23890
+ resolve(void 0);
23891
+ }, 750))]);
23892
+ } catch {
23893
+ permissionContext = void 0;
23894
+ }
23895
+ if (permissionContext === void 0) return writeJson(res, 503, {
23896
+ error: "权限上下文暂时不可用,请稍后重试",
23897
+ code: "permission-context-unavailable",
23898
+ required: requiredPermission
23899
+ });
23900
+ try {
23901
+ await toolDisclosure?.syncToolDisclosure(permissionContext);
23902
+ } catch {}
23903
+ const permissionKeys = permissionContext.permissions;
23904
+ if (Array.isArray(permissionKeys) && !hasPermission(permissionContext, requiredPermission)) return writeJson(res, 403, {
23856
23905
  error: `缺少权限 ${requiredPermission}`,
23857
23906
  code: "forbidden",
23858
23907
  required: requiredPermission
23859
23908
  });
23860
- } catch {}
23909
+ }
23861
23910
  switch (method) {
23862
23911
  case "graph.canvas":
23863
23912
  res.writeHead(200, {
@@ -24404,7 +24453,7 @@ function apply(ctx, deploymentConfig) {
24404
24453
  }
24405
24454
  case "create": {
24406
24455
  const body = await readJsonBody(req);
24407
- const relPath = String(body.relPath ?? "");
24456
+ let relPath = String(body.relPath ?? "");
24408
24457
  const directory = body.kind === "directory";
24409
24458
  const refusal = personalPathRefusal(config, relPath);
24410
24459
  if (refusal !== void 0) return writeJson(res, 400, {
@@ -24419,6 +24468,11 @@ function apply(ctx, deploymentConfig) {
24419
24468
  });
24420
24469
  const caller = await fetchCaller(host, config).catch(() => void 0);
24421
24470
  if (caller === void 0 || !isSafeUserId(caller.userId)) return writeJson(res, 400, { error: "unsafe or unreadable caller id" });
24471
+ relPath = normalizePersonalWritePath(relPath, caller.userId);
24472
+ if (!isContainedRelPath(relPath)) return writeJson(res, 400, {
24473
+ error: "path escapes the knowledge root",
24474
+ refused: [relPath]
24475
+ });
24422
24476
  if (!await canWritePath(host, config, relPath)) return writeJson(res, 403, {
24423
24477
  error: "write access is required to create this path",
24424
24478
  refused: [relPath]
@@ -24587,7 +24641,7 @@ function apply(ctx, deploymentConfig) {
24587
24641
  }
24588
24642
  case "upload": {
24589
24643
  const body = await readJsonBody(req);
24590
- const relPath = String(body.relPath ?? "");
24644
+ let relPath = String(body.relPath ?? "");
24591
24645
  const encoding = body.encoding === "base64" ? "base64" : "utf8";
24592
24646
  const content = typeof body.content === "string" ? body.content : "";
24593
24647
  const refusal = personalPathRefusal(config, relPath);
@@ -24609,6 +24663,11 @@ function apply(ctx, deploymentConfig) {
24609
24663
  });
24610
24664
  const caller = await fetchCaller(host, config).catch(() => void 0);
24611
24665
  if (caller === void 0 || !isSafeUserId(caller.userId)) return writeJson(res, 400, { error: "unsafe or unreadable caller id" });
24666
+ relPath = normalizePersonalWritePath(relPath, caller.userId);
24667
+ if (!isContainedRelPath(relPath)) return writeJson(res, 400, {
24668
+ error: "path escapes the knowledge root",
24669
+ refused: [relPath]
24670
+ });
24612
24671
  if (!await canWritePath(host, config, relPath)) return writeJson(res, 403, {
24613
24672
  error: "write access is required to upload here",
24614
24673
  refused: [relPath]
@@ -25191,6 +25250,10 @@ function apply(ctx, deploymentConfig) {
25191
25250
  if (!await canManageGrants(host, config)) return writeJson(res, 403, { error: "approving requires grant-management access" });
25192
25251
  const submission = (await listPendingWrites(plan.actualRoot)).find((candidate) => candidate.name === body.name);
25193
25252
  if (submission === void 0) return writeJson(res, 404, { error: "no such pending submission" });
25253
+ if (submission.userId === caller.userId) return writeJson(res, 403, {
25254
+ error: "a submission cannot be approved by its submitter",
25255
+ code: "SELF_APPROVAL_FORBIDDEN"
25256
+ });
25194
25257
  const content = await readPendingContent(plan.actualRoot, body.name);
25195
25258
  if (content === null) return writeJson(res, 404, { error: "the pending content is gone" });
25196
25259
  const viewDir = viewPathFor({
@@ -27154,4 +27217,4 @@ async function executeStep(runner, step, hostId, record) {
27154
27217
  }
27155
27218
  }
27156
27219
  //#endregion
27157
- export { BindingStore, Config, FACT_KINDS, GUARDIAN_SESSION_TITLE, GUARDIAN_SKILL_NAME, GraphLoadError, GuardianSessionStore, IDLE_DEBOUNCE_MS, KB_ROOT_RESOURCE_ID, KB_SUMMARIZE_SKILL_DESCRIPTION, KB_SUMMARIZE_SKILL_NAME, KB_SUMMARIZE_SKILL_RANK, KB_VECTORIZE_SKILL_DESCRIPTION, KB_VECTORIZE_SKILL_NAME, KB_VECTORIZE_SKILL_RANK, KNOWLEDGE_GRAPH_SKILL_DESCRIPTION, KNOWLEDGE_GRAPH_SKILL_NAME, KNOWLEDGE_SKILL_DESCRIPTION, KNOWLEDGE_SKILL_INVOCATION, KNOWLEDGE_SKILL_NAME, KNOWLEDGE_SKILL_PROVIDER, KNOWLEDGE_SKILL_RANK, KnowledgeError, KnowledgeWriteError, LOCAL_USER_ID, MAX_KNOWLEDGE_WRITE_BYTES, MEMORY_ENTRY_MARKER, MEMORY_EXTRACT_SKILL_NAME, MEMORY_FACT_FILE, MEMORY_GUARDIAN_SKILL_NAME, MEMORY_LOG_DIR, MEMORY_PITFALL_FILE, MEMORY_PREFERENCE_FILE, MEMORY_SOP_DIR, MEMORY_SOP_EVALUATE_SKILL_NAME, MEMORY_TYPES, MemoryGraphWriter, MemoryGraphWriterError, MemoryStore, MemoryStoreError, PERSONAL_MEMORY_FOLDER, PERSONAL_MEMORY_GRAPH_ID, PRIVACY_VALUES, SOP_STATUSES, TEMPLATE_READ_TIMEOUT_MS, actualRelPathForView, adoptViewFile, apply, applyMigration, applySummaryWriteback, assertValidMemoryEntry, bindingKey, canManageGrants, canManageGraph, canReadPath, canReviewWorkflows, canViewGraph, canWritePath, checkLocalPath, classifyMount, createGrant, createKnowledgeEntry, createMemoryGuardianTools, createMemoryRecordTools, createMemoryTools, decideMemoryAction, deleteSopAfterPromotion, diffSnapshots, extractBeside, extractionOutcomeOf, fetchCaller, fetchGrants, fetchPrincipals, filterVisibleGraphs, inject, installMemoryTriggers, isFactKind, isMemoryType, isPrivacy, isSafeMemorySlug, isSopStatus, isTeamDeployment, kbSummarizeSkillPath, kbVectorizeSkillPath, knowledgeAncestorsFor, knowledgeBaseSkillProvider, knowledgeBaseToolDisclosure, knowledgeGraphScopeRoots, knowledgeGraphSkillPath, knowledgeSkillPath, listDirectory, listDirectoryShapes, listDirectoryWithPermissions, listGraphs, listRelativeFiles, loadGraph, localConfig, localManagementContext, localStatus, localStorageRoot, markUpstreamUpdates, memoryExtractSkillPath, memoryGuardianSkillPath, memorySopEvaluateSkillPath, mineruUrlFor, name, newMemoryId, parentChain, parseMemoryEntries, parseNodeFrontMatter, permissionForKbRoute, planContext, planMigration, promoteSopToSkill, readAuthorized, readDepartmentOf, readKnowledgeFile, readKnowledgeFileForDownload, readSharedMineruUrl, refreshDirtySummaries, renderMemoryContextMarkdown, renderMigrationReport, resolveMemoryContext, resolveMineruUrl, resolveOrCreateGuardian, resolveWorkflowActor, revokeGrant, runGuardianPass, runtimeInjectionTags, scanKnowledgeTree, searchKnowledge, sendToGuardian, serializeMemoryEntry, summarySnapshotPathFor, syncCallerView, syncPersonalMemoryGraph, toolScopedActualPath, toolScopedViewPath, tutorialTemplatePath, validateGraph, validateMemoryEntry, withLocalStorageRoot, withStoredStorage };
27220
+ export { BindingStore, Config, FACT_KINDS, GUARDIAN_SESSION_TITLE, GUARDIAN_SKILL_NAME, GraphLoadError, GuardianSessionStore, IDLE_DEBOUNCE_MS, KB_ROOT_RESOURCE_ID, KB_SUMMARIZE_SKILL_DESCRIPTION, KB_SUMMARIZE_SKILL_NAME, KB_SUMMARIZE_SKILL_RANK, KB_VECTORIZE_SKILL_DESCRIPTION, KB_VECTORIZE_SKILL_NAME, KB_VECTORIZE_SKILL_RANK, KNOWLEDGE_GRAPH_SKILL_DESCRIPTION, KNOWLEDGE_GRAPH_SKILL_NAME, KNOWLEDGE_SKILL_DESCRIPTION, KNOWLEDGE_SKILL_INVOCATION, KNOWLEDGE_SKILL_NAME, KNOWLEDGE_SKILL_PROVIDER, KNOWLEDGE_SKILL_RANK, KnowledgeError, KnowledgeWriteError, LOCAL_USER_ID, MAX_KNOWLEDGE_WRITE_BYTES, MEMORY_ENTRY_MARKER, MEMORY_EXTRACT_SKILL_NAME, MEMORY_FACT_FILE, MEMORY_GUARDIAN_SKILL_NAME, MEMORY_LOG_DIR, MEMORY_PITFALL_FILE, MEMORY_PREFERENCE_FILE, MEMORY_SOP_DIR, MEMORY_SOP_EVALUATE_SKILL_NAME, MEMORY_TYPES, MemoryGraphWriter, MemoryGraphWriterError, MemoryStore, MemoryStoreError, PERSONAL_MEMORY_FOLDER, PERSONAL_MEMORY_GRAPH_ID, PRIVACY_VALUES, SOP_STATUSES, TEMPLATE_READ_TIMEOUT_MS, actualRelPathForView, adoptViewFile, apply, applyMigration, applySummaryWriteback, assertValidMemoryEntry, bindingKey, canManageGrants, canManageGraph, canReadPath, canReviewWorkflows, canViewGraph, canWritePath, checkLocalPath, classifyMount, createGrant, createKnowledgeEntry, createMemoryGuardianTools, createMemoryRecordTools, createMemoryTools, decideMemoryAction, deleteSopAfterPromotion, diffSnapshots, extractBeside, extractionOutcomeOf, fetchCaller, fetchGrants, fetchPrincipals, filterVisibleGraphs, inject, installMemoryTriggers, isFactKind, isMemoryType, isPrivacy, isSafeMemorySlug, isSopStatus, isTeamDeployment, kbSummarizeSkillPath, kbVectorizeSkillPath, knowledgeAncestorsFor, knowledgeBaseSkillProvider, knowledgeBaseToolDisclosure, knowledgeGraphScopeRoots, knowledgeGraphSkillPath, knowledgeSkillPath, listDirectory, listDirectoryShapes, listDirectoryWithPermissions, listGraphs, listRelativeFiles, loadGraph, localConfig, localManagementContext, localStatus, localStorageRoot, markUpstreamUpdates, memoryExtractSkillPath, memoryGuardianSkillPath, memorySopEvaluateSkillPath, mineruUrlFor, name, newMemoryId, normalizePersonalWritePath, parentChain, parseMemoryEntries, parseNodeFrontMatter, permissionForKbRoute, planContext, planMigration, promoteSopToSkill, readAuthorized, readDepartmentOf, readKnowledgeFile, readKnowledgeFileForDownload, readSharedMineruUrl, refreshDirtySummaries, renderMemoryContextMarkdown, renderMigrationReport, resolveMemoryContext, resolveMineruUrl, resolveOrCreateGuardian, resolveWorkflowActor, revokeGrant, runGuardianPass, runtimeInjectionTags, scanKnowledgeTree, searchKnowledge, sendToGuardian, serializeMemoryEntry, summarySnapshotPathFor, syncCallerView, syncPersonalMemoryGraph, toolScopedActualPath, toolScopedViewPath, tutorialTemplatePath, validateGraph, validateMemoryEntry, withLocalStorageRoot, withStoredStorage };
@@ -263,6 +263,24 @@ export interface LocalPathRefusal {
263
263
  * @returns undefined when the path is allowed, else why it is not.
264
264
  */
265
265
  export declare function checkLocalPath(relPath: string): LocalPathRefusal | undefined;
266
+ /**
267
+ * Normalize a PERSONAL write path to the caller's own subtree.
268
+ *
269
+ * The page's upload destination is the virtual bucket `personal`, so a file dropped
270
+ * there arrives as `personal/<file>`. That spelling has no owner segment; writing it
271
+ * literally would put the document beside the owners and force the permission layer
272
+ * to grant the whole `personal` bucket, which resolves as shared across users.
273
+ * Rewriting it to `personal/<callerId>/<file>` keeps the owner in the path, makes the
274
+ * existing `personal/<userId>` grants sufficient, and keeps every user's personal
275
+ * bucket disjoint. An explicit `personal/<uuid>/…` is left untouched so a cross-user
276
+ * write still reaches the permission layer and is refused rather than silently
277
+ * redirected.
278
+ *
279
+ * @param relPath - the path as the caller sent it.
280
+ * @param callerId - the authenticated caller's user id.
281
+ * @returns the caller-scoped personal path, or the input when it is not personal.
282
+ */
283
+ export declare function normalizePersonalWritePath(relPath: string, callerId: string): string;
266
284
  /**
267
285
  * The resolved layout, derived on the Host.
268
286
  *
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sparkelf/dsh-knowledge-base",
3
- "version": "0.5.1",
3
+ "version": "0.5.3",
4
4
  "description": "DataOps-backed knowledge base for DeepSeek Harness: a left-sidebar destination, Settings configuration, and index tooling over a mounted NAS view.",
5
5
  "type": "module",
6
6
  "main": "./lib/index.js",