Skip to content

Enhanced ChatGPT Clone: Features Agents, MCP, Skills, DeepSeek, Anthropic, AWS, OpenAI, Responses API, Azure, Groq, o1, GPT-5, Mistral, OpenRouter, Vertex AI, Gemini, Artifacts, AI model switching, message search, Code Interpreter, langchain, DALL-E-3, OpenAPI Actions, Functions, Secure Multi-User Auth, Presets, open-source for self-hosting. Active

🪑 feat: Add Shared Source Author and Distributed Lock Helpers (#17086)

Atef Bellaaj585953acf9e0
diff --git a/packages/api/src/cache/index.ts b/packages/api/src/cache/index.ts
index 89a1156f0f..1ddba95f7a 100644
--- a/packages/api/src/cache/index.ts
+++ b/packages/api/src/cache/index.ts
@@ -8,3 +8,4 @@ export * from './pullRequests';
export * from './redisUtils';
export * from './redisTelemetry';
export * from './audit';
+export * from './lock';
diff --git a/packages/api/src/cache/lock.cache_integration.spec.ts b/packages/api/src/cache/lock.cache_integration.spec.ts
new file mode 100644
index 0000000000..3ef9231449
--- /dev/null
+++ b/packages/api/src/cache/lock.cache_integration.spec.ts
@@ -0,0 +1,133 @@
+import { randomUUID } from 'node:crypto';
+import { setTimeout as delay } from 'node:timers/promises';
+import type { RedisTestClient } from '../stream/__tests__/helpers/redis';
+import type { DistributedLock } from './lock';
+import { createRedisTestClient } from '../stream/__tests__/helpers/redis';
+import { createDistributedLock } from './lock';
+
+const describeRedis = process.env.USE_REDIS === 'true' ? describe : describe.skip;
+
+describeRedis('createDistributedLock (real Redis)', () => {
+ const keyPrefix = `DistributedLock-Integration-Test:${randomUUID()}:`;
+ const key = 'lock';
+ let redis: RedisTestClient;
+ let otherRedis: RedisTestClient;
+ let lock: DistributedLock;
+ let otherLock: DistributedLock;
+
+ beforeAll(async () => {
+ redis = createRedisTestClient(keyPrefix);
+ otherRedis = createRedisTestClient(keyPrefix);
+ await Promise.all([redis.connect(), otherRedis.connect()]);
+ lock = createDistributedLock({ redisClient: redis });
+ otherLock = createDistributedLock({ redisClient: otherRedis });
+ });
+
+ afterEach(async () => {
+ await redis.del(key);
+ });
+
+ afterAll(() => {
+ redis.disconnect();
+ otherRedis.disconnect();
+ });
+
+ async function acquire(ttlMs = 10_000): Promise<string> {
+ const token = await lock.acquire(key, ttlMs);
+ expect(token).toEqual(expect.any(String));
+ return token!;
+ }
+
+ async function waitForExpiry(): Promise<void> {
+ const deadline = Date.now() + 5_000;
+ while ((await redis.exists(key)) !== 0 && Date.now() < deadline) {
+ await delay(10);
+ }
+ expect(await redis.get(key)).toBeNull();
+ }
+
+ test('only one client acquires the key and Redis stores the owner with a TTL', async () => {
+ const tokens = await Promise.all([lock.acquire(key, 10_000), otherLock.acquire(key, 10_000)]);
+ const owners = tokens.filter((token) => token !== null);
+ expect(owners).toHaveLength(1);
+ expect(await redis.get(key)).toBe(owners[0]);
+ const ttl = await redis.pttl(key);
+ expect(ttl).toBeGreaterThan(0);
+ expect(ttl).toBeLessThanOrEqual(10_000);
+ });
+
+ test('only the owner extends the lease and changes its TTL', async () => {
+ const token = await acquire();
+ const originalTtl = await redis.pttl(key);
+
+ expect(await otherLock.extend(key, randomUUID(), 60_000)).toBe(false);
+ const rejectedTtl = await redis.pttl(key);
+ expect(rejectedTtl).toBeGreaterThan(0);
+ expect(rejectedTtl).toBeLessThanOrEqual(originalTtl);
+ expect(await redis.get(key)).toBe(token);
+
+ expect(await lock.extend(key, token, 60_000)).toBe(true);
+ const extendedTtl = await redis.pttl(key);
+ expect(extendedTtl).toBeGreaterThan(originalTtl);
+ expect(extendedTtl).toBeLessThanOrEqual(60_000);
+ expect(await redis.get(key)).toBe(token);
+ expect(await otherLock.acquire(key, 10_000)).toBeNull();
+ });
+
+ test('only the owner releases the lease and another client can then acquire it', async () => {
+ const token = await acquire();
+
+ expect(await otherLock.release(key, randomUUID())).toBe(false);
+ expect(await redis.get(key)).toBe(token);
+ expect(await otherLock.acquire(key, 10_000)).toBeNull();
+
+ expect(await lock.release(key, token)).toBe(true);
+ expect(await redis.get(key)).toBeNull();
+ expect(await lock.release(key, token)).toBe(false);
+ const replacement = await otherLock.acquire(key, 10_000);
+ expect(replacement).toEqual(expect.any(String));
+ expect(replacement).not.toBe(token);
+ expect(await redis.get(key)).toBe(replacement);
+ });
+
+ test.each(['extend', 'release'] as const)(
+ '%s rejects an expired token without recreating the key',
+ async (operation) => {
+ const token = await acquire(50);
+ await waitForExpiry();
+
+ const result =
+ operation === 'extend'
+ ? await lock.extend(key, token, 60_000)
+ : await lock.release(key, token);
+
+ expect(result).toBe(false);
+ expect(await redis.get(key)).toBeNull();
+ },
+ );
+
+ test.each(['extend', 'release'] as const)(
+ '%s rejects a stale token and preserves the replacement owner and TTL',
+ async (operation) => {
+ const token = await acquire(50);
+ await waitForExpiry();
+ const replacement = await otherLock.acquire(key, 10_000);
+ expect(replacement).toEqual(expect.any(String));
+ expect(replacement).not.toBe(token);
+ const originalTtl = await redis.pttl(key);
+
+ const result =
+ operation === 'extend'
+ ? await lock.extend(key, token, 60_000)
+ : await lock.release(key, token);
+
+ expect(result).toBe(false);
+ expect(await redis.get(key)).toBe(replacement);
+ const remainingTtl = await redis.pttl(key);
+ expect(remainingTtl).toBeGreaterThan(0);
+ expect(remainingTtl).toBeLessThanOrEqual(originalTtl);
+ expect(await otherLock.extend(key, replacement!, 60_000)).toBe(true);
+ expect(await otherLock.release(key, replacement!)).toBe(true);
+ },
+ );
+});
diff --git a/packages/api/src/cache/lock.spec.ts b/packages/api/src/cache/lock.spec.ts
new file mode 100644
index 0000000000..e15007cefb
--- /dev/null
+++ b/packages/api/src/cache/lock.spec.ts
@@ -0,0 +1,307 @@
+import type { DistributedLockRedisClient } from './lock';
+import { createDistributedLock } from './lock';
+
+const UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
+
+function createMockRedisClient(): jest.Mocked<DistributedLockRedisClient> {
+ return {
+ set: jest.fn(),
+ eval: jest.fn(),
+ evalsha: jest.fn(),
+ } as jest.Mocked<DistributedLockRedisClient>;
+}
+
+describe('createDistributedLock (Redis-backed)', () => {
+ test('acquire sets the key with an owner token and NX/PX, returns the token on OK', async () => {
+ const client = createMockRedisClient();
+ client.set.mockResolvedValueOnce('OK');
+ const lock = createDistributedLock({ redisClient: client });
+
+ const token = await lock.acquire('my-key', 5000);
+
+ expect(token).toMatch(UUID_PATTERN);
+ expect(client.set).toHaveBeenCalledWith('my-key', token, 'PX', 5000, 'NX');
+ });
+
+ test('acquire returns null when the key is already held', async () => {
+ const client = createMockRedisClient();
+ client.set.mockResolvedValueOnce(null);
+ const lock = createDistributedLock({ redisClient: client });
+
+ const token = await lock.acquire('my-key', 5000);
+
+ expect(token).toBeNull();
+ });
+
+ test('extend evaluates the extend script with (1, key, token, ttl) and returns true on 1', async () => {
+ const client = createMockRedisClient();
+ client.evalsha.mockResolvedValueOnce(1);
+ const lock = createDistributedLock({ redisClient: client });
+
+ const extended = await lock.extend('my-key', 'owner-token', 3000);
+
+ expect(extended).toBe(true);
+ expect(client.eval).not.toHaveBeenCalled();
+ expect(client.evalsha).toHaveBeenCalledTimes(1);
+ expect(client.evalsha.mock.calls[0].slice(1)).toEqual([1, 'my-key', 'owner-token', 3000]);
+ });
+
+ test('extend returns false on 0', async () => {
+ const client = createMockRedisClient();
+ client.evalsha.mockResolvedValueOnce(0);
+ const lock = createDistributedLock({ redisClient: client });
+
+ const extended = await lock.extend('my-key', 'owner-token', 3000);
+
+ expect(extended).toBe(false);
+ });
+
+ test('release evaluates the release script with (1, key, token) and resolves true on 1', async () => {
+ const client = createMockRedisClient();
+ client.evalsha.mockResolvedValueOnce(1);
+ const lock = createDistributedLock({ redisClient: client });
+
+ const released = await lock.release('my-key', 'owner-token');
+
+ expect(released).toBe(true);
+ expect(client.eval).not.toHaveBeenCalled();
+ expect(client.evalsha).toHaveBeenCalledTimes(1);
+ expect(client.evalsha.mock.calls[0].slice(1)).toEqual([1, 'my-key', 'owner-token']);
+ });
+
+ test('release returns false on 0', async () => {
+ const client = createMockRedisClient();
+ client.evalsha.mockResolvedValueOnce(0);
+ const lock = createDistributedLock({ redisClient: client });
+
+ const released = await lock.release('my-key', 'owner-token');
+
+ expect(released).toBe(false);
+ });
+
+ test('a NOSCRIPT error on evalsha still resolves extend via the EVAL fallback with the extend script', async () => {
+ const client = createMockRedisClient();
+ client.evalsha.mockRejectedValueOnce(new Error('NOSCRIPT No matching script'));
+ client.eval.mockResolvedValueOnce(1);
+ const lock = createDistributedLock({ redisClient: client });
+
+ const extended = await lock.extend('my-key', 'owner-token', 3000);
+
+ expect(extended).toBe(true);
+ expect(client.eval).toHaveBeenCalledTimes(1);
+ const script = client.eval.mock.calls[0][0] as string;
+ expect(script).toContain('PEXPIRE');
+ expect(script).not.toContain('DEL');
+ });
+
+ test('a NOSCRIPT error on evalsha still resolves release via the EVAL fallback with the release script', async () => {
+ const client = createMockRedisClient();
+ client.evalsha.mockRejectedValueOnce(new Error('NOSCRIPT No matching script'));
+ client.eval.mockResolvedValueOnce(1);
+ const lock = createDistributedLock({ redisClient: client });
+
+ const released = await lock.release('my-key', 'owner-token');
+
+ expect(released).toBe(true);
+ expect(client.eval).toHaveBeenCalledTimes(1);
+ const script = client.eval.mock.calls[0][0] as string;
+ expect(script).toContain('DEL');
+ expect(script).not.toContain('PEXPIRE');
+ });
+
+ test.each([0, -1, 1.5, NaN])('acquire throws RangeError for ttlMs %p', async (ttlMs) => {
+ const client = createMockRedisClient();
+ const lock = createDistributedLock({ redisClient: client });
+
+ await expect(lock.acquire('my-key', ttlMs)).rejects.toThrow(RangeError);
+ expect(client.set).not.toHaveBeenCalled();
+ });
+
+ test.each([0, -1, 1.5, NaN])('extend throws RangeError for ttlMs %p', async (ttlMs) => {
+ const client = createMockRedisClient();
+ const lock = createDistributedLock({ redisClient: client });
+
+ await expect(lock.extend('my-key', 'owner-token', ttlMs)).rejects.toThrow(RangeError);
+ expect(client.eval).not.toHaveBeenCalled();
+ expect(client.evalsha).not.toHaveBeenCalled();
+ });
+});
+
+describe('createDistributedLock (in-process)', () => {
+ test('a second acquire on a live key returns null', async () => {
+ const currentTime = 0;
+ const lock = createDistributedLock({ now: () => currentTime });
+
+ const first = await lock.acquire('key-1', 1000);
+ const second = await lock.acquire('key-1', 1000);
+
+ expect(first).toMatch(UUID_PATTERN);
+ expect(second).toBeNull();
+ });
+
+ test('acquire succeeds with a new token once the previous ttl has elapsed', async () => {
+ let currentTime = 0;
+ const lock = createDistributedLock({ now: () => currentTime });
+
+ const first = await lock.acquire('key-1', 1000);
+ currentTime = 1001;
+ const second = await lock.acquire('key-1', 1000);
+
+ expect(second).toMatch(UUID_PATTERN);
+ expect(second).not.toBe(first);
+ });
+
+ test('an expired token can no longer extend or release the new lock', async () => {
+ let currentTime = 0;
+ const lock = createDistributedLock({ now: () => currentTime });
+
+ const first = await lock.acquire('key-1', 1000);
+ currentTime = 1001;
+ await lock.acquire('key-1', 1000);
+
+ expect(await lock.extend('key-1', first as string, 1000)).toBe(false);
+ await lock.release('key-1', first as string);
+ expect(await lock.extend('key-1', first as string, 1000)).toBe(false);
+ });
+
+ test('extend by the owner pushes the expiry so a later acquire within the extended window still fails', async () => {
+ let currentTime = 0;
+ const lock = createDistributedLock({ now: () => currentTime });
+
+ const token = await lock.acquire('key-1', 1000);
+ currentTime = 900;
+ const extended = await lock.extend('key-1', token as string, 1000);
+ currentTime = 1500;
+ const reacquired = await lock.acquire('key-1', 1000);
+
+ expect(extended).toBe(true);
+ expect(reacquired).toBeNull();
+ });
+
+ test('extend by a non-owner returns false', async () => {
+ const currentTime = 0;
+ const lock = createDistributedLock({ now: () => currentTime });
+
+ await lock.acquire('key-1', 1000);
+ const extended = await lock.extend('key-1', 'not-the-owner', 1000);
+
+ expect(extended).toBe(false);
+ });
+
+ test('release by the owner frees the key immediately', async () => {
+ const currentTime = 0;
+ const lock = createDistributedLock({ now: () => currentTime });
+
+ const token = await lock.acquire('key-1', 1000);
+ await lock.release('key-1', token as string);
+ const reacquired = await lock.acquire('key-1', 1000);
+
+ expect(reacquired).toMatch(UUID_PATTERN);
+ });
+
+ test('release by a non-owner is a no-op; the owner keeps the lock', async () => {
+ const currentTime = 0;
+ const lock = createDistributedLock({ now: () => currentTime });
+
+ const token = await lock.acquire('key-1', 1000);
+ const released = await lock.release('key-1', 'not-the-owner');
+ const stillHeld = await lock.acquire('key-1', 1000);
+
+ expect(released).toBe(false);
+ expect(stillHeld).toBeNull();
+ expect(await lock.extend('key-1', token as string, 1000)).toBe(true);
+ });
+
+ test('release returns true for the owner', async () => {
+ const lock = createDistributedLock({ now: () => 0 });
+
+ const token = await lock.acquire('key-1', 1000);
+
+ expect(await lock.release('key-1', token as string)).toBe(true);
+ });
+
+ test('release returns false for an unknown key', async () => {
+ const lock = createDistributedLock({ now: () => 0 });
+
+ expect(await lock.release('no-such-key', 'some-token')).toBe(false);
+ });
+
+ test.each([0, -1, 1.5, NaN])('acquire throws RangeError for ttlMs %p', async (ttlMs) => {
+ const lock = createDistributedLock({ now: () => 0 });
+
+ await expect(lock.acquire('key-1', ttlMs)).rejects.toThrow(RangeError);
+ });
+
+ test.each([0, -1, 1.5, NaN])('extend throws RangeError for ttlMs %p', async (ttlMs) => {
+ const lock = createDistributedLock({ now: () => 0 });
+
+ await lock.acquire('key-1', 1000);
+ await expect(lock.extend('key-1', 'owner-token', ttlMs)).rejects.toThrow(RangeError);
+ });
+
+ test('an expired lock can neither be extended nor blocks a new acquire after other keys were used', async () => {
+ let currentTime = 0;
+ const lock = createDistributedLock({ now: () => currentTime });
+
+ const tokenA = await lock.acquire('key-a', 10);
+ currentTime = 20;
+ await lock.acquire('key-b', 10);
+
+ expect(await lock.extend('key-a', tokenA as string, 10)).toBe(false);
+ expect(await lock.acquire('key-a', 10)).toMatch(UUID_PATTERN);
+ });
+
+ test('exactly one of five concurrent acquire calls on one key succeeds', async () => {
+ const lock = createDistributedLock({ now: () => 0 });
+
+ const results = await Promise.all(Array.from({ length: 5 }, () => lock.acquire('key-1', 1000)));
+
+ const nonNull = results.filter((result) => result !== null);
+ expect(nonNull).toHaveLength(1);
+ });
+
+ test('different keys are independent', async () => {
+ const lock = createDistributedLock({ now: () => 0 });
+
+ const first = await lock.acquire('key-1', 1000);
+ const second = await lock.acquire('key-2', 1000);
+
+ expect(first).toMatch(UUID_PATTERN);
+ expect(second).toMatch(UUID_PATTERN);
+ });
+
+ test('crossing the sweep threshold reclaims keys that expired but were never touched again', async () => {
+ let currentTime = 0;
+ const lock = createDistributedLock({ now: () => currentTime });
+
+ for (let i = 0; i < 200; i += 1) {
+ await lock.acquire(`key-${i}`, 10);
+ }
+ const renewedToken = await lock.acquire('renewed', 10);
+ currentTime = 5;
+ expect(await lock.extend('renewed', renewedToken as string, 100)).toBe(true);
+ currentTime = 20;
+ const replacementToken = await lock.acquire('key-0', 100);
+
+ // The live-entry sweeps at sizes 64 and 128 moved the next threshold to 256.
+ for (let i = 200; i < 255; i += 1) {
+ await lock.acquire(`key-${i}`, 100);
+ }
+
+ // Cleanup is otherwise invisible through the public API: acquire can replace
+ // an expired entry even if the sweep never removes it.
+ const deleted = jest.spyOn(Map.prototype, 'delete');
+ try {
+ await lock.acquire('key-255', 100);
+ expect(deleted.mock.calls).toEqual(Array.from({ length: 199 }, (_, i) => [`key-${i + 1}`]));
+ } finally {
+ deleted.mockRestore();
+ }
+
+ expect(await lock.acquire('renewed', 100)).toBeNull();
+ expect(await lock.release('renewed', renewedToken as string)).toBe(true);
+ expect(await lock.acquire('key-0', 100)).toBeNull();
+ expect(await lock.release('key-0', replacementToken as string)).toBe(true);
+ expect(await lock.acquire('key-200', 100)).toBeNull();
+ });
+});
diff --git a/packages/api/src/cache/lock.ts b/packages/api/src/cache/lock.ts
new file mode 100644
index 0000000000..cf6e9be76d
--- /dev/null
+++ b/packages/api/src/cache/lock.ts
@@ -0,0 +1,145 @@
+import { randomUUID } from 'node:crypto';
+import type { Redis, Cluster } from 'ioredis';
+import type { RedisScriptClient } from './redisScript';
+import { evalScript } from './redisScript';
+
+export type DistributedLock = {
+ /** Claims `key` for `ttlMs`. Returns an owner token, or null when another owner holds it. Throws `RangeError` when `ttlMs` is not a positive integer. */
+ acquire(key: string, ttlMs: number): Promise<string | null>;
+ /** Pushes the expiry of a lock this token owns. False when the lock is gone or owned by someone else. Throws `RangeError` when `ttlMs` is not a positive integer. */
+ extend(key: string, token: string, ttlMs: number): Promise<boolean>;
+ /** Releases only if this token still owns the lock. False means the lease already expired before this call, so the key was gone or held by a different token; true means this call deleted it. */
+ release(key: string, token: string): Promise<boolean>;
+};
+
+export type DistributedLockRedisClient = RedisScriptClient & Pick<Redis | Cluster, 'set'>;
+
+export type CreateDistributedLockOptions = {
+ /** When present the lock is shared across processes. When absent an in-process lock is used. */
+ redisClient?: DistributedLockRedisClient | null;
+ /** Injectable clock for the in-process path (tests). */
+ now?: () => number;
+};
+
+const EXTEND_SCRIPT = `
+if redis.call('GET', KEYS[1]) == ARGV[1] then
+ return redis.call('PEXPIRE', KEYS[1], ARGV[2])
+end
+return 0
+`;
+
+const RELEASE_SCRIPT = `
+if redis.call('GET', KEYS[1]) == ARGV[1] then
+ return redis.call('DEL', KEYS[1])
+end
+return 0
+`;
+
+const SWEEP_MIN_SIZE = 64;
+
+function assertTtl(ttlMs: number): void {
+ if (!Number.isInteger(ttlMs) || ttlMs <= 0) {
+ throw new RangeError(`ttlMs must be a positive integer, got ${ttlMs}`);
+ }
+}
+
+function createRedisLock(redisClient: DistributedLockRedisClient): DistributedLock {
+ return {
+ async acquire(key, ttlMs) {
+ assertTtl(ttlMs);
+ const token = randomUUID();
+ const result = await redisClient.set(key, token, 'PX', ttlMs, 'NX');
+ return result === 'OK' ? token : null;
+ },
+ async extend(key, token, ttlMs) {
+ assertTtl(ttlMs);
+ const result = await evalScript(redisClient, EXTEND_SCRIPT, 1, key, token, ttlMs);
+ return Number(result) === 1;
+ },
+ async release(key, token) {
+ const result = await evalScript(redisClient, RELEASE_SCRIPT, 1, key, token);
+ return Number(result) === 1;
+ },
+ };
+}
+
+function createInProcessLock(now: () => number): DistributedLock {
+ const locks = new Map<string, { token: string; expiresAt: number }>();
+ let sweepAt = SWEEP_MIN_SIZE;
+ function evictExpired(): void {
+ const currentTime = now();
+ for (const [key, entry] of locks) {
+ if (entry.expiresAt <= currentTime) {
+ locks.delete(key);
+ }
+ }
+ }
+ return {
+ async acquire(key, ttlMs) {
+ assertTtl(ttlMs);
+ // Sweeping on every call would make acquire O(n) in the table size. Instead the
+ // sweep runs only once the table has grown past a size-tracking threshold, so
+ // acquire stays amortized O(1) while expired keys that are never touched again
+ // still get reclaimed.
+ if (locks.size >= sweepAt) {
+ evictExpired();
+ sweepAt = Math.max(SWEEP_MIN_SIZE, locks.size * 2);
+ }
+ const existing = locks.get(key);
+ if (existing && existing.expiresAt > now()) {
+ return null;
+ }
+ const token = randomUUID();
+ locks.set(key, { token, expiresAt: now() + ttlMs });
+ return token;
+ },
+ async extend(key, token, ttlMs) {
+ assertTtl(ttlMs);
+ const existing = locks.get(key);
+ if (existing && existing.expiresAt <= now()) {
+ locks.delete(key);
+ return false;
+ }
+ if (!existing || existing.token !== token) {
+ return false;
+ }
+ existing.expiresAt = now() + ttlMs;
+ return true;
+ },
+ async release(key, token) {
+ const existing = locks.get(key);
+ if (existing && existing.expiresAt <= now()) {
+ locks.delete(key);
+ return false;
+ }
+ if (existing && existing.token === token) {
+ locks.delete(key);
+ return true;
+ }
+ return false;
+ },
+ };
+}
+
+/**
+ * Creates a `DistributedLock` for coordinating a critical section across callers.
+ *
+ * The Redis client is a caller-supplied dependency rather than an imported
+ * singleton (`ioredisClient`), so callers can instrument or mock it.
+ *
+ * The in-process lock coordinates only inside one process. Multi-node
+ * deployments must pass a Redis client; LibreChat already requires shared
+ * Redis for multi-replica features (see `.env.example`, scheduled chats).
+ *
+ * Each instance owns its own key namespace: callers that must exclude each
+ * other share one `DistributedLock` instance, the same way they share the
+ * Redis client. Two instances created without a Redis client do not
+ * coordinate.
+ */
+export function createDistributedLock(options: CreateDistributedLockOptions = {}): DistributedLock {
+ const { redisClient, now = Date.now } = options;
+ if (redisClient != null) {
+ return createRedisLock(redisClient);
+ }
+ return createInProcessLock(now);
+}
diff --git a/packages/api/src/skills/sync/github.spec.ts b/packages/api/src/skills/sync/github.spec.ts
index 3781c2349f..3aaa1bfef2 100644
--- a/packages/api/src/skills/sync/github.spec.ts
+++ b/packages/api/src/skills/sync/github.spec.ts
@@ -201,7 +201,7 @@ function makeSkill(input: CreateSkillInput): ISkill & { _id: Types.ObjectId } {
description: input.description,
body: input.body ?? '',
frontmatter: input.frontmatter ?? {},
- author: input.author,
+ author: new Types.ObjectId(input.author),
authorName: input.authorName,
version: 1,
source: input.source ?? 'inline',
diff --git a/packages/api/src/skills/sync/github.ts b/packages/api/src/skills/sync/github.ts
index f6b389b795..0002532336 100644
--- a/packages/api/src/skills/sync/github.ts
+++ b/packages/api/src/skills/sync/github.ts
@@ -40,6 +40,7 @@ import {
createGitHubRepoAdapter,
} from './adapters/github';
import { DEFAULT_SKILL_IMPORT_LIMITS } from '../limits';
+import { makeSourceAuthorId } from '~/utils/author';
import { withSkillUploadIntent } from '../intent';
import { parseSkillMarkdown } from '../parse';
import { normalizeRepoPath } from './path';
@@ -304,18 +305,6 @@ function makeUpstreamId(source: SkillSyncGitHubSourceConfig, rootPath: string):
return `${source.id}:${rootPath}`;
}
-function makeSourceAuthorId(source: SkillSyncGitHubSourceConfig): Types.ObjectId {
- // Fold the tenant into the synthetic author so the same source mirrored into
- // different tenants gets distinct author ids (clearer audits, no cross-tenant
- // author collisions). The tenant suffix is omitted when absent so single-tenant
- // author ids stay stable.
- const seed = source.tenantId
- ? `${PROVIDER}:${source.id}:${source.tenantId}`
- : `${PROVIDER}:${source.id}`;
- const digest = crypto.createHash('sha256').update(seed).digest('hex').slice(0, 24);
- return new Types.ObjectId(digest);
-}
-
function toSkillName(value: string): string {
const normalized = value
.toLowerCase()
@@ -872,7 +861,7 @@ function makeCreateInput(
...(update as Omit<UpdateSkillInput, 'source'>),
name: update.name ?? fallbackName,
description: update.description ?? fallbackName,
- author: makeSourceAuthorId(source),
+ author: makeSourceAuthorId(PROVIDER, source.id, source.tenantId),
authorName: SYSTEM_AUTHOR_NAME,
source: PROVIDER,
tenantId: source.tenantId,
diff --git a/packages/api/src/utils/author.spec.ts b/packages/api/src/utils/author.spec.ts
new file mode 100644
index 0000000000..adbb98067b
--- /dev/null
+++ b/packages/api/src/utils/author.spec.ts
@@ -0,0 +1,70 @@
+import { createHash } from 'node:crypto';
+import { isValidObjectIdString } from '@librechat/data-schemas';
+import { makeSourceAuthorId } from './author';
+
+describe('makeSourceAuthorId', () => {
+ it('returns 24 lowercase hex characters', () => {
+ const id = makeSourceAuthorId('github', 'librechat-skills');
+ expect(id).toMatch(/^[0-9a-f]{24}$/);
+ });
+
+ it('returns the same output for the same inputs', () => {
+ const first = makeSourceAuthorId('github', 'librechat-skills', 'tenant-1');
+ const second = makeSourceAuthorId('github', 'librechat-skills', 'tenant-1');
+ expect(first).toBe(second);
+ });
+
+ it('returns a different output for a different sourceId', () => {
+ const first = makeSourceAuthorId('github', 'librechat-skills');
+ const second = makeSourceAuthorId('github', 'other-skills');
+ expect(first).not.toBe(second);
+ });
+
+ it('returns a different output for a different tenantId', () => {
+ const first = makeSourceAuthorId('github', 'librechat-skills', 'tenant-1');
+ const second = makeSourceAuthorId('github', 'librechat-skills', 'tenant-2');
+ expect(first).not.toBe(second);
+ });
+
+ it('treats an undefined tenantId and an empty tenantId the same', () => {
+ const withUndefined = makeSourceAuthorId('github', 'librechat-skills', undefined);
+ const withEmpty = makeSourceAuthorId('github', 'librechat-skills', '');
+ expect(withUndefined).toBe(withEmpty);
+ });
+
+ it('matches the GitHub sync reference computation without a tenant', () => {
+ const seed = 'github:librechat-skills';
+ const expected = createHash('sha256').update(seed).digest('hex').slice(0, 24);
+ expect(makeSourceAuthorId('github', 'librechat-skills')).toBe(expected);
+ });
+
+ it('matches the GitHub sync reference computation with a tenant', () => {
+ const seed = 'github:librechat-skills:tenant-1';
+ const expected = createHash('sha256').update(seed).digest('hex').slice(0, 24);
+ expect(makeSourceAuthorId('github', 'librechat-skills', 'tenant-1')).toBe(expected);
+ });
+
+ it('produces a valid 24-hex ObjectId string', () => {
+ const id = makeSourceAuthorId('github', 'librechat-skills', 'tenant-1');
+ expect(isValidObjectIdString(id)).toBe(true);
+ });
+
+ it('throws when provider contains ":"', () => {
+ expect(() => makeSourceAuthorId('git:hub', 'librechat-skills')).toThrow(/must not contain/);
+ });
+
+ it('throws when sourceId contains ":"', () => {
+ expect(() => makeSourceAuthorId('github', 'librechat:skills')).toThrow(/must not contain/);
+ });
+
+ it('throws when tenantId contains ":"', () => {
+ expect(() => makeSourceAuthorId('github', 'librechat-skills', 'tenant:1')).toThrow(
+ /must not contain/,
+ );
+ });
+
+ it('does not throw for a tenantId of undefined or empty string', () => {
+ expect(() => makeSourceAuthorId('github', 'librechat-skills', undefined)).not.toThrow();
+ expect(() => makeSourceAuthorId('github', 'librechat-skills', '')).not.toThrow();
+ });
+});
diff --git a/packages/api/src/utils/author.ts b/packages/api/src/utils/author.ts
new file mode 100644
index 0000000000..e36c4bd3c6
--- /dev/null
+++ b/packages/api/src/utils/author.ts
@@ -0,0 +1,27 @@
+import { createHash } from 'node:crypto';
+
+/**
+ * Deterministic 24-hex id for records owned by an external source rather than a user.
+ * Seed is `provider:sourceId` or `provider:sourceId:tenantId`. The tenant segment is
+ * omitted when absent so single-tenant ids stay stable. The result has the shape of an
+ * ObjectId; data-schemas methods that store it accept the hex string and construct the
+ * ObjectId themselves, so no Mongoose type enters this package's exported signatures.
+ *
+ * The components are joined with `:` and are not escaped, so this function throws when
+ * `provider`, `sourceId`, or a provided `tenantId` contains `:`; otherwise two different
+ * inputs could share a seed. The seed is kept identical to the ids the GitHub skill sync
+ * already stores, so the encoding cannot change without re-keying existing records.
+ */
+export function makeSourceAuthorId(provider: string, sourceId: string, tenantId?: string): string {
+ for (const [name, value] of [
+ ['provider', provider],
+ ['sourceId', sourceId],
+ ['tenantId', tenantId],
+ ] as const) {
+ if (value?.includes(':')) {
+ throw new Error(`makeSourceAuthorId components must not contain ":" (got ${name})`);
+ }
+ }
+ const seed = tenantId ? `${provider}:${sourceId}:${tenantId}` : `${provider}:${sourceId}`;
+ return createHash('sha256').update(seed).digest('hex').slice(0, 24);
+}
diff --git a/packages/api/src/utils/index.ts b/packages/api/src/utils/index.ts
index 8b1906e44d..c920eaf193 100644
--- a/packages/api/src/utils/index.ts
+++ b/packages/api/src/utils/index.ts
@@ -2,6 +2,7 @@ export * from './axios';
export * from './streams';
export * from './timeouts';
export * from './azure';
+export * from './author';
export * from './code';
export * from './common';
export * from './content';
diff --git a/packages/data-schemas/src/methods/skill.spec.ts b/packages/data-schemas/src/methods/skill.spec.ts
index 937011a4b4..d94e13c0a5 100644
--- a/packages/data-schemas/src/methods/skill.spec.ts
+++ b/packages/data-schemas/src/methods/skill.spec.ts
@@ -746,6 +746,46 @@ describe('Skill CRUD methods', () => {
await expect(methods.createSkill(makeSkillInput())).rejects.toBeDefined();
});
+ it.each(['abcdef0123456789abcdef01', 'ABCDEF0123456789ABCDEF01'])(
+ 'accepts hex string author %s and stores it as an ObjectId',
+ async (hexAuthor) => {
+ const { skill } = await methods.createSkill(
+ makeSkillInput({ name: 'hex-author-skill', author: hexAuthor }),
+ );
+ expect(skill.author).toBeInstanceOf(mongoose.Types.ObjectId);
+ expect(skill.author.toHexString()).toBe(hexAuthor.toLowerCase());
+ },
+ );
+
+ it.each(['', 'not-an-id', 'a'.repeat(23), 'a'.repeat(25), 'g'.repeat(24)])(
+ 'rejects malformed string author %p with a validation error before querying',
+ async (author) => {
+ const findOne = jest.spyOn(Skill, 'findOne');
+
+ await expect(methods.createSkill(makeSkillInput({ author }))).rejects.toMatchObject({
+ message: 'Skill validation failed',
+ code: 'SKILL_VALIDATION_FAILED',
+ issues: [{ field: 'author', code: 'INVALID_FORMAT' }],
+ });
+ expect(findOne).not.toHaveBeenCalled();
+ },
+ );
+
+ it('enforces name uniqueness per author across ObjectId and string forms', async () => {
+ const hexAuthor = new mongoose.Types.ObjectId().toHexString();
+ await methods.createSkill(
+ makeSkillInput({ name: 'mixed-author-form-skill', author: hexAuthor }),
+ );
+ await expect(
+ methods.createSkill(
+ makeSkillInput({
+ name: 'mixed-author-form-skill',
+ author: new mongoose.Types.ObjectId(hexAuthor),
+ }),
+ ),
+ ).rejects.toBeDefined();
+ });
+
it('throws with validation issues on bad input', async () => {
await expect(methods.createSkill(makeSkillInput({ name: 'BAD NAME' }))).rejects.toMatchObject({
code: 'SKILL_VALIDATION_FAILED',
diff --git a/packages/data-schemas/src/methods/skill.ts b/packages/data-schemas/src/methods/skill.ts
index 0b371c2724..694c8c2f78 100644
--- a/packages/data-schemas/src/methods/skill.ts
+++ b/packages/data-schemas/src/methods/skill.ts
@@ -608,7 +608,8 @@ export type CreateSkillInput = {
body?: string;
frontmatter?: Record<string, unknown>;
category?: string;
- author: Types.ObjectId;
+ /** A 24-hex string is accepted and converted to an ObjectId here. */
+ author: Types.ObjectId | string;
authorName: string;
source?: 'inline' | 'github' | 'notion';
sourceMetadata?: Record<string, unknown>;
@@ -1176,6 +1177,13 @@ export function createSkillMethods(
...validateSkillFrontmatter(frontmatter),
...validateAlwaysApply(data.alwaysApply),
];
+ if (typeof data.author === 'string' && !isValidObjectIdString(data.author)) {
+ issues.push({
+ field: 'author',
+ code: 'INVALID_FORMAT',
+ message: 'Author must be a 24-character hex string',
+ });
+ }
/* Body-level `always-apply:` only needs to be well-formed when a
higher-precedence source won't override it (see
`resolveAlwaysApplyFromInput` for the cascade). A caller sending
@@ -1204,6 +1212,7 @@ export function createSkillMethods(
}
const Skill = mongoose.models.Skill as Model<ISkillDocument>;
+ const author = new mongoose.Types.ObjectId(data.author);
// Application-level uniqueness check on (name, author, tenantId).
// The unique index in the schema is the persistent guarantee, but Mongoose
@@ -1211,7 +1220,7 @@ export function createSkillMethods(
// so we also enforce it here for deterministic behavior and a clean error.
const existing = await Skill.findOne({
name: data.name,
- author: data.author,
+ author,
tenantId: data.tenantId ?? null,
})
.select('_id')
@@ -1230,7 +1239,7 @@ export function createSkillMethods(
body: data.body ?? '',
frontmatter: frontmatter ?? {},
category: data.category ?? '',
- author: data.author,
+ author,
authorName: data.authorName,
version: 1,
source: data.source ?? 'inline',