@lucern/sdk 1.0.11 → 1.0.13

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.
Files changed (331) hide show
  1. package/CHANGELOG.md +10 -0
  2. package/README.md +24 -27
  3. package/dist/.generated +2 -0
  4. package/dist/accessControl.d.ts +19 -26
  5. package/dist/accessControl.js +195 -1423
  6. package/dist/adminClient.d.ts +52 -59
  7. package/dist/adminClient.js +364 -1142
  8. package/dist/answersClient.d.ts +5 -14
  9. package/dist/answersClient.js +19 -737
  10. package/dist/audience/index.d.ts +18 -18
  11. package/dist/audience/index.js +87 -90
  12. package/dist/audiencesClient.d.ts +19 -27
  13. package/dist/audiencesClient.js +107 -868
  14. package/dist/auditClient.d.ts +8 -15
  15. package/dist/auditClient.js +18 -791
  16. package/dist/authContext.d.ts +11 -16
  17. package/dist/authContext.js +122 -154
  18. package/dist/authDeviceClient.d.ts +8 -17
  19. package/dist/authDeviceClient.js +113 -102
  20. package/dist/beliefs/index.d.ts +16 -67
  21. package/dist/beliefs/index.js +20 -10181
  22. package/dist/beliefs/lifecycle.d.ts +10 -11
  23. package/dist/beliefs/lifecycle.js +78 -80
  24. package/dist/beliefsClient.d.ts +30 -35
  25. package/dist/beliefsClient.js +238 -994
  26. package/dist/boundaryClientSurface.d.ts +11 -16
  27. package/dist/boundaryClientSurface.js +49 -68
  28. package/dist/client.d.ts +82 -113
  29. package/dist/client.js +232 -10155
  30. package/dist/clientAssemblyTypes.d.ts +3 -3
  31. package/dist/clientAssemblyTypes.js +1 -2
  32. package/dist/clientConfig.d.ts +45 -59
  33. package/dist/clientConfig.js +1 -2
  34. package/dist/clientEvidenceCompat.d.ts +24 -14
  35. package/dist/clientEvidenceCompat.js +56 -64
  36. package/dist/clientGraphNamespaces.d.ts +3 -5
  37. package/dist/clientGraphNamespaces.js +170 -245
  38. package/dist/clientHelpers.d.ts +20 -25
  39. package/dist/clientHelpers.js +104 -127
  40. package/dist/clientKnowledgeNamespaces.d.ts +24 -54
  41. package/dist/clientKnowledgeNamespaces.js +506 -506
  42. package/dist/clientLocalHelpers.d.ts +11 -56
  43. package/dist/clientLocalHelpers.js +503 -732
  44. package/dist/clientPlatformNamespaces.d.ts +5 -53
  45. package/dist/clientPlatformNamespaces.js +229 -323
  46. package/dist/clientRuntime.d.ts +5 -53
  47. package/dist/clientRuntime.js +26 -30
  48. package/dist/clientWorkflowNamespaces.d.ts +6 -15
  49. package/dist/clientWorkflowNamespaces.js +529 -596
  50. package/dist/contextClient.d.ts +9 -17
  51. package/dist/contextClient.js +92 -805
  52. package/dist/contextFacade.d.ts +11 -2
  53. package/dist/contextFacade.js +10 -81
  54. package/dist/contextPackCompiler.d.ts +10 -11
  55. package/dist/contextPackCompiler.js +494 -1040
  56. package/dist/contextPackPolicy.d.ts +14 -15
  57. package/dist/contextPackPolicy.js +227 -305
  58. package/dist/contextPackSchema.d.ts +3 -3
  59. package/dist/contextPackSchema.js +169 -176
  60. package/dist/contextTypes.d.ts +14 -15
  61. package/dist/contextTypes.js +1 -2
  62. package/dist/contracts/api-enums.contract.d.ts +29 -30
  63. package/dist/contracts/api-enums.contract.js +162 -88
  64. package/dist/contracts/auth-session.contract.d.ts +13 -14
  65. package/dist/contracts/auth-session.contract.js +55 -52
  66. package/dist/contracts/context-pack.contract.d.ts +54 -55
  67. package/dist/contracts/context-pack.contract.js +160 -88
  68. package/dist/contracts/contextPack.d.ts +2 -1
  69. package/dist/contracts/contextPack.js +1 -97
  70. package/dist/contracts/index.d.ts +11 -12
  71. package/dist/contracts/index.js +10 -854
  72. package/dist/contracts/lens-filter.contract.d.ts +9 -10
  73. package/dist/contracts/lens-filter.contract.js +82 -58
  74. package/dist/contracts/lens-workflow.contract.d.ts +21 -23
  75. package/dist/contracts/lens-workflow.contract.js +48 -117
  76. package/dist/contracts/lensFilter.d.ts +2 -1
  77. package/dist/contracts/lensFilter.js +1 -71
  78. package/dist/contracts/lensWorkflow.d.ts +2 -2
  79. package/dist/contracts/lensWorkflow.js +1 -123
  80. package/dist/contracts/mcpTools.d.ts +16 -18
  81. package/dist/contracts/mcpTools.js +89 -123
  82. package/dist/contracts/prompt.contract.d.ts +4 -5
  83. package/dist/contracts/prompt.contract.js +23 -10
  84. package/dist/contracts/prompt.d.ts +2 -1
  85. package/dist/contracts/prompt.js +1 -11
  86. package/dist/contracts/sdk-tools.contract.d.ts +2 -1
  87. package/dist/contracts/sdk-tools.contract.js +1 -2
  88. package/dist/contracts/sdkTools.d.ts +2 -1
  89. package/dist/contracts/sdkTools.js +1 -26
  90. package/dist/contracts/tool-contracts.d.ts +2 -1
  91. package/dist/contracts/tool-contracts.js +1 -2
  92. package/dist/contracts/workflow-runtime.contract.d.ts +45 -46
  93. package/dist/contracts/workflow-runtime.contract.js +241 -228
  94. package/dist/contracts/workflowRuntime.d.ts +2 -1
  95. package/dist/contracts/workflowRuntime.js +1 -244
  96. package/dist/contradictions/index.d.ts +8 -60
  97. package/dist/contradictions/index.js +11 -10175
  98. package/dist/control-plane.d.ts +17 -24
  99. package/dist/control-plane.js +124 -840
  100. package/dist/controlObjectOwnership.d.ts +19 -20
  101. package/dist/controlObjectOwnership.js +207 -201
  102. package/dist/coreClient.d.ts +23 -28
  103. package/dist/coreClient.js +567 -692
  104. package/dist/customTools.d.ts +17 -21
  105. package/dist/customTools.js +221 -221
  106. package/dist/decisions/index.d.ts +7 -58
  107. package/dist/decisions/index.js +14 -10177
  108. package/dist/decisionsClient.d.ts +25 -32
  109. package/dist/decisionsClient.js +113 -913
  110. package/dist/domainContext.d.ts +2 -1
  111. package/dist/domainContext.js +1 -2
  112. package/dist/edges/index.d.ts +21 -73
  113. package/dist/edges/index.js +12 -10176
  114. package/dist/embeddingsClient.d.ts +22 -30
  115. package/dist/embeddingsClient.js +73 -922
  116. package/dist/eventingClient.d.ts +23 -31
  117. package/dist/eventingClient.js +89 -918
  118. package/dist/events.d.ts +48 -49
  119. package/dist/events.js +257 -241
  120. package/dist/eventsCore.d.ts +20 -29
  121. package/dist/eventsCore.js +86 -830
  122. package/dist/evidence/index.d.ts +42 -61
  123. package/dist/evidence/index.js +13 -10176
  124. package/dist/evidenceClient.d.ts +13 -22
  125. package/dist/evidenceClient.js +34 -751
  126. package/dist/facade/context.d.ts +7 -8
  127. package/dist/facade/context.js +73 -72
  128. package/dist/functionSurface.d.ts +2 -156
  129. package/dist/functionSurface.js +1 -1460
  130. package/dist/functionSurfaceClient.d.ts +2 -9
  131. package/dist/functionSurfaceClient.js +1 -1460
  132. package/dist/gatewayFacades.d.ts +93 -296
  133. package/dist/gatewayFacades.factories.d.ts +209 -14
  134. package/dist/gatewayFacades.factories.js +545 -2228
  135. package/dist/gatewayFacades.js +284 -2627
  136. package/dist/generated/functionSurface.d.ts +149 -0
  137. package/dist/generated/functionSurface.js +749 -0
  138. package/dist/graphAnalysisClient.d.ts +41 -49
  139. package/dist/graphAnalysisClient.js +185 -974
  140. package/dist/graphClient.d.ts +53 -60
  141. package/dist/graphClient.js +219 -1090
  142. package/dist/graphIntel.d.ts +2 -4
  143. package/dist/graphIntel.js +1 -2
  144. package/dist/graphIntelligence.d.ts +4 -2
  145. package/dist/graphIntelligence.js +2 -46
  146. package/dist/graphRecommendationsClient.d.ts +15 -23
  147. package/dist/graphRecommendationsClient.js +70 -849
  148. package/dist/graphStateClassifierClient.d.ts +17 -25
  149. package/dist/graphStateClassifierClient.js +67 -908
  150. package/dist/harnessClient.d.ts +40 -47
  151. package/dist/harnessClient.js +198 -993
  152. package/dist/identityClient.d.ts +25 -33
  153. package/dist/identityClient.js +245 -1186
  154. package/dist/index.d.ts +73 -69
  155. package/dist/index.js +72 -13313
  156. package/dist/infisicalRuntime.d.ts +12 -14
  157. package/dist/infisicalRuntime.js +290 -297
  158. package/dist/jobsClient.d.ts +24 -32
  159. package/dist/jobsClient.js +101 -916
  160. package/dist/learningClient.d.ts +8 -16
  161. package/dist/learningClient.js +45 -809
  162. package/dist/lenses/index.d.ts +13 -65
  163. package/dist/lenses/index.js +11 -10175
  164. package/dist/mcpClient.d.ts +14 -23
  165. package/dist/mcpClient.js +115 -856
  166. package/dist/modelRuntimeClient.d.ts +18 -26
  167. package/dist/modelRuntimeClient.js +74 -894
  168. package/dist/nodes/index.d.ts +7 -58
  169. package/dist/nodes/index.js +14 -10177
  170. package/dist/ontologies/index.d.ts +21 -73
  171. package/dist/ontologies/index.js +14 -10178
  172. package/dist/ontologyClient.d.ts +23 -31
  173. package/dist/ontologyClient.js +138 -924
  174. package/dist/ontologyLinksClient.d.ts +16 -24
  175. package/dist/ontologyLinksClient.js +76 -886
  176. package/dist/opinion.d.ts +5 -6
  177. package/dist/opinion.js +21 -25
  178. package/dist/orgGraphSearchClient.d.ts +19 -27
  179. package/dist/orgGraphSearchClient.js +89 -857
  180. package/dist/packRuntime.d.ts +2 -2
  181. package/dist/packRuntime.js +1 -2
  182. package/dist/packsClient.d.ts +30 -37
  183. package/dist/packsClient.js +131 -906
  184. package/dist/policyClient.d.ts +21 -29
  185. package/dist/policyClient.js +267 -1026
  186. package/dist/proof-attestation.json +1 -1
  187. package/dist/questions/index.d.ts +9 -60
  188. package/dist/questions/index.js +15 -10178
  189. package/dist/realtime/index.d.ts +20 -16
  190. package/dist/realtime/index.js +30 -19
  191. package/dist/realtime/refs.d.ts +4 -6
  192. package/dist/realtime/refs.js +12 -7
  193. package/dist/realtime-refs.d.ts +1 -0
  194. package/dist/realtime-refs.js +1 -0
  195. package/dist/realtime.d.ts +1 -0
  196. package/dist/realtime.js +1 -0
  197. package/dist/reportsClient.d.ts +10 -19
  198. package/dist/reportsClient.js +48 -836
  199. package/dist/schemaClient.d.ts +16 -23
  200. package/dist/schemaClient.js +62 -832
  201. package/dist/sdkSurface.d.ts +18 -25
  202. package/dist/sdkSurface.js +135 -106
  203. package/dist/secrets.d.ts +2 -1
  204. package/dist/secrets.js +1 -2
  205. package/dist/sourcesClient.d.ts +11 -18
  206. package/dist/sourcesClient.js +18 -741
  207. package/dist/telemetryClient.d.ts +22 -30
  208. package/dist/telemetryClient.js +107 -931
  209. package/dist/toolRegistryClient.d.ts +27 -35
  210. package/dist/toolRegistryClient.js +116 -954
  211. package/dist/topics/index.d.ts +13 -64
  212. package/dist/topics/index.js +15 -10178
  213. package/dist/topicsClient.d.ts +19 -27
  214. package/dist/topicsClient.js +106 -894
  215. package/dist/types.d.ts +84 -87
  216. package/dist/types.js +1 -2
  217. package/dist/version.d.ts +2 -3
  218. package/dist/version.js +2 -5
  219. package/dist/workflowClient.d.ts +60 -65
  220. package/dist/workflowClient.js +343 -1219
  221. package/dist/worktrees/index.d.ts +16 -68
  222. package/dist/worktrees/index.js +14 -10178
  223. package/package.json +6 -6
  224. package/dist/accessControl.js.map +0 -1
  225. package/dist/adminClient.js.map +0 -1
  226. package/dist/answersClient.js.map +0 -1
  227. package/dist/audience/index.js.map +0 -1
  228. package/dist/audiencesClient.js.map +0 -1
  229. package/dist/auditClient.js.map +0 -1
  230. package/dist/authContext.js.map +0 -1
  231. package/dist/authDeviceClient.js.map +0 -1
  232. package/dist/beliefs/index.js.map +0 -1
  233. package/dist/beliefs/lifecycle.js.map +0 -1
  234. package/dist/beliefsClient.js.map +0 -1
  235. package/dist/boundaryClientSurface.js.map +0 -1
  236. package/dist/client.js.map +0 -1
  237. package/dist/clientAssemblyTypes.js.map +0 -1
  238. package/dist/clientConfig.js.map +0 -1
  239. package/dist/clientEvidenceCompat.js.map +0 -1
  240. package/dist/clientGraphNamespaces.js.map +0 -1
  241. package/dist/clientHelpers.js.map +0 -1
  242. package/dist/clientKnowledgeNamespaces.js.map +0 -1
  243. package/dist/clientLocalHelpers.js.map +0 -1
  244. package/dist/clientPlatformNamespaces.js.map +0 -1
  245. package/dist/clientRuntime.js.map +0 -1
  246. package/dist/clientWorkflowNamespaces.js.map +0 -1
  247. package/dist/contextClient.js.map +0 -1
  248. package/dist/contextFacade.js.map +0 -1
  249. package/dist/contextPackCompiler.js.map +0 -1
  250. package/dist/contextPackPolicy.js.map +0 -1
  251. package/dist/contextPackSchema.js.map +0 -1
  252. package/dist/contextTypes.js.map +0 -1
  253. package/dist/contracts/api-enums.contract.js.map +0 -1
  254. package/dist/contracts/auth-session.contract.js.map +0 -1
  255. package/dist/contracts/context-pack.contract.js.map +0 -1
  256. package/dist/contracts/contextPack.js.map +0 -1
  257. package/dist/contracts/index.js.map +0 -1
  258. package/dist/contracts/lens-filter.contract.js.map +0 -1
  259. package/dist/contracts/lens-workflow.contract.js.map +0 -1
  260. package/dist/contracts/lensFilter.js.map +0 -1
  261. package/dist/contracts/lensWorkflow.js.map +0 -1
  262. package/dist/contracts/mcpTools.js.map +0 -1
  263. package/dist/contracts/prompt.contract.js.map +0 -1
  264. package/dist/contracts/prompt.js.map +0 -1
  265. package/dist/contracts/sdk-tools.contract.js.map +0 -1
  266. package/dist/contracts/sdkTools.js.map +0 -1
  267. package/dist/contracts/tool-contracts.js.map +0 -1
  268. package/dist/contracts/workflow-runtime.contract.js.map +0 -1
  269. package/dist/contracts/workflowRuntime.js.map +0 -1
  270. package/dist/contradictions/index.js.map +0 -1
  271. package/dist/control-plane.js.map +0 -1
  272. package/dist/controlObjectOwnership.js.map +0 -1
  273. package/dist/coreClient.js.map +0 -1
  274. package/dist/customTools.js.map +0 -1
  275. package/dist/decisions/index.js.map +0 -1
  276. package/dist/decisionsClient.js.map +0 -1
  277. package/dist/domainContext.js.map +0 -1
  278. package/dist/edges/index.js.map +0 -1
  279. package/dist/embeddingsClient.js.map +0 -1
  280. package/dist/eventingClient.js.map +0 -1
  281. package/dist/events.js.map +0 -1
  282. package/dist/eventsCore.js.map +0 -1
  283. package/dist/evidence/index.js.map +0 -1
  284. package/dist/evidenceClient.js.map +0 -1
  285. package/dist/facade/context.js.map +0 -1
  286. package/dist/functionSurface.js.map +0 -1
  287. package/dist/functionSurfaceClient.js.map +0 -1
  288. package/dist/gatewayFacades.factories.js.map +0 -1
  289. package/dist/gatewayFacades.js.map +0 -1
  290. package/dist/graphAnalysisClient.js.map +0 -1
  291. package/dist/graphClient.js.map +0 -1
  292. package/dist/graphIntel.js.map +0 -1
  293. package/dist/graphIntelligence.js.map +0 -1
  294. package/dist/graphRecommendationsClient.js.map +0 -1
  295. package/dist/graphStateClassifierClient.js.map +0 -1
  296. package/dist/harnessClient.js.map +0 -1
  297. package/dist/identityClient.js.map +0 -1
  298. package/dist/index.js.map +0 -1
  299. package/dist/infisicalRuntime.js.map +0 -1
  300. package/dist/jobsClient.js.map +0 -1
  301. package/dist/learningClient.js.map +0 -1
  302. package/dist/lenses/index.js.map +0 -1
  303. package/dist/mcpClient.js.map +0 -1
  304. package/dist/modelRuntimeClient.js.map +0 -1
  305. package/dist/nodes/index.js.map +0 -1
  306. package/dist/ontologies/index.js.map +0 -1
  307. package/dist/ontologyClient.js.map +0 -1
  308. package/dist/ontologyLinksClient.js.map +0 -1
  309. package/dist/opinion.js.map +0 -1
  310. package/dist/orgGraphSearchClient.js.map +0 -1
  311. package/dist/packRuntime.js.map +0 -1
  312. package/dist/packsClient.js.map +0 -1
  313. package/dist/policyClient.js.map +0 -1
  314. package/dist/questions/index.js.map +0 -1
  315. package/dist/realtime/index.js.map +0 -1
  316. package/dist/realtime/refs.js.map +0 -1
  317. package/dist/reportsClient.js.map +0 -1
  318. package/dist/schemaClient.js.map +0 -1
  319. package/dist/sdk-tools.contract-B4c1Zr1o.d.ts +0 -22
  320. package/dist/sdkSurface.js.map +0 -1
  321. package/dist/secrets.js.map +0 -1
  322. package/dist/sourcesClient.js.map +0 -1
  323. package/dist/telemetryClient.js.map +0 -1
  324. package/dist/tool-contracts-BUiL9P6z.d.ts +0 -22
  325. package/dist/toolRegistryClient.js.map +0 -1
  326. package/dist/topics/index.js.map +0 -1
  327. package/dist/topicsClient.js.map +0 -1
  328. package/dist/types.js.map +0 -1
  329. package/dist/version.js.map +0 -1
  330. package/dist/workflowClient.js.map +0 -1
  331. package/dist/worktrees/index.js.map +0 -1
@@ -1,1463 +1,235 @@
1
- import { createTelemetryExporterFromEnv, emitTelemetrySignal } from '@lucern/transport-core';
2
- import { redactDiagnosticValue } from '@lucern/transport-core/redaction';
3
- import { classifyRetry } from '@lucern/transport-core/transport';
4
- import { Effect, Exit, Cause } from 'effect';
5
-
6
- // src/authContext.ts
7
- var LucernSdkAuthContextError = class extends Error {
8
- reason;
9
- constructor(reason, message) {
10
- super(message);
11
- this.name = "LucernSdkAuthContextError";
12
- this.reason = reason;
13
- }
14
- };
1
+ import { LucernSdkAuthContextError, normalizeCanonicalLucernAuthContext, } from "./authContext.js";
2
+ import { createIdentityClient, } from "./identityClient.js";
3
+ export class LucernAccessControlError extends LucernSdkAuthContextError {
4
+ policyDecision;
5
+ constructor(reason, message, policyDecision) {
6
+ super(reason, message);
7
+ this.name = "LucernAccessControlError";
8
+ this.policyDecision = policyDecision;
9
+ }
10
+ }
15
11
  function cleanString(value) {
16
- const normalized = value?.trim();
17
- return normalized ? normalized : void 0;
12
+ const normalized = value?.trim();
13
+ return normalized ? normalized : undefined;
18
14
  }
19
15
  function cleanStringList(values) {
20
- if (!values) {
21
- return [];
22
- }
23
- return values.map((value) => value.trim()).filter(
24
- (value, index, list) => value.length > 0 && list.indexOf(value) === index
25
- );
16
+ if (!values) {
17
+ return [];
18
+ }
19
+ return [
20
+ ...new Set(values.map((value) => value.trim()).filter((value) => value.length > 0)),
21
+ ];
26
22
  }
27
23
  function requireString(value, reason, label) {
28
- const normalized = cleanString(value);
29
- if (!normalized) {
30
- throw new LucernSdkAuthContextError(
31
- reason,
32
- `Canonical Lucern SDK auth context is missing ${label}.`
33
- );
34
- }
35
- return normalized;
36
- }
37
- function requirePrincipalType(principalType2) {
38
- if (!principalType2) {
39
- throw new LucernSdkAuthContextError(
40
- "principal_missing",
41
- "Canonical Lucern SDK auth context is missing principalType."
42
- );
43
- }
44
- return principalType2;
45
- }
46
- function requireAuthMode(authMode) {
47
- if (!authMode) {
48
- throw new LucernSdkAuthContextError(
49
- "principal_missing",
50
- "Canonical Lucern SDK auth context is missing authMode."
51
- );
52
- }
53
- return authMode;
54
- }
55
- function ensurePermitMatch(args) {
56
- const actual = cleanString(args.actual);
57
- if (actual && actual !== args.expected) {
58
- throw new LucernSdkAuthContextError(
59
- "policy_denied",
60
- `Canonical Lucern SDK auth context has conflicting Permit ${args.field}.`
61
- );
62
- }
63
- }
64
- function normalizeCanonicalLucernAuthContext(input) {
65
- if (!input) {
66
- throw new LucernSdkAuthContextError(
67
- "principal_missing",
68
- "Canonical Lucern SDK auth context is required."
69
- );
70
- }
71
- if (input.policyDecision === "deny") {
72
- throw new LucernSdkAuthContextError(
73
- "policy_denied",
74
- "Canonical Lucern SDK auth context carries a denied policy decision."
75
- );
76
- }
77
- const principalId = requireString(
78
- input.principalId,
79
- "principal_missing",
80
- "principalId"
81
- );
82
- const tenantId = requireString(input.tenantId, "tenant_missing", "tenantId");
83
- const workspaceId = requireString(
84
- input.workspaceId,
85
- "workspace_missing",
86
- "workspaceId"
87
- );
88
- const roles = cleanStringList(input.roles);
89
- const scopes = cleanStringList(input.scopes);
90
- const principalType2 = requirePrincipalType(input.principalType);
91
- const authMode = requireAuthMode(input.authMode);
92
- const roleBasedInteractiveAuth = authMode === "interactive_user" && roles.length > 0;
93
- if (roles.length === 0 || scopes.length === 0 && !roleBasedInteractiveAuth) {
94
- throw new LucernSdkAuthContextError(
95
- "membership_missing",
96
- "Canonical Lucern SDK auth context requires non-empty roles and scopes."
97
- );
98
- }
99
- const subject = cleanString(input.permit?.subject) ?? principalId;
100
- const tenant = cleanString(input.permit?.tenant) ?? tenantId;
101
- const workspace = cleanString(input.permit?.workspace) ?? workspaceId;
102
- ensurePermitMatch({
103
- field: "subject",
104
- expected: principalId,
105
- actual: subject
106
- });
107
- ensurePermitMatch({ field: "tenant", expected: tenantId, actual: tenant });
108
- ensurePermitMatch({
109
- field: "workspace",
110
- expected: workspaceId,
111
- actual: workspace
112
- });
113
- const context = input.permit?.context ? { ...input.permit.context } : void 0;
114
- return {
115
- clerkId: cleanString(input.clerkId),
116
- principalId,
117
- tenantId,
118
- workspaceId,
119
- principalType: principalType2,
120
- authMode,
121
- roles,
122
- scopes,
123
- delegationChain: input.delegationChain ? [...input.delegationChain] : [],
124
- policyTraceId: cleanString(input.policyTraceId),
125
- correlationId: cleanString(input.correlationId),
126
- membershipId: cleanString(input.membershipId),
127
- permit: {
128
- subject,
129
- tenant,
130
- workspace,
131
- resource: cleanString(input.permit?.resource),
132
- action: cleanString(input.permit?.action),
133
- relation: cleanString(input.permit?.relation),
134
- context
24
+ const normalized = cleanString(value);
25
+ if (!normalized) {
26
+ throw new LucernAccessControlError(reason, `Lucern SDK access control requires ${label}.`);
135
27
  }
136
- };
137
- }
138
- function createCanonicalAuthHeaders(authContext) {
139
- const headers = {
140
- "x-lucern-principal-id": authContext.principalId,
141
- "x-lucern-principal-type": authContext.principalType,
142
- "x-lucern-tenant": authContext.tenantId,
143
- "x-lucern-tenant-id": authContext.tenantId,
144
- "x-lucern-workspace": authContext.workspaceId,
145
- "x-lucern-workspace-id": authContext.workspaceId,
146
- "x-lucern-auth-mode": authContext.authMode,
147
- "x-lucern-roles": authContext.roles.join(","),
148
- "x-lucern-scopes": authContext.scopes.join(","),
149
- "x-lucern-permit-context": JSON.stringify(authContext.permit)
150
- };
151
- if (authContext.clerkId) {
152
- headers["x-lucern-clerk-id"] = authContext.clerkId;
153
- headers["x-lucern-user-id"] = authContext.clerkId;
154
- }
155
- if (authContext.delegationChain.length > 0) {
156
- headers["x-lucern-delegation-chain"] = JSON.stringify(
157
- authContext.delegationChain
158
- );
159
- }
160
- if (authContext.policyTraceId) {
161
- headers["x-lucern-policy-trace-id"] = authContext.policyTraceId;
162
- }
163
- if (authContext.correlationId) {
164
- headers["x-correlation-id"] = authContext.correlationId;
165
- headers["x-lucern-correlation-id"] = authContext.correlationId;
166
- }
167
- if (authContext.membershipId) {
168
- headers["x-lucern-membership-id"] = authContext.membershipId;
169
- }
170
- return headers;
28
+ return normalized;
171
29
  }
172
- var DEFAULT_GATEWAY_TIMEOUT_MS = 15e3;
173
- var DEFAULT_GATEWAY_MAX_RETRIES = 2;
174
- var DEFAULT_ENV_TIMEOUT_MS = "LUCERN_REQUEST_TIMEOUT_MS";
175
- var DEFAULT_ENV_MAX_RETRIES = "LUCERN_GATEWAY_MAX_RETRIES";
176
- var ENV_TIMEOUT_BY_METHOD_PREFIX = "LUCERN_REQUEST_TIMEOUT_MS_";
177
- var GatewayTimeoutError = class extends Error {
178
- retryable = true;
179
- timeoutMs;
180
- constructor(timeoutMs) {
181
- super(`Request timed out after ${timeoutMs}ms`);
182
- this.name = "AbortError";
183
- this.timeoutMs = timeoutMs;
184
- }
185
- };
186
- var GatewayTransportError = class extends Error {
187
- retryable;
188
- cause;
189
- constructor(message, options) {
190
- super(message);
191
- this.name = "GatewayTransportError";
192
- this.retryable = options?.retryable ?? true;
193
- this.cause = options?.cause;
194
- }
195
- };
196
- function isGatewayRetryableError(error) {
197
- return error instanceof GatewayTimeoutError && error.retryable || error instanceof GatewayTransportError && error.retryable || false;
198
- }
199
- var LucernApiError = class extends Error {
200
- code;
201
- status;
202
- invariant;
203
- suggestion;
204
- details;
205
- requestId;
206
- correlationId;
207
- policyTraceId;
208
- constructor(args) {
209
- super(args.message);
210
- this.name = "LucernApiError";
211
- this.code = args.code;
212
- this.status = args.status;
213
- this.invariant = args.invariant;
214
- this.suggestion = args.suggestion;
215
- this.details = args.details;
216
- this.requestId = args.requestId;
217
- this.correlationId = args.correlationId;
218
- this.policyTraceId = args.policyTraceId;
219
- }
220
- };
221
- function toQueryString(scope) {
222
- const params = new URLSearchParams();
223
- if (scope.tenantId) {
224
- params.set("tenantId", scope.tenantId);
225
- }
226
- if (scope.workspaceId) {
227
- params.set("workspaceId", scope.workspaceId);
228
- }
229
- for (const [key, value] of Object.entries(scope)) {
230
- if (key === "tenantId" || key === "workspaceId") {
231
- continue;
30
+ function normalizePrincipalType(principalType) {
31
+ if (principalType === "agent") {
32
+ return "agent";
232
33
  }
233
- if (value === void 0) {
234
- continue;
34
+ if (principalType === "service") {
35
+ return "service";
235
36
  }
236
- params.set(key, String(value));
237
- }
238
- const serialized = params.toString();
239
- return serialized.length > 0 ? `?${serialized}` : "";
240
- }
241
- function fillRandomBytes(length) {
242
- const bytes = new Uint8Array(length);
243
- if (typeof globalThis.crypto?.getRandomValues === "function") {
244
- globalThis.crypto.getRandomValues(bytes);
245
- return bytes;
246
- }
247
- for (let index = 0; index < length; index += 1) {
248
- bytes[index] = Math.floor(Math.random() * 256);
249
- }
250
- return bytes;
251
- }
252
- function generatePortableRequestId() {
253
- if (typeof globalThis.crypto?.randomUUID === "function") {
254
- return globalThis.crypto.randomUUID();
255
- }
256
- const bytes = fillRandomBytes(16);
257
- bytes[6] = bytes[6] & 15 | 64;
258
- bytes[8] = bytes[8] & 63 | 128;
259
- const hex = Array.from(bytes, (value) => value.toString(16).padStart(2, "0"));
260
- return `${hex.slice(0, 4).join("")}-${hex.slice(4, 6).join("")}-${hex.slice(
261
- 6,
262
- 8
263
- ).join("")}-${hex.slice(8, 10).join("")}-${hex.slice(10).join("")}`;
264
- }
265
- function resolveEnvironment() {
266
- const processEnv = typeof globalThis === "object" && globalThis !== null && "process" in globalThis ? globalThis.process : void 0;
267
- const env = processEnv !== void 0 && typeof processEnv === "object" && processEnv !== null && typeof processEnv.env === "object" ? processEnv.env : void 0;
268
- return {
269
- get: (name) => {
270
- const value = env?.[name];
271
- return typeof value === "string" && value.length > 0 ? value : void 0;
272
- }
273
- };
274
- }
275
- function telemetryEnvironmentRecord(environment) {
276
- const names = [
277
- "LUCERN_TELEMETRY_ENABLED",
278
- "AXIOM_TELEMETRY_ENABLED",
279
- "LUCERN_AXIOM_TOKEN",
280
- "AXIOM_TOKEN",
281
- "LUCERN_AXIOM_EVENTS_DATASET",
282
- "LUCERN_AXIOM_DATASET",
283
- "AXIOM_EVENTS_DATASET",
284
- "AXIOM_DATASET",
285
- "LUCERN_AXIOM_API_URL",
286
- "AXIOM_URL",
287
- "LUCERN_ENVIRONMENT",
288
- "NODE_ENV",
289
- "LUCERN_RELEASE",
290
- "SENTRY_RELEASE",
291
- "VERCEL_GIT_COMMIT_SHA"
292
- ];
293
- return Object.fromEntries(
294
- names.map((name) => [name, environment.get(name)])
295
- );
296
- }
297
- function resolveRequestProfile(config, environment) {
298
- const requestIdFactory = config.requestIdFactory ?? (() => generatePortableRequestId());
299
- const parsedMaxRetries = parseIntegerFromString(
300
- config.maxRetries,
301
- environment.get(DEFAULT_ENV_MAX_RETRIES)
302
- );
303
- const parsedTimeoutMs = parseIntegerFromString(
304
- config.timeoutMs,
305
- environment.get(DEFAULT_ENV_TIMEOUT_MS)
306
- );
307
- const methodTimeouts = {
308
- ...config.timeoutMsByMethod
309
- };
310
- for (const method of ["GET", "POST", "PUT", "PATCH", "DELETE"]) {
311
- const envKey = `${ENV_TIMEOUT_BY_METHOD_PREFIX}${method}`;
312
- const raw = environment.get(envKey);
313
- if (!raw || methodTimeouts[method] !== void 0) {
314
- continue;
37
+ if (principalType === "group") {
38
+ return "group";
315
39
  }
316
- const parsed = parseIntegerFromString(void 0, raw);
317
- if (typeof parsed === "number") {
318
- methodTimeouts[method] = parsed;
319
- }
320
- }
321
- return {
322
- maxRetries: parsedMaxRetries ?? DEFAULT_GATEWAY_MAX_RETRIES,
323
- timeoutMs: parsedTimeoutMs ?? DEFAULT_GATEWAY_TIMEOUT_MS,
324
- timeoutMsByMethod: methodTimeouts,
325
- requestIdFactory
326
- };
327
- }
328
- function createGatewayRuntime(config, environment) {
329
- return {
330
- fetch: config.fetchImpl ?? fetch,
331
- now: () => Date.now(),
332
- sleep: (ms) => delay(ms),
333
- env: environment,
334
- redaction: resolveRequestRedactionValue,
335
- profile: resolveRequestProfile(config, environment)
336
- };
337
- }
338
- function parseIntegerFromString(value, rawValue) {
339
- if (typeof value === "number" && Number.isInteger(value) && value >= 0) {
340
- return value;
341
- }
342
- if (typeof rawValue !== "string" || !rawValue.trim()) {
343
- return void 0;
344
- }
345
- const parsed = Number.parseInt(rawValue, 10);
346
- return Number.isInteger(parsed) && parsed >= 0 ? parsed : void 0;
347
- }
348
- function resolveRequestRedactionValue(value) {
349
- return redactDiagnosticValue(value);
350
- }
351
- function resolveGatewayBaseUrl(configBaseUrl, environment) {
352
- const envBaseUrl = environment.get("LUCERN_API_URL") ?? environment.get("LUCERN_BASE_URL") ?? environment.get("LUCERN_GATEWAY_BASE_URL");
353
- return (configBaseUrl ?? envBaseUrl ?? "").replace(/\/+$/, "");
354
- }
355
- function normalizeGatewayEnvironment(value) {
356
- return value === "sandbox" || value === "production" ? value : void 0;
357
- }
358
- var randomIdempotencyKey = generatePortableRequestId;
359
- function fallbackErrorCode(status) {
360
- if (status === 401) {
361
- return "AUTHENTICATION_REQUIRED";
362
- }
363
- if (status === 403) {
364
- return "FORBIDDEN";
365
- }
366
- if (status === 404) {
367
- return "NOT_FOUND";
368
- }
369
- if (status === 408) {
370
- return "UPSTREAM_ERROR";
371
- }
372
- if (status === 409) {
373
- return "CONFLICT";
374
- }
375
- if (status === 429) {
376
- return "RATE_LIMIT_EXCEEDED";
377
- }
378
- if (status >= 500) {
379
- return "UPSTREAM_ERROR";
380
- }
381
- return "INTERNAL_ERROR";
382
- }
383
- function delay(ms) {
384
- return new Promise((resolve) => setTimeout(resolve, ms));
385
- }
386
- function computeRetryDelayMs(args) {
387
- const baseDelay = args.status === 429 ? Math.max(
388
- args.retryAfterMs ?? 0,
389
- Math.min(1e3 * 2 ** args.attempt, 1e4)
390
- ) : Math.min(1e3 * 2 ** args.attempt, 4e3);
391
- if (args.status !== 429) {
392
- return baseDelay;
393
- }
394
- const jitterWindow = Math.max(250, Math.round(baseDelay * 0.25));
395
- return baseDelay + Math.round(Math.random() * jitterWindow);
396
- }
397
- function classifyGatewayErrorForRetry(error) {
398
- return isGatewayRetryableError(error) || classifyRetry({ error }).retryable;
399
- }
400
- function isRecord(value) {
401
- return value !== null && typeof value === "object" && !Array.isArray(value);
402
- }
403
- function readPolicySummaryFromDetails(details) {
404
- if (!isRecord(details)) {
405
- return null;
406
- }
407
- const directSummary = details.summary;
408
- if (typeof directSummary === "string" && directSummary.trim().length > 0) {
409
- return directSummary.trim();
410
- }
411
- const policy = details.policy;
412
- if (!isRecord(policy)) {
413
- return null;
414
- }
415
- const explanation = policy.explanation;
416
- if (!isRecord(explanation)) {
417
- return null;
418
- }
419
- const nestedSummary = explanation.summary;
420
- if (typeof nestedSummary === "string" && nestedSummary.trim().length > 0) {
421
- return nestedSummary.trim();
422
- }
423
- return null;
424
- }
425
- function redactJsonDiagnosticValue(value) {
426
- return value === void 0 ? void 0 : redactDiagnosticValue(value);
427
- }
428
- async function resolveConfiguredAuthContext(authContext) {
429
- if (typeof authContext === "function") {
430
- return await authContext();
431
- }
432
- return authContext;
433
- }
434
- function mergeHeaderRecord(base, addition) {
435
- const headers = new Headers(base);
436
- for (const [key, value] of Object.entries(addition)) {
437
- const existing = headers.get(key);
438
- if (existing !== null && existing !== value) {
439
- throw new LucernSdkAuthContextError(
440
- "policy_denied",
441
- `Canonical Lucern SDK auth context conflicts with existing ${key} header.`
442
- );
40
+ if (principalType === "external_viewer") {
41
+ return "external_viewer";
443
42
  }
444
- headers.set(key, value);
445
- }
446
- return Object.fromEntries(headers.entries());
43
+ return "human";
447
44
  }
448
- function cleanHeaderValue(value) {
449
- const normalized = value?.trim();
450
- return normalized ? normalized : void 0;
45
+ function aliasKey(alias) {
46
+ return `${alias.provider}:${alias.providerProjectId ?? ""}:${alias.externalSubjectId}`;
451
47
  }
452
- function createGatewayRequestClient(config = {}) {
453
- const env = resolveEnvironment();
454
- const runtime = createGatewayRuntime(config, env);
455
- const baseUrl = resolveGatewayBaseUrl(config.baseUrl, env);
456
- const maxRetries = runtime.profile.maxRetries;
457
- const requestIdFactory = runtime.profile.requestIdFactory;
458
- const requestTimeoutByMethod = runtime.profile.timeoutMsByMethod;
459
- const defaultRequestTimeoutMs = runtime.profile.timeoutMs;
460
- const normalizedEnvironment = normalizeGatewayEnvironment(config.environment);
461
- const telemetryExporter = config.telemetryEnabled === false ? null : config.telemetryExporter ?? createTelemetryExporterFromEnv(telemetryEnvironmentRecord(env), {
462
- service: "lucern-sdk",
463
- environment: normalizedEnvironment
464
- });
465
- async function resolveAuthHeaders() {
466
- const provided = config.getAuthHeaders ? await config.getAuthHeaders() : {};
467
- const headers = new Headers(provided);
468
- const setIfAbsent = (name, value) => {
469
- const normalized = cleanHeaderValue(value);
470
- if (normalized && !headers.has(name)) {
471
- headers.set(name, normalized);
472
- }
473
- };
474
- setIfAbsent("x-lucern-key", config.apiKey);
475
- setIfAbsent("x-lucern-session-token", config.userToken);
476
- setIfAbsent("x-lucern-environment", normalizedEnvironment);
477
- setIfAbsent("x-lucern-clerk-id", config.clerkId);
478
- setIfAbsent("x-lucern-user-id", config.userId ?? config.clerkId);
479
- setIfAbsent("x-lucern-deployment-host", config.deploymentHost);
480
- const base = Object.fromEntries(headers.entries());
481
- const authContextInput = await resolveConfiguredAuthContext(
482
- config.authContext
483
- );
484
- if (!authContextInput && !config.requireCanonicalAuthContext) {
485
- return base;
486
- }
487
- const authContext = normalizeCanonicalLucernAuthContext(authContextInput);
488
- return mergeHeaderRecord(base, createCanonicalAuthHeaders(authContext));
489
- }
490
- async function fetchWithTimeout(url, init, timeoutMs) {
491
- const normalizeTransportError = (error, isTimeout) => {
492
- if (isTimeout) {
493
- return new GatewayTimeoutError(timeoutMs);
494
- }
495
- return error instanceof GatewayTimeoutError || error instanceof GatewayTransportError ? error : new GatewayTransportError(
496
- error instanceof Error ? error.message : "Gateway transport error",
497
- {
498
- cause: error,
499
- retryable: classifyGatewayErrorForRetry(error)
500
- }
501
- );
502
- };
503
- const controller = new AbortController();
504
- const timer = setTimeout(() => controller.abort(), timeoutMs);
505
- const requestEffect = Effect.tryPromise({
506
- try: () => runtime.fetch(url, { ...init, signal: controller.signal }),
507
- catch: (error) => normalizeTransportError(error, controller.signal.aborted)
508
- });
509
- try {
510
- const exit = await Effect.runPromiseExit(requestEffect);
511
- if (Exit.isSuccess(exit)) {
512
- return exit.value;
513
- }
514
- const failure = Array.from(Cause.failures(exit.cause))[0];
515
- if (failure !== void 0) {
516
- throw failure;
517
- }
518
- throw Cause.squash(exit.cause);
519
- } finally {
520
- clearTimeout(timer);
521
- }
522
- }
523
- async function emitSdkResponseTelemetry(context) {
524
- const retry = classifyRetry({
525
- status: context.status,
526
- error: context.error,
527
- retryAfter: context.retryAfterMs !== null && context.retryAfterMs !== void 0 ? String(context.retryAfterMs / 1e3) : void 0
528
- });
529
- await emitTelemetrySignal(telemetryExporter, {
530
- signalType: "trace",
531
- surface: "sdk-retry",
532
- eventName: context.willRetry ? "sdk.retry" : context.error ? "sdk.request.error" : "sdk.request.complete",
533
- severity: context.error ? context.willRetry ? "warn" : "error" : "info",
534
- durationMs: context.durationMs,
535
- metricName: "sdk.request.duration_ms",
536
- metricValue: context.durationMs,
537
- correlationId: context.correlationId ?? context.requestId,
538
- policyTraceId: context.policyTraceId ?? null,
539
- tenantId: context.headers.get("x-lucern-tenant-id") ?? context.headers.get("x-lucern-tenant") ?? void 0,
540
- workspaceId: context.headers.get("x-lucern-workspace-id") ?? context.headers.get("x-lucern-workspace") ?? void 0,
541
- attributes: {
542
- service: "lucern-sdk",
543
- operation: "gateway.request",
544
- path: context.path,
545
- httpMethod: context.method,
546
- httpStatus: context.status,
547
- attempt: context.attempt,
548
- maxRetries: context.maxRetries,
549
- retryReason: retry.reason,
550
- retryAfterMs: context.retryAfterMs ?? retry.retryAfterMs,
551
- willRetry: context.willRetry,
552
- retryable: retry.retryable,
553
- errorName: context.error instanceof Error ? context.error.name : void 0,
554
- errorMessage: context.error instanceof Error ? context.error.message : void 0
555
- }
556
- });
557
- }
558
- async function parsePayload(response) {
559
- const text = await response.text();
560
- if (!text) {
561
- return null;
562
- }
563
- const parsed = tryParseGatewayEnvelopeJson(text);
564
- if (!parsed.ok) {
565
- return null;
566
- }
567
- return isRecord(parsed.value) ? parsed.value : null;
568
- }
569
- function resolveTimeoutMs(method, requestTimeoutMs) {
570
- if (typeof requestTimeoutMs === "number") {
571
- return requestTimeoutMs;
572
- }
573
- const methodTimeoutMs = requestTimeoutByMethod?.[method];
574
- if (typeof methodTimeoutMs === "number") {
575
- return methodTimeoutMs;
576
- }
577
- return defaultRequestTimeoutMs;
578
- }
579
- function tryParseGatewayEnvelopeJson(text) {
580
- const trimmed = text.trim();
581
- if (!trimmed.startsWith("{") && !trimmed.startsWith("[")) {
582
- return { ok: false, reason: "non-json" };
583
- }
584
- try {
585
- return { ok: true, value: JSON.parse(trimmed) };
586
- } catch (error) {
587
- if (error instanceof SyntaxError) {
588
- return { ok: false, reason: "invalid-json", error };
589
- }
590
- throw error;
591
- }
592
- }
593
- function buildApiError(args) {
594
- const failure = args.failure;
595
- const legacyError = failure && isRecord(failure.error) ? failure.error : failure?.legacyError;
596
- const correlationId = failure?.correlationId ?? args.response.headers.get("x-lucern-correlation-id")?.trim() ?? args.requestId;
597
- const policyTraceId = failure?.policyTraceId ?? args.response.headers.get("x-lucern-policy-trace-id")?.trim() ?? null;
598
- const details = runtime.redaction(
599
- redactJsonDiagnosticValue(failure?.details ?? legacyError?.details)
600
- );
601
- const policySummary = readPolicySummaryFromDetails(details);
602
- const failureMessage = typeof failure?.error === "string" ? failure.error : legacyError?.message;
603
- return new LucernApiError({
604
- code: failure?.code ?? legacyError?.code ?? fallbackErrorCode(args.response.status),
605
- message: policySummary ?? failureMessage ?? (args.response.ok ? "Platform API returned an invalid success payload." : "Platform API request failed."),
606
- status: args.response.status,
607
- invariant: failure?.invariant,
608
- suggestion: failure?.suggestion,
609
- details,
610
- requestId: args.requestId,
611
- correlationId,
612
- policyTraceId
613
- });
614
- }
615
- async function request(args) {
616
- const authHeaders = await resolveAuthHeaders();
617
- const method = args.method ?? "GET";
618
- const timeoutMs = resolveTimeoutMs(method, args.timeoutMs);
619
- const headers = new Headers({
620
- "content-type": "application/json",
621
- ...authHeaders
622
- });
623
- if (args.idempotencyKey) {
624
- headers.set("idempotency-key", args.idempotencyKey);
625
- }
626
- const requestId = headers.get("x-correlation-id")?.trim() || headers.get("x-request-id")?.trim() || args.requestId || requestIdFactory();
627
- if (!headers.has("x-correlation-id") && !headers.has("x-request-id")) {
628
- headers.set("x-correlation-id", requestId);
629
- }
630
- const url = `${baseUrl}${args.path}`;
631
- const serializedBody = args.body ? JSON.stringify(args.body) : void 0;
632
- const init = {
633
- method,
634
- headers,
635
- body: serializedBody
636
- };
637
- let lastError;
638
- for (let attempt = 0; attempt <= maxRetries; attempt++) {
639
- const hookRequestContext = {
640
- requestId,
641
- attempt,
642
- maxRetries,
643
- method,
644
- path: args.path,
645
- url,
646
- headers: new Headers(headers),
647
- body: serializedBody,
648
- timeoutMs
649
- };
650
- await config.onRequest?.(hookRequestContext);
651
- const startedAt = Date.now();
652
- try {
653
- const response = await fetchWithTimeout(url, init, timeoutMs);
654
- const responseClone = response.clone();
655
- const payload = await parsePayload(response);
656
- const retry = classifyRetry({
657
- status: response.status,
658
- retryAfter: response.headers.get("Retry-After")
659
- });
660
- const retryAfterMs = retry.retryAfterMs ?? null;
661
- if (!response.ok || !payload?.success) {
662
- const failure = payload && !payload.success ? payload : null;
663
- const apiError = buildApiError({
664
- requestId,
665
- response,
666
- failure
667
- });
668
- const willRetry = attempt < maxRetries && retry.retryable;
669
- const responseContext2 = {
670
- ...hookRequestContext,
671
- durationMs: Date.now() - startedAt,
672
- status: response.status,
673
- response: responseClone,
674
- error: apiError,
675
- correlationId: apiError.correlationId ?? requestId,
676
- policyTraceId: apiError.policyTraceId ?? null,
677
- retryAfterMs,
678
- willRetry
679
- };
680
- await config.onResponse?.(responseContext2);
681
- await emitSdkResponseTelemetry(responseContext2);
682
- if (willRetry) {
683
- lastError = apiError;
684
- await delay(
685
- computeRetryDelayMs({
686
- attempt,
687
- status: response.status,
688
- retryAfterMs
689
- })
690
- );
48
+ function normalizeAliases(input, canonicalClerkUserId) {
49
+ const aliases = new Map();
50
+ for (const alias of input ?? []) {
51
+ const externalSubjectId = cleanString(alias.externalSubjectId);
52
+ if (!externalSubjectId) {
691
53
  continue;
692
- }
693
- throw apiError;
694
- }
695
- const successPayload = payload;
696
- const responseContext = {
697
- ...hookRequestContext,
698
- durationMs: Date.now() - startedAt,
699
- status: response.status,
700
- response: responseClone,
701
- correlationId: successPayload.correlationId ?? response.headers.get("x-lucern-correlation-id")?.trim() ?? requestId,
702
- policyTraceId: successPayload.policyTraceId ?? response.headers.get("x-lucern-policy-trace-id")?.trim() ?? null,
703
- idempotentReplay: successPayload.idempotentReplay,
704
- retryAfterMs,
705
- willRetry: false
706
- };
707
- await config.onResponse?.(responseContext);
708
- await emitSdkResponseTelemetry(responseContext);
709
- return successPayload;
710
- } catch (fetchError) {
711
- if (fetchError instanceof LucernApiError) {
712
- throw fetchError;
713
54
  }
714
- const willRetry = attempt < maxRetries && classifyGatewayErrorForRetry(fetchError);
715
- const responseContext = {
716
- ...hookRequestContext,
717
- durationMs: Date.now() - startedAt,
718
- error: fetchError,
719
- correlationId: requestId,
720
- policyTraceId: null,
721
- willRetry
55
+ const normalized = {
56
+ provider: cleanString(alias.provider) ?? "clerk",
57
+ providerProjectId: cleanString(alias.providerProjectId),
58
+ externalSubjectId,
59
+ status: cleanString(alias.status),
722
60
  };
723
- await config.onResponse?.(responseContext);
724
- await emitSdkResponseTelemetry(responseContext);
725
- lastError = fetchError;
726
- if (willRetry) {
727
- await delay(computeRetryDelayMs({ attempt }));
728
- }
729
- }
61
+ aliases.set(aliasKey(normalized), normalized);
730
62
  }
731
- throw lastError instanceof Error ? lastError : new Error("Platform API request failed after retries.");
732
- }
733
- return {
734
- request
735
- };
736
- }
737
-
738
- // src/sdkSurface.ts
739
- function createListResult(items, legacyKey) {
740
- const result = {
741
- items,
742
- total: items.length
743
- };
744
- if (legacyKey) {
745
- return {
746
- ...result,
747
- [legacyKey]: items
748
- };
749
- }
750
- return result;
751
- }
752
- function mapGatewayData(response, mapper) {
753
- return {
754
- ...response,
755
- data: mapper(response.data)
756
- };
757
- }
758
-
759
- // src/boundaryClientSurface.ts
760
- function cleanOptionalString(value) {
761
- const normalized = value?.trim();
762
- return normalized ? normalized : void 0;
763
- }
764
- function isRecord2(value) {
765
- return Boolean(value) && typeof value === "object" && !Array.isArray(value);
766
- }
767
- function cleanRequiredString(value, label) {
768
- const normalized = cleanOptionalString(value);
769
- if (!normalized) {
770
- throw new Error(`${label} is required`);
771
- }
772
- return normalized;
773
- }
774
- function assertKnownKeys(input, allowed, operation) {
775
- const allowedSet = new Set(allowed);
776
- const unknownKeys = Object.keys(input).filter((key) => !allowedSet.has(key));
777
- if (unknownKeys.length > 0) {
778
- throw new Error(
779
- `${operation} received unsupported field(s): ${unknownKeys.join(", ")}`
780
- );
781
- }
782
- }
783
- function knownPayload(input, allowed, operation) {
784
- assertKnownKeys(input, allowed, operation);
785
- return { ...input };
786
- }
787
- function listResultFromEnvelope(data, legacyKey) {
788
- const record = isRecord2(data) ? data : {};
789
- const legacyItems = record[legacyKey];
790
- return createListResult(
791
- Array.isArray(legacyItems) ? legacyItems : Array.isArray(data) ? data : [],
792
- legacyKey
793
- );
794
- }
795
-
796
- // src/control-plane.ts
797
- var LucernControlPlaneIdentityError = class extends Error {
798
- reason;
799
- principalStatus;
800
- tenantStatus;
801
- workspaceStatus;
802
- details;
803
- constructor(failure) {
804
- super(failure.message);
805
- this.name = "LucernControlPlaneIdentityError";
806
- this.reason = failure.reason;
807
- this.principalStatus = failure.principalStatus;
808
- this.tenantStatus = failure.tenantStatus;
809
- this.workspaceStatus = failure.workspaceStatus;
810
- this.details = failure.details;
811
- }
812
- };
813
- function cleanString2(value) {
814
- return typeof value === "string" && value.trim().length > 0 ? value.trim() : void 0;
815
- }
816
- function stringList(value) {
817
- if (!Array.isArray(value)) {
818
- return [];
819
- }
820
- return [
821
- ...new Set(
822
- value.filter((entry) => typeof entry === "string").map((entry) => entry.trim()).filter(Boolean)
823
- )
824
- ];
825
- }
826
- function principalType(value) {
827
- switch (value) {
828
- case "service":
829
- case "service_principal":
830
- return "service";
831
- case "agent":
832
- return "agent";
833
- case "group":
834
- return "group";
835
- case "external_viewer":
836
- case "external_stakeholder":
837
- return "external_viewer";
838
- default:
839
- return "human";
840
- }
841
- }
842
- function adminFlags(roles) {
843
- const normalized = roles.map((role) => role.toLowerCase());
844
- const isPlatformAdmin = normalized.includes("platform_admin");
845
- const isTenantAdmin = isPlatformAdmin || normalized.includes("tenant_admin");
846
- const isWorkspaceAdmin = isTenantAdmin || normalized.includes("workspace_admin") || normalized.includes("workspace_owner");
847
- return { isPlatformAdmin, isTenantAdmin, isWorkspaceAdmin };
848
- }
849
- function normalizeResolvedInteractivePrincipal(payload) {
850
- if ("ok" in payload && payload.ok === false) {
851
- throw new LucernControlPlaneIdentityError(payload);
852
- }
853
- const principalId = cleanString2(payload.principalId);
854
- const clerkId = cleanString2(payload.clerkId);
855
- const tenantId = cleanString2(payload.tenantId);
856
- if (!principalId || !clerkId || !tenantId) {
857
- throw new LucernControlPlaneIdentityError({
858
- ok: false,
859
- reason: "resolver_unavailable",
860
- message: "Control-plane principal resolver returned an incomplete principal context.",
861
- principalStatus: payload.principalStatus ?? "missing",
862
- tenantStatus: payload.tenantStatus,
863
- workspaceStatus: payload.workspaceStatus
864
- });
865
- }
866
- const roles = stringList(payload.roles);
867
- const scopes = stringList(payload.scopes);
868
- const workspaceId = cleanString2(payload.workspaceId) ?? null;
869
- const flags = adminFlags(roles);
870
- return {
871
- principalId,
872
- principalType: principalType(payload.principalType),
873
- clerkId,
874
- tenantId,
875
- workspaceId,
876
- roles,
877
- scopes,
878
- groupIds: stringList(payload.groupIds),
879
- permittedToolNames: stringList(payload.permittedToolNames),
880
- permittedPackKeys: stringList(payload.permittedPackKeys),
881
- principalStatus: cleanString2(payload.principalStatus) ?? "active",
882
- tenantStatus: cleanString2(payload.tenantStatus) ?? "active",
883
- workspaceStatus: cleanString2(payload.workspaceStatus) ?? (workspaceId ? "active" : "none"),
884
- isPlatformAdmin: typeof payload.isPlatformAdmin === "boolean" ? payload.isPlatformAdmin : flags.isPlatformAdmin,
885
- isTenantAdmin: typeof payload.isTenantAdmin === "boolean" ? payload.isTenantAdmin : flags.isTenantAdmin,
886
- isWorkspaceAdmin: typeof payload.isWorkspaceAdmin === "boolean" ? payload.isWorkspaceAdmin : flags.isWorkspaceAdmin,
887
- permit: {
888
- subject: cleanString2(payload.permit?.subject) ?? principalId,
889
- tenant: cleanString2(payload.permit?.tenant) ?? tenantId,
890
- ...workspaceId ? { workspace: cleanString2(payload.permit?.workspace) ?? workspaceId } : {}
891
- },
892
- authMode: "interactive_user",
893
- sessionId: payload.sessionId,
894
- delegatedBy: payload.delegatedBy,
895
- expiresAt: payload.expiresAt
896
- };
897
- }
898
-
899
- // src/identityClient.ts
900
- function createIdentityWhoamiClient(config = {}) {
901
- const gateway = createGatewayRequestClient(config);
902
- return {
903
- async whoami() {
904
- return gateway.request({
905
- path: "/api/platform/v1/identity/whoami"
906
- });
907
- }
908
- };
909
- }
910
- var TENANT_IDENTITY_FIELDS = [
911
- "tenantId",
912
- "workspaceId",
913
- "principalId",
914
- "integrationKey",
915
- "secretRef",
916
- "policySubject",
917
- "policyAction",
918
- "policyResource",
919
- "decision",
920
- "config",
921
- "configKey",
922
- "configValue",
923
- "provider",
924
- "status",
925
- "metadata",
926
- "limit",
927
- "cursor"
928
- ];
929
- function tenantIdentityQuery(input) {
930
- return {
931
- tenantId: cleanRequiredString(input.tenantId, "tenantId"),
932
- workspaceId: input.workspaceId,
933
- principalId: input.principalId,
934
- limit: input.limit,
935
- cursor: input.cursor
936
- };
937
- }
938
- function tenantIdentityBody(input, operation) {
939
- return knownPayload(input, TENANT_IDENTITY_FIELDS, operation);
940
- }
941
- function createIdentityClient(config = {}) {
942
- const gateway = createGatewayRequestClient(config);
943
- const whoamiClient = createIdentityWhoamiClient(config);
944
- const requestPrincipalWrite = (method, input, idempotencyKey) => gateway.request({
945
- path: "/api/platform/v1/identity/principals",
946
- method,
947
- body: input,
948
- idempotencyKey: idempotencyKey ?? randomIdempotencyKey()
949
- });
950
- const updatePrincipal = (input, idempotencyKey) => requestPrincipalWrite("PATCH", input, idempotencyKey);
951
- const deleteKey = (keyId, input = {}, idempotencyKey) => gateway.request({
952
- path: `/api/platform/v1/identity/keys/${encodeURIComponent(keyId)}/revoke`,
953
- method: "POST",
954
- body: input,
955
- idempotencyKey: idempotencyKey ?? randomIdempotencyKey()
956
- });
957
- return {
958
- /**
959
- * Resolve the current authenticated identity summary.
960
- */
961
- async whoami() {
962
- return whoamiClient.whoami().then(
963
- (response) => mapGatewayData(response, (data) => ({
964
- principalId: data.principalId,
965
- principalType: data.principalType,
966
- clerkId: data.clerkId,
967
- tenantId: data.tenantId ?? null,
968
- workspaceId: data.workspaceId ?? null,
969
- scopes: Array.isArray(data.scopes) ? data.scopes : [],
970
- roles: Array.isArray(data.roles) ? data.roles : [],
971
- groupIds: Array.isArray(data.groupIds) ? data.groupIds : [],
972
- permittedToolNames: Array.isArray(data.permittedToolNames) ? data.permittedToolNames : [],
973
- permittedPackKeys: Array.isArray(data.permittedPackKeys) ? data.permittedPackKeys : [],
974
- principalStatus: data.principalStatus,
975
- tenantStatus: data.tenantStatus,
976
- workspaceStatus: data.workspaceStatus,
977
- isPlatformAdmin: data.isPlatformAdmin === true,
978
- isTenantAdmin: data.isTenantAdmin === true,
979
- isWorkspaceAdmin: data.isWorkspaceAdmin === true,
980
- permit: data.permit ?? (data.tenantId ? {
981
- subject: data.principalId,
982
- tenant: data.tenantId,
983
- ...data.workspaceId ? { workspace: data.workspaceId } : {}
984
- } : void 0),
985
- authMode: data.authMode,
986
- sessionId: data.sessionId,
987
- delegatedBy: data.delegatedBy,
988
- expiresAt: data.expiresAt
989
- }))
990
- );
991
- },
992
- /**
993
- * Resolve a Clerk subject through the tenant control-plane Permit projection.
994
- * @deprecated Prefer lucern.controlPlane.identity.resolveInteractivePrincipal().
995
- */
996
- async resolveInteractivePrincipal(input) {
997
- return gateway.request({
998
- path: "/api/platform/v1/control-plane/identity/resolve-interactive-principal",
999
- method: "POST",
1000
- body: input
1001
- }).then(
1002
- (response) => mapGatewayData(response, normalizeResolvedInteractivePrincipal)
1003
- );
1004
- },
1005
- /**
1006
- * List principals in the current identity scope.
1007
- */
1008
- async listPrincipals(query = {}) {
1009
- return gateway.request({
1010
- path: `/api/platform/v1/identity/principals${toQueryString(query)}`
1011
- }).then(
1012
- (response) => mapGatewayData(
1013
- response,
1014
- (data) => createListResult(
1015
- Array.isArray(data) ? data : [],
1016
- "principals"
1017
- )
1018
- )
1019
- );
1020
- },
1021
- /**
1022
- * Create a principal.
1023
- */
1024
- async createPrincipal(input, idempotencyKey) {
1025
- return requestPrincipalWrite("POST", input, idempotencyKey);
1026
- },
1027
- /**
1028
- * Update a principal.
1029
- */
1030
- updatePrincipal,
1031
- /**
1032
- * @deprecated Use createPrincipal or updatePrincipal.
1033
- */
1034
- upsertPrincipal: updatePrincipal,
1035
- /**
1036
- * List keys in the current identity scope.
1037
- */
1038
- async listKeys(query = {}) {
1039
- return gateway.request({
1040
- path: `/api/platform/v1/identity/keys${toQueryString(query)}`
1041
- }).then(
1042
- (response) => mapGatewayData(
1043
- response,
1044
- (data) => createListResult(Array.isArray(data) ? data : [], "keys")
1045
- )
1046
- );
1047
- },
1048
- /**
1049
- * Create an API key.
1050
- */
1051
- async createKey(input, idempotencyKey) {
1052
- return gateway.request({
1053
- path: "/api/platform/v1/identity/keys",
1054
- method: "POST",
1055
- body: input,
1056
- idempotencyKey: idempotencyKey ?? randomIdempotencyKey()
1057
- });
1058
- },
1059
- /**
1060
- * Rotate an API key.
1061
- */
1062
- async rotateKey(keyId, input = {}, idempotencyKey) {
1063
- return gateway.request({
1064
- path: `/api/platform/v1/identity/keys/${encodeURIComponent(keyId)}/rotate`,
1065
- method: "POST",
1066
- body: input,
1067
- idempotencyKey: idempotencyKey ?? randomIdempotencyKey()
1068
- });
1069
- },
1070
- /**
1071
- * Delete an API key by revoking it.
1072
- */
1073
- deleteKey,
1074
- /**
1075
- * @deprecated Use deleteKey.
1076
- */
1077
- revokeKey: deleteKey,
1078
- /**
1079
- * Search Clerk users by email or display attributes.
1080
- */
1081
- async searchClerkUsers(q) {
1082
- return gateway.request({
1083
- path: `/api/platform/v1/identity/clerk-users${toQueryString({ q })}`
1084
- });
1085
- },
1086
- async getTenantConfig(input) {
1087
- return gateway.request({
1088
- path: `/api/platform/v1/identity/tenant-config${toQueryString(
1089
- tenantIdentityQuery(input)
1090
- )}`
1091
- });
1092
- },
1093
- async updateTenantConfig(input, idempotencyKey) {
1094
- cleanRequiredString(input.tenantId, "tenantId");
1095
- return gateway.request({
1096
- path: "/api/platform/v1/identity/tenant-config",
1097
- method: "PATCH",
1098
- body: tenantIdentityBody(
1099
- input,
1100
- "identity.updateTenantConfig"
1101
- ),
1102
- idempotencyKey: idempotencyKey ?? randomIdempotencyKey()
1103
- });
1104
- },
1105
- async listIntegrations(input) {
1106
- return gateway.request({
1107
- path: `/api/platform/v1/identity/integrations${toQueryString(
1108
- tenantIdentityQuery(input)
1109
- )}`
1110
- }).then(
1111
- (response) => mapGatewayData(
1112
- response,
1113
- (data) => listResultFromEnvelope(
1114
- data,
1115
- "integrations"
1116
- )
1117
- )
1118
- );
1119
- },
1120
- async upsertIntegration(input, idempotencyKey) {
1121
- cleanRequiredString(input.tenantId, "tenantId");
1122
- cleanRequiredString(input.integrationKey, "integrationKey");
1123
- return gateway.request({
1124
- path: "/api/platform/v1/identity/integrations",
1125
- method: "PUT",
1126
- body: tenantIdentityBody(
1127
- input,
1128
- "identity.upsertIntegration"
1129
- ),
1130
- idempotencyKey: idempotencyKey ?? randomIdempotencyKey()
1131
- });
1132
- },
1133
- async listSecrets(input) {
1134
- return gateway.request({
1135
- path: `/api/platform/v1/identity/secrets${toQueryString(
1136
- tenantIdentityQuery(input)
1137
- )}`
1138
- }).then(
1139
- (response) => mapGatewayData(
1140
- response,
1141
- (data) => listResultFromEnvelope(
1142
- data,
1143
- "secrets"
1144
- )
1145
- )
1146
- );
1147
- },
1148
- async putSecretReference(input, idempotencyKey) {
1149
- cleanRequiredString(input.tenantId, "tenantId");
1150
- cleanRequiredString(input.secretRef, "secretRef");
1151
- return gateway.request({
1152
- path: "/api/platform/v1/identity/secrets",
1153
- method: "PUT",
1154
- body: tenantIdentityBody(
1155
- input,
1156
- "identity.putSecretReference"
1157
- ),
1158
- idempotencyKey: idempotencyKey ?? randomIdempotencyKey()
1159
- });
1160
- },
1161
- async evaluatePolicy(input, idempotencyKey) {
1162
- cleanRequiredString(input.tenantId, "tenantId");
1163
- cleanRequiredString(input.policySubject, "policySubject");
1164
- cleanRequiredString(input.policyAction, "policyAction");
1165
- cleanRequiredString(input.policyResource, "policyResource");
1166
- return gateway.request({
1167
- path: "/api/platform/v1/identity/policy/evaluate",
1168
- method: "POST",
1169
- body: tenantIdentityBody(
1170
- input,
1171
- "identity.evaluatePolicy"
1172
- ),
1173
- idempotencyKey: idempotencyKey ?? randomIdempotencyKey()
1174
- });
1175
- },
1176
- async recordPolicyDecision(input, idempotencyKey) {
1177
- cleanRequiredString(input.tenantId, "tenantId");
1178
- cleanRequiredString(input.decision, "decision");
1179
- return gateway.request({
1180
- path: "/api/platform/v1/identity/policy/decisions",
1181
- method: "POST",
1182
- body: tenantIdentityBody(
1183
- input,
1184
- "identity.recordPolicyDecision"
1185
- ),
1186
- idempotencyKey: idempotencyKey ?? randomIdempotencyKey()
1187
- });
63
+ if (canonicalClerkUserId) {
64
+ const canonicalAlias = {
65
+ provider: "clerk",
66
+ externalSubjectId: canonicalClerkUserId,
67
+ status: "active",
68
+ };
69
+ aliases.set(aliasKey(canonicalAlias), canonicalAlias);
1188
70
  }
1189
- };
1190
- }
1191
-
1192
- // src/accessControl.ts
1193
- var LucernAccessControlError = class extends LucernSdkAuthContextError {
1194
- policyDecision;
1195
- constructor(reason, message, policyDecision) {
1196
- super(reason, message);
1197
- this.name = "LucernAccessControlError";
1198
- this.policyDecision = policyDecision;
1199
- }
1200
- };
1201
- function cleanString3(value) {
1202
- const normalized = value?.trim();
1203
- return normalized ? normalized : void 0;
1204
- }
1205
- function cleanStringList2(values) {
1206
- if (!values) {
1207
- return [];
1208
- }
1209
- return [
1210
- ...new Set(
1211
- values.map((value) => value.trim()).filter((value) => value.length > 0)
1212
- )
1213
- ];
1214
- }
1215
- function requireString2(value, reason, label) {
1216
- const normalized = cleanString3(value);
1217
- if (!normalized) {
1218
- throw new LucernAccessControlError(
1219
- reason,
1220
- `Lucern SDK access control requires ${label}.`
1221
- );
1222
- }
1223
- return normalized;
1224
- }
1225
- function normalizePrincipalType(principalType2) {
1226
- if (principalType2 === "agent") {
1227
- return "agent";
1228
- }
1229
- if (principalType2 === "service") {
1230
- return "service";
1231
- }
1232
- if (principalType2 === "group") {
1233
- return "group";
1234
- }
1235
- if (principalType2 === "external_viewer") {
1236
- return "external_viewer";
1237
- }
1238
- return "human";
1239
- }
1240
- function aliasKey(alias) {
1241
- return `${alias.provider}:${alias.providerProjectId ?? ""}:${alias.externalSubjectId}`;
1242
- }
1243
- function normalizeAliases(input, canonicalClerkUserId) {
1244
- const aliases = /* @__PURE__ */ new Map();
1245
- for (const alias of input ?? []) {
1246
- const externalSubjectId = cleanString3(alias.externalSubjectId);
1247
- if (!externalSubjectId) {
1248
- continue;
1249
- }
1250
- const normalized = {
1251
- provider: cleanString3(alias.provider) ?? "clerk",
1252
- providerProjectId: cleanString3(alias.providerProjectId),
1253
- externalSubjectId,
1254
- status: cleanString3(alias.status)
1255
- };
1256
- aliases.set(aliasKey(normalized), normalized);
1257
- }
1258
- if (canonicalClerkUserId) {
1259
- const canonicalAlias = {
1260
- provider: "clerk",
1261
- externalSubjectId: canonicalClerkUserId,
1262
- status: "active"
1263
- };
1264
- aliases.set(aliasKey(canonicalAlias), canonicalAlias);
1265
- }
1266
- return [...aliases.values()];
71
+ return [...aliases.values()];
1267
72
  }
1268
73
  function isKnownClerkSubject(args) {
1269
- if (args.clerkId === args.canonicalClerkUserId) {
1270
- return true;
1271
- }
1272
- return args.aliases.some(
1273
- (alias) => alias.provider === "clerk" && alias.externalSubjectId === args.clerkId
1274
- );
74
+ if (args.clerkId === args.canonicalClerkUserId) {
75
+ return true;
76
+ }
77
+ return args.aliases.some((alias) => alias.provider === "clerk" && alias.externalSubjectId === args.clerkId);
1275
78
  }
1276
79
  function authContextToPrincipalInput(input) {
1277
- const normalized = normalizeCanonicalLucernAuthContext(input);
1278
- return {
1279
- principalId: normalized.principalId,
1280
- principalType: normalized.principalType,
1281
- canonicalClerkUserId: normalized.clerkId,
1282
- clerkId: normalized.clerkId,
1283
- tenantId: normalized.tenantId,
1284
- workspaceId: normalized.workspaceId,
1285
- roles: normalized.roles,
1286
- scopes: normalized.scopes
1287
- };
80
+ const normalized = normalizeCanonicalLucernAuthContext(input);
81
+ return {
82
+ principalId: normalized.principalId,
83
+ principalType: normalized.principalType,
84
+ canonicalClerkUserId: normalized.clerkId,
85
+ clerkId: normalized.clerkId,
86
+ tenantId: normalized.tenantId,
87
+ workspaceId: normalized.workspaceId,
88
+ roles: normalized.roles,
89
+ scopes: normalized.scopes,
90
+ };
1288
91
  }
1289
92
  function isAuthContextInput(input) {
1290
- return "authMode" in input || "permit" in input || "delegationChain" in input;
1291
- }
1292
- function normalizeCanonicalPrincipalIdentity(input, options = {}) {
1293
- const principalInput = isAuthContextInput(input) ? authContextToPrincipalInput(input) : input;
1294
- const principalId = requireString2(
1295
- principalInput.principalId,
1296
- "principal_missing",
1297
- "principalId"
1298
- );
1299
- const principalType2 = normalizePrincipalType(principalInput.principalType);
1300
- const observedClerkId = cleanString3(options.observedClerkId);
1301
- const canonicalClerkUserId = cleanString3(principalInput.canonicalClerkUserId) ?? cleanString3(principalInput.clerkId);
1302
- if (principalType2 === "human" && !canonicalClerkUserId) {
1303
- throw new LucernAccessControlError(
1304
- "clerk_alias_missing",
1305
- "Human principals require one canonical Clerk user id."
1306
- );
1307
- }
1308
- const aliases = normalizeAliases(
1309
- principalInput.clerkIdentityAliases,
1310
- canonicalClerkUserId
1311
- );
1312
- if (observedClerkId && !isKnownClerkSubject({
1313
- clerkId: observedClerkId,
1314
- canonicalClerkUserId,
1315
- aliases
1316
- })) {
1317
- throw new LucernAccessControlError(
1318
- "clerk_alias_unrecognized",
1319
- "Observed Clerk user id does not match the canonical human principal id."
1320
- );
1321
- }
1322
- return {
1323
- principalId,
1324
- principalType: principalType2,
1325
- canonicalClerkUserId,
1326
- clerkIdentityAliases: aliases,
1327
- tenantId: cleanString3(principalInput.tenantId),
1328
- workspaceId: cleanString3(principalInput.workspaceId),
1329
- roles: cleanStringList2(principalInput.roles),
1330
- scopes: cleanStringList2(principalInput.scopes)
1331
- };
93
+ return "authMode" in input || "permit" in input || "delegationChain" in input;
94
+ }
95
+ export function normalizeCanonicalPrincipalIdentity(input, options = {}) {
96
+ const principalInput = isAuthContextInput(input)
97
+ ? authContextToPrincipalInput(input)
98
+ : input;
99
+ const principalId = requireString(principalInput.principalId, "principal_missing", "principalId");
100
+ const principalType = normalizePrincipalType(principalInput.principalType);
101
+ const observedClerkId = cleanString(options.observedClerkId);
102
+ const canonicalClerkUserId = cleanString(principalInput.canonicalClerkUserId) ??
103
+ cleanString(principalInput.clerkId);
104
+ if (principalType === "human" && !canonicalClerkUserId) {
105
+ throw new LucernAccessControlError("clerk_alias_missing", "Human principals require one canonical Clerk user id.");
106
+ }
107
+ const aliases = normalizeAliases(principalInput.clerkIdentityAliases, canonicalClerkUserId);
108
+ if (observedClerkId &&
109
+ !isKnownClerkSubject({
110
+ clerkId: observedClerkId,
111
+ canonicalClerkUserId,
112
+ aliases,
113
+ })) {
114
+ throw new LucernAccessControlError("clerk_alias_unrecognized", "Observed Clerk user id does not match the canonical human principal id.");
115
+ }
116
+ return {
117
+ principalId,
118
+ principalType,
119
+ canonicalClerkUserId,
120
+ clerkIdentityAliases: aliases,
121
+ tenantId: cleanString(principalInput.tenantId),
122
+ workspaceId: cleanString(principalInput.workspaceId),
123
+ roles: cleanStringList(principalInput.roles),
124
+ scopes: cleanStringList(principalInput.scopes),
125
+ };
1332
126
  }
1333
- function formatPermitResource(resource) {
1334
- if (typeof resource === "string") {
1335
- return requireString2(resource, "policy_denied", "policyResource");
1336
- }
1337
- const type = requireString2(resource.type, "policy_denied", "resource.type");
1338
- const key = requireString2(resource.key, "policy_denied", "resource.key");
1339
- return key.startsWith(`${type}:`) ? key : `${type}:${key}`;
127
+ export function formatPermitResource(resource) {
128
+ if (typeof resource === "string") {
129
+ return requireString(resource, "policy_denied", "policyResource");
130
+ }
131
+ const type = requireString(resource.type, "policy_denied", "resource.type");
132
+ const key = requireString(resource.key, "policy_denied", "resource.key");
133
+ return key.startsWith(`${type}:`) ? key : `${type}:${key}`;
1340
134
  }
1341
135
  function resourceRequiresWorkspace(resource) {
1342
- if (typeof resource === "string") {
1343
- return !resource.startsWith("tenant:");
1344
- }
1345
- return resource.type !== "tenant";
136
+ if (typeof resource === "string") {
137
+ return !resource.startsWith("tenant:");
138
+ }
139
+ return resource.type !== "tenant";
1346
140
  }
1347
141
  function rejectConflictingScopeOverride(args) {
1348
- if (args.identityValue && args.requestedValue && args.identityValue !== args.requestedValue) {
1349
- throw new LucernAccessControlError(
1350
- "policy_denied",
1351
- `Lucern SDK access control rejects conflicting ${args.field} scope.`
1352
- );
1353
- }
142
+ if (args.identityValue &&
143
+ args.requestedValue &&
144
+ args.identityValue !== args.requestedValue) {
145
+ throw new LucernAccessControlError("policy_denied", `Lucern SDK access control rejects conflicting ${args.field} scope.`);
146
+ }
1354
147
  }
1355
148
  function buildPolicyInput(identity, input) {
1356
- rejectConflictingScopeOverride({
1357
- field: "tenantId",
1358
- identityValue: identity.tenantId,
1359
- requestedValue: cleanString3(input.tenantId)
1360
- });
1361
- rejectConflictingScopeOverride({
1362
- field: "workspaceId",
1363
- identityValue: identity.workspaceId,
1364
- requestedValue: cleanString3(input.workspaceId)
1365
- });
1366
- const tenantId = requireString2(
1367
- input.tenantId ?? identity.tenantId,
1368
- "tenant_missing",
1369
- "tenantId"
1370
- );
1371
- const workspaceId = cleanString3(input.workspaceId ?? identity.workspaceId);
1372
- if (resourceRequiresWorkspace(input.resource) && !workspaceId) {
1373
- throw new LucernAccessControlError(
1374
- "workspace_missing",
1375
- "Workspace-scoped Permit checks require workspaceId."
1376
- );
1377
- }
1378
- return {
1379
- tenantId,
1380
- workspaceId,
1381
- principalId: identity.principalId,
1382
- policySubject: identity.principalId,
1383
- policyAction: requireString2(input.action, "policy_denied", "policyAction"),
1384
- policyResource: formatPermitResource(input.resource),
1385
- metadata: input.context
1386
- };
149
+ rejectConflictingScopeOverride({
150
+ field: "tenantId",
151
+ identityValue: identity.tenantId,
152
+ requestedValue: cleanString(input.tenantId),
153
+ });
154
+ rejectConflictingScopeOverride({
155
+ field: "workspaceId",
156
+ identityValue: identity.workspaceId,
157
+ requestedValue: cleanString(input.workspaceId),
158
+ });
159
+ const tenantId = requireString(input.tenantId ?? identity.tenantId, "tenant_missing", "tenantId");
160
+ const workspaceId = cleanString(input.workspaceId ?? identity.workspaceId);
161
+ if (resourceRequiresWorkspace(input.resource) && !workspaceId) {
162
+ throw new LucernAccessControlError("workspace_missing", "Workspace-scoped Permit checks require workspaceId.");
163
+ }
164
+ return {
165
+ tenantId,
166
+ workspaceId,
167
+ principalId: identity.principalId,
168
+ policySubject: identity.principalId,
169
+ policyAction: requireString(input.action, "policy_denied", "policyAction"),
170
+ policyResource: formatPermitResource(input.resource),
171
+ metadata: input.context,
172
+ };
1387
173
  }
1388
174
  async function resolveConfiguredPrincipalInput(authContext) {
1389
- if (typeof authContext === "function") {
1390
- return await authContext();
1391
- }
1392
- return authContext;
175
+ if (typeof authContext === "function") {
176
+ return await authContext();
177
+ }
178
+ return authContext;
1393
179
  }
1394
- function assertPermitAllowed(decision) {
1395
- if (decision.decision !== "allow") {
1396
- throw new LucernAccessControlError(
1397
- decision.decision === "deny" ? "policy_denied" : "policy_unknown",
1398
- `Permit denied ${decision.policyAction} on ${decision.policyResource}.`,
1399
- decision
1400
- );
1401
- }
180
+ export function assertPermitAllowed(decision) {
181
+ if (decision.decision !== "allow") {
182
+ throw new LucernAccessControlError(decision.decision === "deny" ? "policy_denied" : "policy_unknown", `Permit denied ${decision.policyAction} on ${decision.policyResource}.`, decision);
183
+ }
1402
184
  }
1403
- function createAccessControlClient(config = {}) {
1404
- const identityClient = createIdentityClient(config);
1405
- async function resolveIdentity(input, observedClerkId) {
1406
- const identityInput = input ?? await resolveConfiguredPrincipalInput(config.authContext);
1407
- if (!identityInput) {
1408
- throw new LucernAccessControlError(
1409
- "principal_missing",
1410
- "Lucern SDK access control requires a canonical principal identity."
1411
- );
185
+ export function createAccessControlClient(config = {}) {
186
+ const identityClient = createIdentityClient(config);
187
+ async function resolveIdentity(input, observedClerkId) {
188
+ const identityInput = input ?? (await resolveConfiguredPrincipalInput(config.authContext));
189
+ if (!identityInput) {
190
+ throw new LucernAccessControlError("principal_missing", "Lucern SDK access control requires a canonical principal identity.");
191
+ }
192
+ return normalizeCanonicalPrincipalIdentity(identityInput, {
193
+ observedClerkId,
194
+ });
1412
195
  }
1413
- return normalizeCanonicalPrincipalIdentity(identityInput, {
1414
- observedClerkId
1415
- });
1416
- }
1417
- async function checkAccess(input, idempotencyKey) {
1418
- const identity = await resolveIdentity(input.identity, input.observedClerkId);
1419
- const policyInput = buildPolicyInput(identity, input);
1420
- try {
1421
- const response = await identityClient.evaluatePolicy(
1422
- policyInput,
1423
- idempotencyKey
1424
- );
1425
- return {
1426
- identity,
1427
- policyInput,
1428
- decision: response.data
1429
- };
1430
- } catch (error) {
1431
- if (error instanceof LucernSdkAuthContextError) {
1432
- throw error;
1433
- }
1434
- throw new LucernAccessControlError(
1435
- "policy_unavailable",
1436
- "Permit policy check failed closed before an allow decision was returned."
1437
- );
196
+ async function checkAccess(input, idempotencyKey) {
197
+ const identity = await resolveIdentity(input.identity, input.observedClerkId);
198
+ const policyInput = buildPolicyInput(identity, input);
199
+ try {
200
+ const response = await identityClient.evaluatePolicy(policyInput, idempotencyKey);
201
+ return {
202
+ identity,
203
+ policyInput,
204
+ decision: response.data,
205
+ };
206
+ }
207
+ catch (error) {
208
+ if (error instanceof LucernSdkAuthContextError) {
209
+ throw error;
210
+ }
211
+ throw new LucernAccessControlError("policy_unavailable", "Permit policy check failed closed before an allow decision was returned.");
212
+ }
1438
213
  }
1439
- }
1440
- async function requireAccess(input, idempotencyKey) {
1441
- const result = await checkAccess(input, idempotencyKey);
1442
- assertPermitAllowed(result.decision);
1443
- return result;
1444
- }
1445
- async function canAccess(input, idempotencyKey) {
1446
- try {
1447
- await requireAccess(input, idempotencyKey);
1448
- return true;
1449
- } catch {
1450
- return false;
214
+ async function requireAccess(input, idempotencyKey) {
215
+ const result = await checkAccess(input, idempotencyKey);
216
+ assertPermitAllowed(result.decision);
217
+ return result;
1451
218
  }
1452
- }
1453
- return {
1454
- normalizePrincipal: normalizeCanonicalPrincipalIdentity,
1455
- checkAccess,
1456
- requireAccess,
1457
- canAccess
1458
- };
219
+ async function canAccess(input, idempotencyKey) {
220
+ try {
221
+ await requireAccess(input, idempotencyKey);
222
+ return true;
223
+ }
224
+ catch {
225
+ return false;
226
+ }
227
+ }
228
+ return {
229
+ normalizePrincipal: normalizeCanonicalPrincipalIdentity,
230
+ checkAccess,
231
+ requireAccess,
232
+ canAccess,
233
+ };
1459
234
  }
1460
-
1461
- export { LucernAccessControlError, assertPermitAllowed, createAccessControlClient, formatPermitResource, normalizeCanonicalPrincipalIdentity };
1462
- //# sourceMappingURL=accessControl.js.map
1463
235
  //# sourceMappingURL=accessControl.js.map