LibreChat/packages/api/src/utils/author.ts
Atef Bellaaj 585953acf9
🪑 feat: Add Shared Source Author and Distributed Lock Helpers (#17086)
* feat(api): add shared source-author and distributed-lock helpers

Lift makeSourceAuthorId out of the GitHub skill sync into
packages/api/src/utils/author.ts and add createDistributedLock in
packages/api/src/cache/lock.ts (Redis SET NX PX with owner-checked Lua
extend/release, in-process Map fallback without Redis). The skill sync
call site uses the shared helper; author ids are byte-identical.

* refactor(data-schemas): accept hex-string skill author in createSkill

CreateSkillInput.author takes a Types.ObjectId or a 24-hex string, and
createSkill builds the ObjectId once for both the uniqueness check and
the insert. The GitHub skill sync passes the makeSourceAuthorId string
as-is, so no Mongoose conversion remains at that call site in
packages/api.

* fix: validate skill authors and verify lock cleanup and ownership

---------

Co-authored-by: Rebase Probe <probe@example.com>
2026-10-24 13:46:15 +02:00

27 lines
1.3 KiB
TypeScript

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);
}