🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
🔒 fix(share): generate share-link ids from the CSPRNG (#23677)
Bryan4ee4cbbfde58
diff --git a/packages/database/src/models/__tests__/fileShare.test.ts b/packages/database/src/models/__tests__/fileShare.test.tsindex 2c66e1d4cbe..dd427066bf1 100644--- a/packages/database/src/models/__tests__/fileShare.test.ts+++ b/packages/database/src/models/__tests__/fileShare.test.ts@@ -45,7 +45,7 @@ describe('FileShareModel', () => {const result = await shareModel.create(fileId);expect(result).toMatchObject({ fileId, userId, visibility: 'private' });- expect(result!.id).toHaveLength(16);+ expect(result!.id).toMatch(/^[\w-]{22}$/);});it('creates a link share', async () => {diff --git a/packages/database/src/models/__tests__/goalShare.test.ts b/packages/database/src/models/__tests__/goalShare.test.tsindex 1aa37096458..2d43e474b8c 100644--- a/packages/database/src/models/__tests__/goalShare.test.ts+++ b/packages/database/src/models/__tests__/goalShare.test.ts@@ -43,7 +43,7 @@ describe('GoalShareModel', () => {const result = await shareModel.create(goalId);expect(result).toMatchObject({ goalId, userId, visibility: 'private' });- expect(result!.id).toHaveLength(16);+ expect(result!.id).toMatch(/^[\w-]{22}$/);});it('creates a link share', async () => {diff --git a/packages/database/src/schemas/fileShare.ts b/packages/database/src/schemas/fileShare.tsindex 956cd7af6cc..57506136f76 100644--- a/packages/database/src/schemas/fileShare.ts+++ b/packages/database/src/schemas/fileShare.ts@@ -1,7 +1,7 @@import type { FileShareConfig, ShareVisibility } from '@lobechat/types';import { index, integer, jsonb, pgTable, text, uniqueIndex } from 'drizzle-orm/pg-core';-import { createNanoId } from '../utils/idGenerator';+import { generateShareToken } from '../utils/idGenerator';import { timestamps } from './_helpers';import { files } from './file';import { users } from './user';@@ -15,9 +15,7 @@ import { workspaces } from './workspace';export const fileShares = pgTable('file_shares',{- id: text('id')- .$defaultFn(() => createNanoId(16)())- .primaryKey(),+ id: text('id').$defaultFn(generateShareToken).primaryKey(),fileId: text('file_id').notNull()diff --git a/packages/database/src/schemas/goalShare.ts b/packages/database/src/schemas/goalShare.tsindex c0479d1f059..a39f038734e 100644--- a/packages/database/src/schemas/goalShare.ts+++ b/packages/database/src/schemas/goalShare.ts@@ -1,7 +1,7 @@import type { GoalShareConfig, ShareVisibility } from '@lobechat/types';import { index, integer, jsonb, pgTable, text, uniqueIndex } from 'drizzle-orm/pg-core';-import { createNanoId } from '../utils/idGenerator';+import { generateShareToken } from '../utils/idGenerator';import { timestamps } from './_helpers';import { goals } from './goal';import { users } from './user';@@ -15,9 +15,7 @@ import { workspaces } from './workspace';export const goalShares = pgTable('goal_shares',{- id: text('id')- .$defaultFn(() => createNanoId(16)())- .primaryKey(),+ id: text('id').$defaultFn(generateShareToken).primaryKey(),goalId: text('goal_id').notNull()diff --git a/packages/database/src/schemas/topic.ts b/packages/database/src/schemas/topic.tsindex 340d9a6a118..0a81b42e0fc 100644--- a/packages/database/src/schemas/topic.ts+++ b/packages/database/src/schemas/topic.ts@@ -14,7 +14,7 @@ import {import { createInsertSchema, createUpdateSchema } from 'drizzle-zod';import { z } from 'zod';-import { createNanoId, idGenerator } from '../utils/idGenerator';+import { generateShareToken, idGenerator } from '../utils/idGenerator';import { amountNumeric, createdAt, softDeleteColumns, timestamps, timestamptz } from './_helpers';import { agents } from './agent';import { chatGroups } from './chatGroup';@@ -248,9 +248,7 @@ export type TopicDocumentItem = typeof topicDocuments.$inferSelect;export const topicShares = pgTable('topic_shares',{- id: text('id')- .$defaultFn(() => createNanoId(8)())- .primaryKey(),+ id: text('id').$defaultFn(generateShareToken).primaryKey(),topicId: text('topic_id').notNull()diff --git a/packages/database/src/utils/idGenerator.test.ts b/packages/database/src/utils/idGenerator.test.tsindex df1a5457ea7..a22d3d824d4 100644--- a/packages/database/src/utils/idGenerator.test.ts+++ b/packages/database/src/utils/idGenerator.test.ts@@ -1,6 +1,9 @@-import { describe, expect, it } from 'vitest';+import { describe, expect, it, vi } from 'vitest';-import { idGenerator } from './idGenerator';+import { fileShares } from '../schemas/fileShare';+import { goalShares } from '../schemas/goalShare';+import { topicShares } from '../schemas/topic';+import { generateShareToken, idGenerator } from './idGenerator';describe('idGenerator', () => {it('should generate an ID with the correct prefix and length', () => {@@ -40,3 +43,37 @@ describe('idGenerator', () => {);});});++describe('generateShareToken', () => {+ it('should draw from the platform CSPRNG', () => {+ const spy = vi.spyOn(crypto, 'getRandomValues');++ generateShareToken();++ expect(spy).toHaveBeenCalled();+ spy.mockRestore();+ });++ it('should carry at least 128 bits of entropy in a URL-safe alphabet', () => {+ const token = generateShareToken();++ expect(token).toMatch(/^[\w-]{22}$/);+ expect(Buffer.from(token, 'base64url')).toHaveLength(16);+ });++ it('should not collide across many generations', () => {+ const tokens = new Set(Array.from({ length: 1000 }, () => generateShareToken()));+ expect(tokens.size).toBe(1000);+ });++ it.each([+ ['topicShares', topicShares],+ ['fileShares', fileShares],+ ['goalShares', goalShares],+ ])('should back the %s id default', (_name, table) => {+ const token = table.id.defaultFn!() as string;++ expect(token).toMatch(/^[\w-]{22}$/);+ expect(Buffer.from(token, 'base64url')).toHaveLength(16);+ });+});diff --git a/packages/database/src/utils/idGenerator.ts b/packages/database/src/utils/idGenerator.tsindex ea42315710e..b3885e60ebe 100644--- a/packages/database/src/utils/idGenerator.ts+++ b/packages/database/src/utils/idGenerator.ts@@ -63,6 +63,17 @@ export const idGenerator = (namespace: keyof typeof prefixes, size = 12) => {return `${prefix}_${hash()}`;};+/**+ * Share-link ids act as bearer tokens in public URLs, so unlike internal ids+ * they must come from the platform CSPRNG and carry enough entropy to resist+ * enumeration. 16 random bytes encode to 22 base64url chars (128 bits).+ *+ * Stored ids are looked up verbatim, so links issued before this change with+ * shorter non-secure ids keep working — this only hardens newly issued shares.+ */+export const generateShareToken = () =>+ Buffer.from(crypto.getRandomValues(new Uint8Array(16))).toString('base64url');+export const randomSlug = (count = 2) => (generate(count) as string[]).join('-');export const inboxSessionId = (userId: string) => `ssn_inbox_${userId}`;