@open-mercato/shared 0.6.7-develop.6784.1.f80b9afce5 → 0.6.7-develop.6785.1.1dd7cfac55
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/.turbo/turbo-build.log +1 -1
- package/dist/lib/ai/safety-identifier.js +32 -0
- package/dist/lib/ai/safety-identifier.js.map +7 -0
- package/dist/lib/version.js +1 -1
- package/dist/lib/version.js.map +1 -1
- package/package.json +2 -2
- package/src/lib/ai/__tests__/llm-provider-contract.test.ts +59 -0
- package/src/lib/ai/__tests__/safety-identifier.test.ts +71 -0
- package/src/lib/ai/llm-provider.ts +33 -0
- package/src/lib/ai/safety-identifier.ts +73 -0
package/.turbo/turbo-build.log
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
[build:shared] found
|
|
1
|
+
[build:shared] found 251 entry points
|
|
2
2
|
[build:shared] built successfully
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import crypto from "node:crypto";
|
|
2
|
+
const SAFETY_IDENTIFIER_SECRET_LABEL = "open-mercato:ai-safety-identifier:v1";
|
|
3
|
+
const derivedSecretCache = /* @__PURE__ */ new Map();
|
|
4
|
+
function readBaseSecret(explicit) {
|
|
5
|
+
const secret = explicit ?? process.env.JWT_SECRET;
|
|
6
|
+
if (!secret) {
|
|
7
|
+
throw new Error("[internal] JWT_SECRET is not set; cannot derive AI safety-identifier secret");
|
|
8
|
+
}
|
|
9
|
+
return secret;
|
|
10
|
+
}
|
|
11
|
+
function deriveAiSafetyIdentifierSecret(baseSecret) {
|
|
12
|
+
const base = readBaseSecret(baseSecret);
|
|
13
|
+
const cached = derivedSecretCache.get(base);
|
|
14
|
+
if (cached !== void 0) return cached;
|
|
15
|
+
const derived = crypto.createHmac("sha256", base).update(SAFETY_IDENTIFIER_SECRET_LABEL).digest("hex");
|
|
16
|
+
derivedSecretCache.set(base, derived);
|
|
17
|
+
return derived;
|
|
18
|
+
}
|
|
19
|
+
function computeEndUserIdentifier(tenantId, userId, options) {
|
|
20
|
+
const normalizedUser = (userId ?? "").trim();
|
|
21
|
+
if (!normalizedUser) {
|
|
22
|
+
throw new Error("[internal] computeEndUserIdentifier requires a non-empty userId");
|
|
23
|
+
}
|
|
24
|
+
const key = deriveAiSafetyIdentifierSecret(options?.baseSecret);
|
|
25
|
+
const salt = (tenantId ?? "").trim();
|
|
26
|
+
return crypto.createHmac("sha256", key).update(`${salt}:${normalizedUser}`).digest("hex");
|
|
27
|
+
}
|
|
28
|
+
export {
|
|
29
|
+
computeEndUserIdentifier,
|
|
30
|
+
deriveAiSafetyIdentifierSecret
|
|
31
|
+
};
|
|
32
|
+
//# sourceMappingURL=safety-identifier.js.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../../src/lib/ai/safety-identifier.ts"],
|
|
4
|
+
"sourcesContent": ["/**\n * End-user safety identifiers for AI provider calls.\n *\n * Providers such as OpenAI let developers attach an opaque per-end-user\n * identifier to each request so abuse enforcement can target one user instead\n * of suspending the whole API-key organization. We never send a reversible id:\n * the value is a tenant-salted HMAC computed from the platform's existing auth\n * secret, so no PII or internal id leaves the platform and the same end user in\n * two tenants produces two unrelated hashes.\n *\n * The per-process secret derivation mirrors `deriveJwtAudienceSecret`\n * (`@open-mercato/shared/lib/auth/jwt`): one HMAC from the base `JWT_SECRET`\n * under a versioned purpose label, memoized for the process lifetime. No new\n * secret to provision.\n *\n * @see .ai/specs/2026-06-04-ai-input-moderation-and-safety-identifiers.md\n */\n\nimport crypto from 'node:crypto'\n\nconst SAFETY_IDENTIFIER_SECRET_LABEL = 'open-mercato:ai-safety-identifier:v1'\n\nconst derivedSecretCache = new Map<string, string>()\n\nfunction readBaseSecret(explicit?: string): string {\n const secret = explicit ?? process.env.JWT_SECRET\n if (!secret) {\n throw new Error('[internal] JWT_SECRET is not set; cannot derive AI safety-identifier secret')\n }\n return secret\n}\n\n/**\n * Derive the per-process safety-identifier HMAC key from the base auth secret.\n *\n * Deterministic HMAC-SHA256 of a versioned purpose label keyed by the base\n * secret, memoized per base secret. Rotating the base secret rotates every\n * derived identifier \u2014 documented as accepted (identifiers are advisory\n * provider-side metadata, not an in-platform security control).\n */\nexport function deriveAiSafetyIdentifierSecret(baseSecret?: string): string {\n const base = readBaseSecret(baseSecret)\n const cached = derivedSecretCache.get(base)\n if (cached !== undefined) return cached\n const derived = crypto\n .createHmac('sha256', base)\n .update(SAFETY_IDENTIFIER_SECRET_LABEL)\n .digest('hex')\n derivedSecretCache.set(base, derived)\n return derived\n}\n\n/**\n * Compute the opaque end-user safety identifier for a (tenant, user) pair.\n *\n * Returns a 64-char lowercase hex HMAC-SHA256 of `${tenantId}:${userId}` keyed\n * by the derived secret. Throws (with an `[internal]` message) when the base\n * secret is missing or `userId` is empty \u2014 callers in the runtime wrap this in\n * a best-effort try/catch so identifier-derivation failures never break chat.\n */\nexport function computeEndUserIdentifier(\n tenantId: string | null | undefined,\n userId: string,\n options?: { baseSecret?: string },\n): string {\n const normalizedUser = (userId ?? '').trim()\n if (!normalizedUser) {\n throw new Error('[internal] computeEndUserIdentifier requires a non-empty userId')\n }\n const key = deriveAiSafetyIdentifierSecret(options?.baseSecret)\n const salt = (tenantId ?? '').trim()\n return crypto.createHmac('sha256', key).update(`${salt}:${normalizedUser}`).digest('hex')\n}\n"],
|
|
5
|
+
"mappings": "AAkBA,OAAO,YAAY;AAEnB,MAAM,iCAAiC;AAEvC,MAAM,qBAAqB,oBAAI,IAAoB;AAEnD,SAAS,eAAe,UAA2B;AACjD,QAAM,SAAS,YAAY,QAAQ,IAAI;AACvC,MAAI,CAAC,QAAQ;AACX,UAAM,IAAI,MAAM,6EAA6E;AAAA,EAC/F;AACA,SAAO;AACT;AAUO,SAAS,+BAA+B,YAA6B;AAC1E,QAAM,OAAO,eAAe,UAAU;AACtC,QAAM,SAAS,mBAAmB,IAAI,IAAI;AAC1C,MAAI,WAAW,OAAW,QAAO;AACjC,QAAM,UAAU,OACb,WAAW,UAAU,IAAI,EACzB,OAAO,8BAA8B,EACrC,OAAO,KAAK;AACf,qBAAmB,IAAI,MAAM,OAAO;AACpC,SAAO;AACT;AAUO,SAAS,yBACd,UACA,QACA,SACQ;AACR,QAAM,kBAAkB,UAAU,IAAI,KAAK;AAC3C,MAAI,CAAC,gBAAgB;AACnB,UAAM,IAAI,MAAM,iEAAiE;AAAA,EACnF;AACA,QAAM,MAAM,+BAA+B,SAAS,UAAU;AAC9D,QAAM,QAAQ,YAAY,IAAI,KAAK;AACnC,SAAO,OAAO,WAAW,UAAU,GAAG,EAAE,OAAO,GAAG,IAAI,IAAI,cAAc,EAAE,EAAE,OAAO,KAAK;AAC1F;",
|
|
6
|
+
"names": []
|
|
7
|
+
}
|
package/dist/lib/version.js
CHANGED
package/dist/lib/version.js.map
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/lib/version.ts"],
|
|
4
|
-
"sourcesContent": ["// Build-time generated version\nexport const APP_VERSION = '0.6.7-develop.
|
|
4
|
+
"sourcesContent": ["// Build-time generated version\nexport const APP_VERSION = '0.6.7-develop.6785.1.1dd7cfac55'\nexport const appVersion = APP_VERSION\n"],
|
|
5
5
|
"mappings": "AACO,MAAM,cAAc;AACpB,MAAM,aAAa;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@open-mercato/shared",
|
|
3
|
-
"version": "0.6.7-develop.
|
|
3
|
+
"version": "0.6.7-develop.6785.1.1dd7cfac55",
|
|
4
4
|
"license": "MIT",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.js",
|
|
@@ -105,7 +105,7 @@
|
|
|
105
105
|
"@mikro-orm/core": "^7.1.5",
|
|
106
106
|
"@mikro-orm/decorators": "^7.1.5",
|
|
107
107
|
"@mikro-orm/postgresql": "^7.1.5",
|
|
108
|
-
"@open-mercato/cache": "0.6.7-develop.
|
|
108
|
+
"@open-mercato/cache": "0.6.7-develop.6785.1.1dd7cfac55",
|
|
109
109
|
"@types/sanitize-html": "^2.16.1",
|
|
110
110
|
"dotenv": "^17.4.2",
|
|
111
111
|
"pino": "^10.3.1",
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
import type { EnvLookup, LlmProvider, LlmCreateModelOptions } from '../llm-provider'
|
|
2
|
+
|
|
3
|
+
function makeBaseProvider(overrides: Partial<LlmProvider> = {}): LlmProvider {
|
|
4
|
+
const id = overrides.id ?? 'contract-provider'
|
|
5
|
+
const envKeys = overrides.envKeys ?? [`${id.toUpperCase()}_API_KEY`]
|
|
6
|
+
const base: LlmProvider = {
|
|
7
|
+
id,
|
|
8
|
+
name: `Contract Provider ${id}`,
|
|
9
|
+
envKeys,
|
|
10
|
+
defaultModel: 'contract-model',
|
|
11
|
+
defaultModels: [{ id: 'contract-model', name: 'Contract Model', contextWindow: 8192 }],
|
|
12
|
+
isConfigured(env?: EnvLookup): boolean {
|
|
13
|
+
const lookup = env ?? process.env
|
|
14
|
+
return envKeys.some((key) => {
|
|
15
|
+
const value = lookup[key]
|
|
16
|
+
return typeof value === 'string' && value.trim().length > 0
|
|
17
|
+
})
|
|
18
|
+
},
|
|
19
|
+
resolveApiKey(): string | null {
|
|
20
|
+
return null
|
|
21
|
+
},
|
|
22
|
+
getConfiguredEnvKey(): string {
|
|
23
|
+
return envKeys[0]
|
|
24
|
+
},
|
|
25
|
+
createModel(options: LlmCreateModelOptions) {
|
|
26
|
+
return { __kind: 'contract-model', modelId: options.modelId }
|
|
27
|
+
},
|
|
28
|
+
}
|
|
29
|
+
return { ...base, ...overrides }
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
describe('LlmProvider contract — moderation/safety-identifier additive members', () => {
|
|
33
|
+
it('treats mapEndUserIdentifier and supportsInputModeration as optional (legacy adapters)', () => {
|
|
34
|
+
const provider = makeBaseProvider()
|
|
35
|
+
expect(provider.mapEndUserIdentifier).toBeUndefined()
|
|
36
|
+
expect(provider.supportsInputModeration).toBeUndefined()
|
|
37
|
+
})
|
|
38
|
+
|
|
39
|
+
it('accepts an optional endUserIdentifier on createModel options without changing behavior', () => {
|
|
40
|
+
const provider = makeBaseProvider()
|
|
41
|
+
const withIdentifier: LlmCreateModelOptions = {
|
|
42
|
+
modelId: 'contract-model',
|
|
43
|
+
apiKey: 'sk-test',
|
|
44
|
+
endUserIdentifier: 'hashed-identifier',
|
|
45
|
+
}
|
|
46
|
+
expect(provider.createModel(withIdentifier)).toEqual({ __kind: 'contract-model', modelId: 'contract-model' })
|
|
47
|
+
})
|
|
48
|
+
|
|
49
|
+
it('exposes a providerOptions fragment when mapEndUserIdentifier is implemented', () => {
|
|
50
|
+
const provider = makeBaseProvider({
|
|
51
|
+
mapEndUserIdentifier(identifier: string) {
|
|
52
|
+
return { contract: { user_id: identifier } }
|
|
53
|
+
},
|
|
54
|
+
supportsInputModeration: true,
|
|
55
|
+
})
|
|
56
|
+
expect(provider.supportsInputModeration).toBe(true)
|
|
57
|
+
expect(provider.mapEndUserIdentifier?.('abc123')).toEqual({ contract: { user_id: 'abc123' } })
|
|
58
|
+
})
|
|
59
|
+
})
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
import { computeEndUserIdentifier, deriveAiSafetyIdentifierSecret } from '../safety-identifier'
|
|
2
|
+
|
|
3
|
+
const BASE_SECRET = 'unit-test-base-secret'
|
|
4
|
+
const HEX_64 = /^[0-9a-f]{64}$/
|
|
5
|
+
|
|
6
|
+
describe('safety-identifier', () => {
|
|
7
|
+
describe('deriveAiSafetyIdentifierSecret', () => {
|
|
8
|
+
it('is deterministic and memoized for a given base secret', () => {
|
|
9
|
+
const first = deriveAiSafetyIdentifierSecret(BASE_SECRET)
|
|
10
|
+
const second = deriveAiSafetyIdentifierSecret(BASE_SECRET)
|
|
11
|
+
expect(first).toBe(second)
|
|
12
|
+
expect(first).toMatch(HEX_64)
|
|
13
|
+
})
|
|
14
|
+
|
|
15
|
+
it('produces a different key for a different base secret', () => {
|
|
16
|
+
expect(deriveAiSafetyIdentifierSecret(BASE_SECRET)).not.toBe(
|
|
17
|
+
deriveAiSafetyIdentifierSecret('other-base-secret'),
|
|
18
|
+
)
|
|
19
|
+
})
|
|
20
|
+
|
|
21
|
+
it('throws when no base secret is available', () => {
|
|
22
|
+
const previous = process.env.JWT_SECRET
|
|
23
|
+
delete process.env.JWT_SECRET
|
|
24
|
+
try {
|
|
25
|
+
expect(() => deriveAiSafetyIdentifierSecret()).toThrow(/JWT_SECRET/)
|
|
26
|
+
} finally {
|
|
27
|
+
if (previous !== undefined) process.env.JWT_SECRET = previous
|
|
28
|
+
}
|
|
29
|
+
})
|
|
30
|
+
})
|
|
31
|
+
|
|
32
|
+
describe('computeEndUserIdentifier', () => {
|
|
33
|
+
it('is stable for the same (tenant, user) pair', () => {
|
|
34
|
+
const a = computeEndUserIdentifier('tenant-1', 'user-1', { baseSecret: BASE_SECRET })
|
|
35
|
+
const b = computeEndUserIdentifier('tenant-1', 'user-1', { baseSecret: BASE_SECRET })
|
|
36
|
+
expect(a).toBe(b)
|
|
37
|
+
expect(a).toMatch(HEX_64)
|
|
38
|
+
})
|
|
39
|
+
|
|
40
|
+
it('separates the same user across tenants (tenant-salted)', () => {
|
|
41
|
+
const t1 = computeEndUserIdentifier('tenant-1', 'user-1', { baseSecret: BASE_SECRET })
|
|
42
|
+
const t2 = computeEndUserIdentifier('tenant-2', 'user-1', { baseSecret: BASE_SECRET })
|
|
43
|
+
expect(t1).not.toBe(t2)
|
|
44
|
+
})
|
|
45
|
+
|
|
46
|
+
it('separates different users within the same tenant', () => {
|
|
47
|
+
const u1 = computeEndUserIdentifier('tenant-1', 'user-1', { baseSecret: BASE_SECRET })
|
|
48
|
+
const u2 = computeEndUserIdentifier('tenant-1', 'user-2', { baseSecret: BASE_SECRET })
|
|
49
|
+
expect(u1).not.toBe(u2)
|
|
50
|
+
})
|
|
51
|
+
|
|
52
|
+
it('never leaks the raw tenant or user id', () => {
|
|
53
|
+
const id = computeEndUserIdentifier('tenant-1', 'user-1', { baseSecret: BASE_SECRET })
|
|
54
|
+
expect(id).not.toContain('tenant-1')
|
|
55
|
+
expect(id).not.toContain('user-1')
|
|
56
|
+
})
|
|
57
|
+
|
|
58
|
+
it('treats a null tenant as an empty salt without throwing', () => {
|
|
59
|
+
const withNull = computeEndUserIdentifier(null, 'user-1', { baseSecret: BASE_SECRET })
|
|
60
|
+
const withEmpty = computeEndUserIdentifier('', 'user-1', { baseSecret: BASE_SECRET })
|
|
61
|
+
expect(withNull).toMatch(HEX_64)
|
|
62
|
+
expect(withNull).toBe(withEmpty)
|
|
63
|
+
})
|
|
64
|
+
|
|
65
|
+
it('throws when userId is empty', () => {
|
|
66
|
+
expect(() => computeEndUserIdentifier('tenant-1', ' ', { baseSecret: BASE_SECRET })).toThrow(
|
|
67
|
+
/userId/,
|
|
68
|
+
)
|
|
69
|
+
})
|
|
70
|
+
})
|
|
71
|
+
})
|
|
@@ -62,6 +62,16 @@ export interface LlmCreateModelOptions {
|
|
|
62
62
|
* proxy); Google honors it when the SDK supports it (@ai-sdk/google ≥3.0).
|
|
63
63
|
*/
|
|
64
64
|
baseURL?: string
|
|
65
|
+
/**
|
|
66
|
+
* Optional opaque, non-reversible end-user identifier attached to the model
|
|
67
|
+
* call so provider-side abuse enforcement can target a single end user
|
|
68
|
+
* instead of the whole API-key organization. The runtime computes this as a
|
|
69
|
+
* tenant-salted HMAC (no PII leaves the platform); the adapter decides how to
|
|
70
|
+
* map it into per-call `providerOptions` via
|
|
71
|
+
* {@link LlmProvider.mapEndUserIdentifier}. Adapters without a mapping ignore
|
|
72
|
+
* it. Always optional — absent identifiers reproduce today's behavior.
|
|
73
|
+
*/
|
|
74
|
+
endUserIdentifier?: string
|
|
65
75
|
}
|
|
66
76
|
|
|
67
77
|
/**
|
|
@@ -146,4 +156,27 @@ export interface LlmProvider {
|
|
|
146
156
|
* behavior at `packages/ai-assistant/src/modules/ai_assistant/api/route/route.ts`.
|
|
147
157
|
*/
|
|
148
158
|
createModel(options: LlmCreateModelOptions): unknown
|
|
159
|
+
|
|
160
|
+
/**
|
|
161
|
+
* Optional. Maps a runtime-computed end-user identifier (see
|
|
162
|
+
* {@link LlmCreateModelOptions.endUserIdentifier}) into the AI SDK
|
|
163
|
+
* `providerOptions` fragment this provider understands — e.g. OpenAI returns
|
|
164
|
+
* `{ openai: { safetyIdentifier } }`, Anthropic returns
|
|
165
|
+
* `{ anthropic: { metadata: { userId } } }`. Keys MUST be the AI SDK
|
|
166
|
+
* provider-option names (camelCase); the SDK translates them to the
|
|
167
|
+
* provider's request-body fields and strips unknown keys. The runtime merges
|
|
168
|
+
* the returned fragment into the per-call `providerOptions`. Adapters that
|
|
169
|
+
* omit this method send no identifier (today's behavior). Implementations
|
|
170
|
+
* MUST be pure and stateless.
|
|
171
|
+
*/
|
|
172
|
+
mapEndUserIdentifier?(identifier: string): Record<string, unknown>
|
|
173
|
+
|
|
174
|
+
/**
|
|
175
|
+
* Optional. When `true`, the runtime may run input pre-moderation through
|
|
176
|
+
* this provider's moderation endpoint before the model call. Only providers
|
|
177
|
+
* that actually expose a moderation API (initially the OpenAI adapter) set
|
|
178
|
+
* this. Absent/`false` means the moderation gate is skipped for this provider
|
|
179
|
+
* and the surface relies on the provider's own server-side filtering.
|
|
180
|
+
*/
|
|
181
|
+
readonly supportsInputModeration?: boolean
|
|
149
182
|
}
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* End-user safety identifiers for AI provider calls.
|
|
3
|
+
*
|
|
4
|
+
* Providers such as OpenAI let developers attach an opaque per-end-user
|
|
5
|
+
* identifier to each request so abuse enforcement can target one user instead
|
|
6
|
+
* of suspending the whole API-key organization. We never send a reversible id:
|
|
7
|
+
* the value is a tenant-salted HMAC computed from the platform's existing auth
|
|
8
|
+
* secret, so no PII or internal id leaves the platform and the same end user in
|
|
9
|
+
* two tenants produces two unrelated hashes.
|
|
10
|
+
*
|
|
11
|
+
* The per-process secret derivation mirrors `deriveJwtAudienceSecret`
|
|
12
|
+
* (`@open-mercato/shared/lib/auth/jwt`): one HMAC from the base `JWT_SECRET`
|
|
13
|
+
* under a versioned purpose label, memoized for the process lifetime. No new
|
|
14
|
+
* secret to provision.
|
|
15
|
+
*
|
|
16
|
+
* @see .ai/specs/2026-06-04-ai-input-moderation-and-safety-identifiers.md
|
|
17
|
+
*/
|
|
18
|
+
|
|
19
|
+
import crypto from 'node:crypto'
|
|
20
|
+
|
|
21
|
+
const SAFETY_IDENTIFIER_SECRET_LABEL = 'open-mercato:ai-safety-identifier:v1'
|
|
22
|
+
|
|
23
|
+
const derivedSecretCache = new Map<string, string>()
|
|
24
|
+
|
|
25
|
+
function readBaseSecret(explicit?: string): string {
|
|
26
|
+
const secret = explicit ?? process.env.JWT_SECRET
|
|
27
|
+
if (!secret) {
|
|
28
|
+
throw new Error('[internal] JWT_SECRET is not set; cannot derive AI safety-identifier secret')
|
|
29
|
+
}
|
|
30
|
+
return secret
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* Derive the per-process safety-identifier HMAC key from the base auth secret.
|
|
35
|
+
*
|
|
36
|
+
* Deterministic HMAC-SHA256 of a versioned purpose label keyed by the base
|
|
37
|
+
* secret, memoized per base secret. Rotating the base secret rotates every
|
|
38
|
+
* derived identifier — documented as accepted (identifiers are advisory
|
|
39
|
+
* provider-side metadata, not an in-platform security control).
|
|
40
|
+
*/
|
|
41
|
+
export function deriveAiSafetyIdentifierSecret(baseSecret?: string): string {
|
|
42
|
+
const base = readBaseSecret(baseSecret)
|
|
43
|
+
const cached = derivedSecretCache.get(base)
|
|
44
|
+
if (cached !== undefined) return cached
|
|
45
|
+
const derived = crypto
|
|
46
|
+
.createHmac('sha256', base)
|
|
47
|
+
.update(SAFETY_IDENTIFIER_SECRET_LABEL)
|
|
48
|
+
.digest('hex')
|
|
49
|
+
derivedSecretCache.set(base, derived)
|
|
50
|
+
return derived
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* Compute the opaque end-user safety identifier for a (tenant, user) pair.
|
|
55
|
+
*
|
|
56
|
+
* Returns a 64-char lowercase hex HMAC-SHA256 of `${tenantId}:${userId}` keyed
|
|
57
|
+
* by the derived secret. Throws (with an `[internal]` message) when the base
|
|
58
|
+
* secret is missing or `userId` is empty — callers in the runtime wrap this in
|
|
59
|
+
* a best-effort try/catch so identifier-derivation failures never break chat.
|
|
60
|
+
*/
|
|
61
|
+
export function computeEndUserIdentifier(
|
|
62
|
+
tenantId: string | null | undefined,
|
|
63
|
+
userId: string,
|
|
64
|
+
options?: { baseSecret?: string },
|
|
65
|
+
): string {
|
|
66
|
+
const normalizedUser = (userId ?? '').trim()
|
|
67
|
+
if (!normalizedUser) {
|
|
68
|
+
throw new Error('[internal] computeEndUserIdentifier requires a non-empty userId')
|
|
69
|
+
}
|
|
70
|
+
const key = deriveAiSafetyIdentifierSecret(options?.baseSecret)
|
|
71
|
+
const salt = (tenantId ?? '').trim()
|
|
72
|
+
return crypto.createHmac('sha256', key).update(`${salt}:${normalizedUser}`).digest('hex')
|
|
73
|
+
}
|