@lucern/sdk 0.3.0-alpha.10 → 0.3.0-alpha.11
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/README.md +1 -1
- package/dist/accessControl.d.ts +78 -0
- package/dist/accessControl.js +1118 -0
- package/dist/accessControl.js.map +1 -0
- package/dist/adminClient.js.map +1 -1
- package/dist/answersClient.js.map +1 -1
- package/dist/audiencesClient.js.map +1 -1
- package/dist/auditClient.js.map +1 -1
- package/dist/authContext.d.ts +1 -1
- package/dist/authContext.js.map +1 -1
- package/dist/beliefs/index.d.ts +1 -0
- package/dist/beliefs/index.js +799 -551
- package/dist/beliefs/index.js.map +1 -1
- package/dist/beliefsClient.js.map +1 -1
- package/dist/client.d.ts +27 -8
- package/dist/client.js +799 -551
- package/dist/client.js.map +1 -1
- package/dist/contextClient.js.map +1 -1
- package/dist/contracts/api-enums.contract.d.ts +1 -1
- package/dist/contracts/api-enums.contract.js +6 -1
- package/dist/contracts/api-enums.contract.js.map +1 -1
- package/dist/contracts/index.js +12 -1
- package/dist/contracts/index.js.map +1 -1
- package/dist/contracts/mcpTools.js +6 -0
- package/dist/contracts/mcpTools.js.map +1 -1
- package/dist/contradictions/index.d.ts +1 -0
- package/dist/contradictions/index.js +799 -551
- package/dist/contradictions/index.js.map +1 -1
- package/dist/coreClient.js.map +1 -1
- package/dist/decisions/index.d.ts +1 -0
- package/dist/decisions/index.js +799 -551
- package/dist/decisions/index.js.map +1 -1
- package/dist/decisionsClient.js.map +1 -1
- package/dist/edges/index.d.ts +1 -0
- package/dist/edges/index.js +799 -551
- package/dist/edges/index.js.map +1 -1
- package/dist/embeddingsClient.js.map +1 -1
- package/dist/eventingClient.js.map +1 -1
- package/dist/eventsCore.js.map +1 -1
- package/dist/evidence/index.d.ts +1 -0
- package/dist/evidence/index.js +799 -551
- package/dist/evidence/index.js.map +1 -1
- package/dist/evidenceClient.js.map +1 -1
- package/dist/functionSurface.js.map +1 -1
- package/dist/functionSurfaceClient.js.map +1 -1
- package/dist/gatewayFacades.d.ts +1 -0
- package/dist/gatewayFacades.js.map +1 -1
- package/dist/graphAnalysisClient.js.map +1 -1
- package/dist/graphClient.d.ts +1 -0
- package/dist/graphClient.js.map +1 -1
- package/dist/graphIntel.d.ts +1 -0
- package/dist/graphRecommendationsClient.js.map +1 -1
- package/dist/graphStateClassifierClient.js.map +1 -1
- package/dist/harnessClient.js.map +1 -1
- package/dist/identityClient.d.ts +1 -1
- package/dist/identityClient.js.map +1 -1
- package/dist/index.d.ts +2 -0
- package/dist/index.js +790 -490
- package/dist/index.js.map +1 -1
- package/dist/infisicalRuntime.d.ts +1 -0
- package/dist/infisicalRuntime.js +64 -32
- package/dist/infisicalRuntime.js.map +1 -1
- package/dist/jobsClient.js.map +1 -1
- package/dist/learningClient.js.map +1 -1
- package/dist/lenses/index.d.ts +1 -0
- package/dist/lenses/index.js +799 -551
- package/dist/lenses/index.js.map +1 -1
- package/dist/mcpClient.js +2 -1
- package/dist/mcpClient.js.map +1 -1
- package/dist/modelRuntimeClient.js.map +1 -1
- package/dist/nodes/index.d.ts +1 -0
- package/dist/nodes/index.js +799 -551
- package/dist/nodes/index.js.map +1 -1
- package/dist/ontologies/index.d.ts +1 -0
- package/dist/ontologies/index.js +799 -551
- package/dist/ontologies/index.js.map +1 -1
- package/dist/ontologyClient.js.map +1 -1
- package/dist/ontologyLinksClient.js.map +1 -1
- package/dist/orgGraphSearchClient.js.map +1 -1
- package/dist/packsClient.js.map +1 -1
- package/dist/policyClient.js.map +1 -1
- package/dist/questions/index.d.ts +1 -0
- package/dist/questions/index.js +799 -551
- package/dist/questions/index.js.map +1 -1
- package/dist/reportsClient.js.map +1 -1
- package/dist/schemaClient.js.map +1 -1
- package/dist/secrets.d.ts +1 -0
- package/dist/secrets.js +3 -0
- package/dist/secrets.js.map +1 -0
- package/dist/sourcesClient.js.map +1 -1
- package/dist/telemetryClient.js.map +1 -1
- package/dist/toolRegistryClient.js.map +1 -1
- package/dist/topics/index.d.ts +1 -0
- package/dist/topics/index.js +799 -551
- package/dist/topics/index.js.map +1 -1
- package/dist/topicsClient.js.map +1 -1
- package/dist/version.d.ts +1 -1
- package/dist/version.js +1 -1
- package/dist/version.js.map +1 -1
- package/dist/workflowClient.js.map +1 -1
- package/dist/worktrees/index.d.ts +1 -0
- package/dist/worktrees/index.js +799 -551
- package/dist/worktrees/index.js.map +1 -1
- package/package.json +5 -4
|
@@ -0,0 +1,1118 @@
|
|
|
1
|
+
// src/authContext.ts
|
|
2
|
+
var LucernSdkAuthContextError = class extends Error {
|
|
3
|
+
reason;
|
|
4
|
+
constructor(reason, message) {
|
|
5
|
+
super(message);
|
|
6
|
+
this.name = "LucernSdkAuthContextError";
|
|
7
|
+
this.reason = reason;
|
|
8
|
+
}
|
|
9
|
+
};
|
|
10
|
+
function cleanString(value) {
|
|
11
|
+
const normalized = value?.trim();
|
|
12
|
+
return normalized ? normalized : void 0;
|
|
13
|
+
}
|
|
14
|
+
function cleanStringList(values) {
|
|
15
|
+
if (!values) {
|
|
16
|
+
return [];
|
|
17
|
+
}
|
|
18
|
+
return values.map((value) => value.trim()).filter(
|
|
19
|
+
(value, index, list) => value.length > 0 && list.indexOf(value) === index
|
|
20
|
+
);
|
|
21
|
+
}
|
|
22
|
+
function requireString(value, reason, label) {
|
|
23
|
+
const normalized = cleanString(value);
|
|
24
|
+
if (!normalized) {
|
|
25
|
+
throw new LucernSdkAuthContextError(
|
|
26
|
+
reason,
|
|
27
|
+
`Canonical Lucern SDK auth context is missing ${label}.`
|
|
28
|
+
);
|
|
29
|
+
}
|
|
30
|
+
return normalized;
|
|
31
|
+
}
|
|
32
|
+
function requirePrincipalType(principalType) {
|
|
33
|
+
if (!principalType) {
|
|
34
|
+
throw new LucernSdkAuthContextError(
|
|
35
|
+
"principal_missing",
|
|
36
|
+
"Canonical Lucern SDK auth context is missing principalType."
|
|
37
|
+
);
|
|
38
|
+
}
|
|
39
|
+
return principalType;
|
|
40
|
+
}
|
|
41
|
+
function requireAuthMode(authMode) {
|
|
42
|
+
if (!authMode) {
|
|
43
|
+
throw new LucernSdkAuthContextError(
|
|
44
|
+
"principal_missing",
|
|
45
|
+
"Canonical Lucern SDK auth context is missing authMode."
|
|
46
|
+
);
|
|
47
|
+
}
|
|
48
|
+
return authMode;
|
|
49
|
+
}
|
|
50
|
+
function ensurePermitMatch(args) {
|
|
51
|
+
const actual = cleanString(args.actual);
|
|
52
|
+
if (actual && actual !== args.expected) {
|
|
53
|
+
throw new LucernSdkAuthContextError(
|
|
54
|
+
"policy_denied",
|
|
55
|
+
`Canonical Lucern SDK auth context has conflicting Permit ${args.field}.`
|
|
56
|
+
);
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
function normalizeCanonicalLucernAuthContext(input) {
|
|
60
|
+
if (!input) {
|
|
61
|
+
throw new LucernSdkAuthContextError(
|
|
62
|
+
"principal_missing",
|
|
63
|
+
"Canonical Lucern SDK auth context is required."
|
|
64
|
+
);
|
|
65
|
+
}
|
|
66
|
+
if (input.policyDecision === "deny") {
|
|
67
|
+
throw new LucernSdkAuthContextError(
|
|
68
|
+
"policy_denied",
|
|
69
|
+
"Canonical Lucern SDK auth context carries a denied policy decision."
|
|
70
|
+
);
|
|
71
|
+
}
|
|
72
|
+
const principalId = requireString(
|
|
73
|
+
input.principalId,
|
|
74
|
+
"principal_missing",
|
|
75
|
+
"principalId"
|
|
76
|
+
);
|
|
77
|
+
const tenantId = requireString(input.tenantId, "tenant_missing", "tenantId");
|
|
78
|
+
const workspaceId = requireString(
|
|
79
|
+
input.workspaceId,
|
|
80
|
+
"workspace_missing",
|
|
81
|
+
"workspaceId"
|
|
82
|
+
);
|
|
83
|
+
const roles = cleanStringList(input.roles);
|
|
84
|
+
const scopes = cleanStringList(input.scopes);
|
|
85
|
+
const principalType = requirePrincipalType(input.principalType);
|
|
86
|
+
const authMode = requireAuthMode(input.authMode);
|
|
87
|
+
const roleBasedInteractiveAuth = authMode === "interactive_user" && roles.length > 0;
|
|
88
|
+
if (roles.length === 0 || scopes.length === 0 && !roleBasedInteractiveAuth) {
|
|
89
|
+
throw new LucernSdkAuthContextError(
|
|
90
|
+
"membership_missing",
|
|
91
|
+
"Canonical Lucern SDK auth context requires non-empty roles and scopes."
|
|
92
|
+
);
|
|
93
|
+
}
|
|
94
|
+
const subject = cleanString(input.permit?.subject) ?? principalId;
|
|
95
|
+
const tenant = cleanString(input.permit?.tenant) ?? tenantId;
|
|
96
|
+
const workspace = cleanString(input.permit?.workspace) ?? workspaceId;
|
|
97
|
+
ensurePermitMatch({
|
|
98
|
+
field: "subject",
|
|
99
|
+
expected: principalId,
|
|
100
|
+
actual: subject
|
|
101
|
+
});
|
|
102
|
+
ensurePermitMatch({ field: "tenant", expected: tenantId, actual: tenant });
|
|
103
|
+
ensurePermitMatch({
|
|
104
|
+
field: "workspace",
|
|
105
|
+
expected: workspaceId,
|
|
106
|
+
actual: workspace
|
|
107
|
+
});
|
|
108
|
+
const context = input.permit?.context ? { ...input.permit.context } : void 0;
|
|
109
|
+
return {
|
|
110
|
+
clerkId: cleanString(input.clerkId),
|
|
111
|
+
principalId,
|
|
112
|
+
tenantId,
|
|
113
|
+
workspaceId,
|
|
114
|
+
principalType,
|
|
115
|
+
authMode,
|
|
116
|
+
roles,
|
|
117
|
+
scopes,
|
|
118
|
+
delegationChain: input.delegationChain ? [...input.delegationChain] : [],
|
|
119
|
+
policyTraceId: cleanString(input.policyTraceId),
|
|
120
|
+
correlationId: cleanString(input.correlationId),
|
|
121
|
+
membershipId: cleanString(input.membershipId),
|
|
122
|
+
permit: {
|
|
123
|
+
subject,
|
|
124
|
+
tenant,
|
|
125
|
+
workspace,
|
|
126
|
+
resource: cleanString(input.permit?.resource),
|
|
127
|
+
action: cleanString(input.permit?.action),
|
|
128
|
+
relation: cleanString(input.permit?.relation),
|
|
129
|
+
context
|
|
130
|
+
}
|
|
131
|
+
};
|
|
132
|
+
}
|
|
133
|
+
function createCanonicalAuthHeaders(authContext) {
|
|
134
|
+
const headers = {
|
|
135
|
+
"x-lucern-principal-id": authContext.principalId,
|
|
136
|
+
"x-lucern-principal-type": authContext.principalType,
|
|
137
|
+
"x-lucern-tenant": authContext.tenantId,
|
|
138
|
+
"x-lucern-tenant-id": authContext.tenantId,
|
|
139
|
+
"x-lucern-workspace": authContext.workspaceId,
|
|
140
|
+
"x-lucern-workspace-id": authContext.workspaceId,
|
|
141
|
+
"x-lucern-auth-mode": authContext.authMode,
|
|
142
|
+
"x-lucern-roles": authContext.roles.join(","),
|
|
143
|
+
"x-lucern-scopes": authContext.scopes.join(","),
|
|
144
|
+
"x-lucern-permit-context": JSON.stringify(authContext.permit)
|
|
145
|
+
};
|
|
146
|
+
if (authContext.clerkId) {
|
|
147
|
+
headers["x-lucern-clerk-id"] = authContext.clerkId;
|
|
148
|
+
headers["x-lucern-user-id"] = authContext.clerkId;
|
|
149
|
+
}
|
|
150
|
+
if (authContext.delegationChain.length > 0) {
|
|
151
|
+
headers["x-lucern-delegation-chain"] = JSON.stringify(
|
|
152
|
+
authContext.delegationChain
|
|
153
|
+
);
|
|
154
|
+
}
|
|
155
|
+
if (authContext.policyTraceId) {
|
|
156
|
+
headers["x-lucern-policy-trace-id"] = authContext.policyTraceId;
|
|
157
|
+
}
|
|
158
|
+
if (authContext.correlationId) {
|
|
159
|
+
headers["x-correlation-id"] = authContext.correlationId;
|
|
160
|
+
headers["x-lucern-correlation-id"] = authContext.correlationId;
|
|
161
|
+
}
|
|
162
|
+
if (authContext.membershipId) {
|
|
163
|
+
headers["x-lucern-membership-id"] = authContext.membershipId;
|
|
164
|
+
}
|
|
165
|
+
return headers;
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
// src/coreClient.ts
|
|
169
|
+
var LucernApiError = class extends Error {
|
|
170
|
+
code;
|
|
171
|
+
status;
|
|
172
|
+
invariant;
|
|
173
|
+
suggestion;
|
|
174
|
+
details;
|
|
175
|
+
requestId;
|
|
176
|
+
correlationId;
|
|
177
|
+
policyTraceId;
|
|
178
|
+
constructor(args) {
|
|
179
|
+
super(args.message);
|
|
180
|
+
this.name = "LucernApiError";
|
|
181
|
+
this.code = args.code;
|
|
182
|
+
this.status = args.status;
|
|
183
|
+
this.invariant = args.invariant;
|
|
184
|
+
this.suggestion = args.suggestion;
|
|
185
|
+
this.details = args.details;
|
|
186
|
+
this.requestId = args.requestId;
|
|
187
|
+
this.correlationId = args.correlationId;
|
|
188
|
+
this.policyTraceId = args.policyTraceId;
|
|
189
|
+
}
|
|
190
|
+
};
|
|
191
|
+
function toQueryString(scope) {
|
|
192
|
+
const params = new URLSearchParams();
|
|
193
|
+
if (scope.tenantId) {
|
|
194
|
+
params.set("tenantId", scope.tenantId);
|
|
195
|
+
}
|
|
196
|
+
if (scope.workspaceId) {
|
|
197
|
+
params.set("workspaceId", scope.workspaceId);
|
|
198
|
+
}
|
|
199
|
+
for (const [key, value] of Object.entries(scope)) {
|
|
200
|
+
if (key === "tenantId" || key === "workspaceId") {
|
|
201
|
+
continue;
|
|
202
|
+
}
|
|
203
|
+
if (value === void 0) {
|
|
204
|
+
continue;
|
|
205
|
+
}
|
|
206
|
+
params.set(key, String(value));
|
|
207
|
+
}
|
|
208
|
+
const serialized = params.toString();
|
|
209
|
+
return serialized.length > 0 ? `?${serialized}` : "";
|
|
210
|
+
}
|
|
211
|
+
function fillRandomBytes(length) {
|
|
212
|
+
const bytes = new Uint8Array(length);
|
|
213
|
+
if (typeof globalThis.crypto?.getRandomValues === "function") {
|
|
214
|
+
globalThis.crypto.getRandomValues(bytes);
|
|
215
|
+
return bytes;
|
|
216
|
+
}
|
|
217
|
+
for (let index = 0; index < length; index += 1) {
|
|
218
|
+
bytes[index] = Math.floor(Math.random() * 256);
|
|
219
|
+
}
|
|
220
|
+
return bytes;
|
|
221
|
+
}
|
|
222
|
+
function generatePortableRequestId() {
|
|
223
|
+
if (typeof globalThis.crypto?.randomUUID === "function") {
|
|
224
|
+
return globalThis.crypto.randomUUID();
|
|
225
|
+
}
|
|
226
|
+
const bytes = fillRandomBytes(16);
|
|
227
|
+
bytes[6] = bytes[6] & 15 | 64;
|
|
228
|
+
bytes[8] = bytes[8] & 63 | 128;
|
|
229
|
+
const hex = Array.from(bytes, (value) => value.toString(16).padStart(2, "0"));
|
|
230
|
+
return `${hex.slice(0, 4).join("")}-${hex.slice(4, 6).join("")}-${hex.slice(
|
|
231
|
+
6,
|
|
232
|
+
8
|
|
233
|
+
).join("")}-${hex.slice(8, 10).join("")}-${hex.slice(10).join("")}`;
|
|
234
|
+
}
|
|
235
|
+
var randomIdempotencyKey = generatePortableRequestId;
|
|
236
|
+
function isRetryableStatus(status) {
|
|
237
|
+
return status >= 500 || status === 408 || status === 429;
|
|
238
|
+
}
|
|
239
|
+
function fallbackErrorCode(status) {
|
|
240
|
+
if (status === 401) {
|
|
241
|
+
return "AUTHENTICATION_REQUIRED";
|
|
242
|
+
}
|
|
243
|
+
if (status === 403) {
|
|
244
|
+
return "FORBIDDEN";
|
|
245
|
+
}
|
|
246
|
+
if (status === 404) {
|
|
247
|
+
return "NOT_FOUND";
|
|
248
|
+
}
|
|
249
|
+
if (status === 408) {
|
|
250
|
+
return "UPSTREAM_ERROR";
|
|
251
|
+
}
|
|
252
|
+
if (status === 409) {
|
|
253
|
+
return "CONFLICT";
|
|
254
|
+
}
|
|
255
|
+
if (status === 429) {
|
|
256
|
+
return "RATE_LIMIT_EXCEEDED";
|
|
257
|
+
}
|
|
258
|
+
if (status >= 500) {
|
|
259
|
+
return "UPSTREAM_ERROR";
|
|
260
|
+
}
|
|
261
|
+
return "INTERNAL_ERROR";
|
|
262
|
+
}
|
|
263
|
+
function delay(ms) {
|
|
264
|
+
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
265
|
+
}
|
|
266
|
+
function parseRetryAfterMs(value) {
|
|
267
|
+
if (!value) {
|
|
268
|
+
return null;
|
|
269
|
+
}
|
|
270
|
+
const trimmed = value.trim();
|
|
271
|
+
if (!trimmed) {
|
|
272
|
+
return null;
|
|
273
|
+
}
|
|
274
|
+
const numeric = Number(trimmed);
|
|
275
|
+
if (Number.isFinite(numeric)) {
|
|
276
|
+
return Math.max(0, Math.round(numeric * 1e3));
|
|
277
|
+
}
|
|
278
|
+
const parsedDate = Date.parse(trimmed);
|
|
279
|
+
if (Number.isFinite(parsedDate)) {
|
|
280
|
+
return Math.max(0, parsedDate - Date.now());
|
|
281
|
+
}
|
|
282
|
+
return null;
|
|
283
|
+
}
|
|
284
|
+
function computeRetryDelayMs(args) {
|
|
285
|
+
const baseDelay = args.status === 429 ? Math.max(
|
|
286
|
+
args.retryAfterMs ?? 0,
|
|
287
|
+
Math.min(1e3 * 2 ** args.attempt, 1e4)
|
|
288
|
+
) : Math.min(1e3 * 2 ** args.attempt, 4e3);
|
|
289
|
+
if (args.status !== 429) {
|
|
290
|
+
return baseDelay;
|
|
291
|
+
}
|
|
292
|
+
const jitterWindow = Math.max(250, Math.round(baseDelay * 0.25));
|
|
293
|
+
return baseDelay + Math.round(Math.random() * jitterWindow);
|
|
294
|
+
}
|
|
295
|
+
function timeoutError(timeoutMs) {
|
|
296
|
+
const error = new Error(`Request timed out after ${timeoutMs}ms`);
|
|
297
|
+
error.name = "AbortError";
|
|
298
|
+
return error;
|
|
299
|
+
}
|
|
300
|
+
function isRecord(value) {
|
|
301
|
+
return value !== null && typeof value === "object" && !Array.isArray(value);
|
|
302
|
+
}
|
|
303
|
+
function readPolicySummaryFromDetails(details) {
|
|
304
|
+
if (!isRecord(details)) {
|
|
305
|
+
return null;
|
|
306
|
+
}
|
|
307
|
+
const directSummary = details.summary;
|
|
308
|
+
if (typeof directSummary === "string" && directSummary.trim().length > 0) {
|
|
309
|
+
return directSummary.trim();
|
|
310
|
+
}
|
|
311
|
+
const policy = details.policy;
|
|
312
|
+
if (!isRecord(policy)) {
|
|
313
|
+
return null;
|
|
314
|
+
}
|
|
315
|
+
const explanation = policy.explanation;
|
|
316
|
+
if (!isRecord(explanation)) {
|
|
317
|
+
return null;
|
|
318
|
+
}
|
|
319
|
+
const nestedSummary = explanation.summary;
|
|
320
|
+
if (typeof nestedSummary === "string" && nestedSummary.trim().length > 0) {
|
|
321
|
+
return nestedSummary.trim();
|
|
322
|
+
}
|
|
323
|
+
return null;
|
|
324
|
+
}
|
|
325
|
+
async function resolveConfiguredAuthContext(authContext) {
|
|
326
|
+
if (typeof authContext === "function") {
|
|
327
|
+
return await authContext();
|
|
328
|
+
}
|
|
329
|
+
return authContext;
|
|
330
|
+
}
|
|
331
|
+
function mergeHeaderRecord(base, addition) {
|
|
332
|
+
const headers = new Headers(base);
|
|
333
|
+
for (const [key, value] of Object.entries(addition)) {
|
|
334
|
+
const existing = headers.get(key);
|
|
335
|
+
if (existing !== null && existing !== value) {
|
|
336
|
+
throw new LucernSdkAuthContextError(
|
|
337
|
+
"policy_denied",
|
|
338
|
+
`Canonical Lucern SDK auth context conflicts with existing ${key} header.`
|
|
339
|
+
);
|
|
340
|
+
}
|
|
341
|
+
headers.set(key, value);
|
|
342
|
+
}
|
|
343
|
+
return Object.fromEntries(headers.entries());
|
|
344
|
+
}
|
|
345
|
+
function createGatewayRequestClient(config = {}) {
|
|
346
|
+
const fetchImpl = config.fetchImpl ?? fetch;
|
|
347
|
+
const baseUrl = config.baseUrl?.replace(/\/+$/, "") ?? "";
|
|
348
|
+
const maxRetries = config.maxRetries ?? 2;
|
|
349
|
+
const requestIdFactory = config.requestIdFactory ?? (() => generatePortableRequestId());
|
|
350
|
+
async function resolveAuthHeaders() {
|
|
351
|
+
const base = config.getAuthHeaders ? await config.getAuthHeaders() : {};
|
|
352
|
+
const authContextInput = await resolveConfiguredAuthContext(
|
|
353
|
+
config.authContext
|
|
354
|
+
);
|
|
355
|
+
if (!authContextInput && !config.requireCanonicalAuthContext) {
|
|
356
|
+
return base;
|
|
357
|
+
}
|
|
358
|
+
const authContext = normalizeCanonicalLucernAuthContext(authContextInput);
|
|
359
|
+
return mergeHeaderRecord(base, createCanonicalAuthHeaders(authContext));
|
|
360
|
+
}
|
|
361
|
+
async function fetchWithTimeout(url, init, timeoutMs) {
|
|
362
|
+
const controller = new AbortController();
|
|
363
|
+
const timer = setTimeout(() => controller.abort(), timeoutMs);
|
|
364
|
+
try {
|
|
365
|
+
return await fetchImpl(url, { ...init, signal: controller.signal });
|
|
366
|
+
} catch (error) {
|
|
367
|
+
if (controller.signal.aborted) {
|
|
368
|
+
throw timeoutError(timeoutMs);
|
|
369
|
+
}
|
|
370
|
+
throw error;
|
|
371
|
+
} finally {
|
|
372
|
+
clearTimeout(timer);
|
|
373
|
+
}
|
|
374
|
+
}
|
|
375
|
+
async function parsePayload(response) {
|
|
376
|
+
const text = await response.text();
|
|
377
|
+
if (!text) {
|
|
378
|
+
return null;
|
|
379
|
+
}
|
|
380
|
+
const parsed = tryParseGatewayEnvelopeJson(text);
|
|
381
|
+
if (!parsed.ok) {
|
|
382
|
+
return null;
|
|
383
|
+
}
|
|
384
|
+
return isRecord(parsed.value) ? parsed.value : null;
|
|
385
|
+
}
|
|
386
|
+
function resolveTimeoutMs(method, requestTimeoutMs) {
|
|
387
|
+
if (typeof requestTimeoutMs === "number") {
|
|
388
|
+
return requestTimeoutMs;
|
|
389
|
+
}
|
|
390
|
+
const methodTimeoutMs = config.timeoutMsByMethod?.[method];
|
|
391
|
+
if (typeof methodTimeoutMs === "number") {
|
|
392
|
+
return methodTimeoutMs;
|
|
393
|
+
}
|
|
394
|
+
return config.timeoutMs ?? 15e3;
|
|
395
|
+
}
|
|
396
|
+
function tryParseGatewayEnvelopeJson(text) {
|
|
397
|
+
const trimmed = text.trim();
|
|
398
|
+
if (!trimmed.startsWith("{") && !trimmed.startsWith("[")) {
|
|
399
|
+
return { ok: false, reason: "non-json" };
|
|
400
|
+
}
|
|
401
|
+
try {
|
|
402
|
+
return { ok: true, value: JSON.parse(trimmed) };
|
|
403
|
+
} catch (error) {
|
|
404
|
+
if (error instanceof SyntaxError) {
|
|
405
|
+
return { ok: false, reason: "invalid-json", error };
|
|
406
|
+
}
|
|
407
|
+
throw error;
|
|
408
|
+
}
|
|
409
|
+
}
|
|
410
|
+
function buildApiError(args) {
|
|
411
|
+
const failure = args.failure;
|
|
412
|
+
const legacyError = failure && isRecord(failure.error) ? failure.error : failure?.legacyError;
|
|
413
|
+
const correlationId = failure?.correlationId ?? args.response.headers.get("x-lucern-correlation-id")?.trim() ?? args.requestId;
|
|
414
|
+
const policyTraceId = failure?.policyTraceId ?? args.response.headers.get("x-lucern-policy-trace-id")?.trim() ?? null;
|
|
415
|
+
const details = failure?.details ?? legacyError?.details;
|
|
416
|
+
const policySummary = readPolicySummaryFromDetails(details);
|
|
417
|
+
const failureMessage = typeof failure?.error === "string" ? failure.error : legacyError?.message;
|
|
418
|
+
return new LucernApiError({
|
|
419
|
+
code: failure?.code ?? legacyError?.code ?? fallbackErrorCode(args.response.status),
|
|
420
|
+
message: policySummary ?? failureMessage ?? (args.response.ok ? "Platform API returned an invalid success payload." : "Platform API request failed."),
|
|
421
|
+
status: args.response.status,
|
|
422
|
+
invariant: failure?.invariant,
|
|
423
|
+
suggestion: failure?.suggestion,
|
|
424
|
+
details,
|
|
425
|
+
requestId: args.requestId,
|
|
426
|
+
correlationId,
|
|
427
|
+
policyTraceId
|
|
428
|
+
});
|
|
429
|
+
}
|
|
430
|
+
async function request(args) {
|
|
431
|
+
const authHeaders = await resolveAuthHeaders();
|
|
432
|
+
const method = args.method ?? "GET";
|
|
433
|
+
const timeoutMs = resolveTimeoutMs(method, args.timeoutMs);
|
|
434
|
+
const headers = new Headers({
|
|
435
|
+
"content-type": "application/json",
|
|
436
|
+
...authHeaders
|
|
437
|
+
});
|
|
438
|
+
if (args.idempotencyKey) {
|
|
439
|
+
headers.set("idempotency-key", args.idempotencyKey);
|
|
440
|
+
}
|
|
441
|
+
const requestId = headers.get("x-correlation-id")?.trim() || headers.get("x-request-id")?.trim() || args.requestId || requestIdFactory();
|
|
442
|
+
if (!headers.has("x-correlation-id") && !headers.has("x-request-id")) {
|
|
443
|
+
headers.set("x-correlation-id", requestId);
|
|
444
|
+
}
|
|
445
|
+
const url = `${baseUrl}${args.path}`;
|
|
446
|
+
const serializedBody = args.body ? JSON.stringify(args.body) : void 0;
|
|
447
|
+
const init = {
|
|
448
|
+
method,
|
|
449
|
+
headers,
|
|
450
|
+
body: serializedBody
|
|
451
|
+
};
|
|
452
|
+
let lastError;
|
|
453
|
+
for (let attempt = 0; attempt <= maxRetries; attempt++) {
|
|
454
|
+
const hookRequestContext = {
|
|
455
|
+
requestId,
|
|
456
|
+
attempt,
|
|
457
|
+
maxRetries,
|
|
458
|
+
method,
|
|
459
|
+
path: args.path,
|
|
460
|
+
url,
|
|
461
|
+
headers: new Headers(headers),
|
|
462
|
+
body: serializedBody,
|
|
463
|
+
timeoutMs
|
|
464
|
+
};
|
|
465
|
+
await config.onRequest?.(hookRequestContext);
|
|
466
|
+
const startedAt = Date.now();
|
|
467
|
+
try {
|
|
468
|
+
const response = await fetchWithTimeout(url, init, timeoutMs);
|
|
469
|
+
const responseClone = response.clone();
|
|
470
|
+
const payload = await parsePayload(response);
|
|
471
|
+
const retryAfterMs = parseRetryAfterMs(
|
|
472
|
+
response.headers.get("Retry-After")
|
|
473
|
+
);
|
|
474
|
+
if (!response.ok || !payload?.success) {
|
|
475
|
+
const failure = payload && !payload.success ? payload : null;
|
|
476
|
+
const apiError = buildApiError({
|
|
477
|
+
requestId,
|
|
478
|
+
response,
|
|
479
|
+
failure
|
|
480
|
+
});
|
|
481
|
+
const willRetry = attempt < maxRetries && isRetryableStatus(response.status);
|
|
482
|
+
await config.onResponse?.({
|
|
483
|
+
...hookRequestContext,
|
|
484
|
+
durationMs: Date.now() - startedAt,
|
|
485
|
+
status: response.status,
|
|
486
|
+
response: responseClone,
|
|
487
|
+
error: apiError,
|
|
488
|
+
correlationId: apiError.correlationId ?? requestId,
|
|
489
|
+
policyTraceId: apiError.policyTraceId ?? null,
|
|
490
|
+
retryAfterMs,
|
|
491
|
+
willRetry
|
|
492
|
+
});
|
|
493
|
+
if (willRetry) {
|
|
494
|
+
lastError = apiError;
|
|
495
|
+
await delay(
|
|
496
|
+
computeRetryDelayMs({
|
|
497
|
+
attempt,
|
|
498
|
+
status: response.status,
|
|
499
|
+
retryAfterMs
|
|
500
|
+
})
|
|
501
|
+
);
|
|
502
|
+
continue;
|
|
503
|
+
}
|
|
504
|
+
throw apiError;
|
|
505
|
+
}
|
|
506
|
+
const successPayload = payload;
|
|
507
|
+
await config.onResponse?.({
|
|
508
|
+
...hookRequestContext,
|
|
509
|
+
durationMs: Date.now() - startedAt,
|
|
510
|
+
status: response.status,
|
|
511
|
+
response: responseClone,
|
|
512
|
+
correlationId: successPayload.correlationId ?? response.headers.get("x-lucern-correlation-id")?.trim() ?? requestId,
|
|
513
|
+
policyTraceId: successPayload.policyTraceId ?? response.headers.get("x-lucern-policy-trace-id")?.trim() ?? null,
|
|
514
|
+
idempotentReplay: successPayload.idempotentReplay,
|
|
515
|
+
retryAfterMs,
|
|
516
|
+
willRetry: false
|
|
517
|
+
});
|
|
518
|
+
return successPayload;
|
|
519
|
+
} catch (fetchError) {
|
|
520
|
+
if (fetchError instanceof LucernApiError) {
|
|
521
|
+
throw fetchError;
|
|
522
|
+
}
|
|
523
|
+
const willRetry = attempt < maxRetries;
|
|
524
|
+
await config.onResponse?.({
|
|
525
|
+
...hookRequestContext,
|
|
526
|
+
durationMs: Date.now() - startedAt,
|
|
527
|
+
error: fetchError,
|
|
528
|
+
correlationId: requestId,
|
|
529
|
+
policyTraceId: null,
|
|
530
|
+
willRetry
|
|
531
|
+
});
|
|
532
|
+
lastError = fetchError;
|
|
533
|
+
if (willRetry) {
|
|
534
|
+
await delay(computeRetryDelayMs({ attempt }));
|
|
535
|
+
}
|
|
536
|
+
}
|
|
537
|
+
}
|
|
538
|
+
throw lastError instanceof Error ? lastError : new Error("Platform API request failed after retries.");
|
|
539
|
+
}
|
|
540
|
+
return {
|
|
541
|
+
request
|
|
542
|
+
};
|
|
543
|
+
}
|
|
544
|
+
|
|
545
|
+
// src/sdkSurface.ts
|
|
546
|
+
function createListResult(items, legacyKey) {
|
|
547
|
+
const result = {
|
|
548
|
+
items,
|
|
549
|
+
total: items.length
|
|
550
|
+
};
|
|
551
|
+
if (legacyKey) {
|
|
552
|
+
return {
|
|
553
|
+
...result,
|
|
554
|
+
[legacyKey]: items
|
|
555
|
+
};
|
|
556
|
+
}
|
|
557
|
+
return result;
|
|
558
|
+
}
|
|
559
|
+
function mapGatewayData(response, mapper) {
|
|
560
|
+
return {
|
|
561
|
+
...response,
|
|
562
|
+
data: mapper(response.data)
|
|
563
|
+
};
|
|
564
|
+
}
|
|
565
|
+
|
|
566
|
+
// src/boundaryClientSurface.ts
|
|
567
|
+
function cleanOptionalString(value) {
|
|
568
|
+
const normalized = value?.trim();
|
|
569
|
+
return normalized ? normalized : void 0;
|
|
570
|
+
}
|
|
571
|
+
function isRecord2(value) {
|
|
572
|
+
return Boolean(value) && typeof value === "object" && !Array.isArray(value);
|
|
573
|
+
}
|
|
574
|
+
function cleanRequiredString(value, label) {
|
|
575
|
+
const normalized = cleanOptionalString(value);
|
|
576
|
+
if (!normalized) {
|
|
577
|
+
throw new Error(`${label} is required`);
|
|
578
|
+
}
|
|
579
|
+
return normalized;
|
|
580
|
+
}
|
|
581
|
+
function assertKnownKeys(input, allowed, operation) {
|
|
582
|
+
const allowedSet = new Set(allowed);
|
|
583
|
+
const unknownKeys = Object.keys(input).filter((key) => !allowedSet.has(key));
|
|
584
|
+
if (unknownKeys.length > 0) {
|
|
585
|
+
throw new Error(
|
|
586
|
+
`${operation} received unsupported field(s): ${unknownKeys.join(", ")}`
|
|
587
|
+
);
|
|
588
|
+
}
|
|
589
|
+
}
|
|
590
|
+
function knownPayload(input, allowed, operation) {
|
|
591
|
+
assertKnownKeys(input, allowed, operation);
|
|
592
|
+
return { ...input };
|
|
593
|
+
}
|
|
594
|
+
function listResultFromEnvelope(data, legacyKey) {
|
|
595
|
+
const record = isRecord2(data) ? data : {};
|
|
596
|
+
const legacyItems = record[legacyKey];
|
|
597
|
+
return createListResult(
|
|
598
|
+
Array.isArray(legacyItems) ? legacyItems : Array.isArray(data) ? data : [],
|
|
599
|
+
legacyKey
|
|
600
|
+
);
|
|
601
|
+
}
|
|
602
|
+
|
|
603
|
+
// src/identityClient.ts
|
|
604
|
+
function createIdentityWhoamiClient(config = {}) {
|
|
605
|
+
const gateway = createGatewayRequestClient(config);
|
|
606
|
+
return {
|
|
607
|
+
async whoami() {
|
|
608
|
+
return gateway.request({
|
|
609
|
+
path: "/api/platform/v1/identity/whoami"
|
|
610
|
+
});
|
|
611
|
+
}
|
|
612
|
+
};
|
|
613
|
+
}
|
|
614
|
+
var TENANT_IDENTITY_FIELDS = [
|
|
615
|
+
"tenantId",
|
|
616
|
+
"workspaceId",
|
|
617
|
+
"principalId",
|
|
618
|
+
"integrationKey",
|
|
619
|
+
"secretRef",
|
|
620
|
+
"policySubject",
|
|
621
|
+
"policyAction",
|
|
622
|
+
"policyResource",
|
|
623
|
+
"decision",
|
|
624
|
+
"config",
|
|
625
|
+
"configKey",
|
|
626
|
+
"configValue",
|
|
627
|
+
"provider",
|
|
628
|
+
"status",
|
|
629
|
+
"metadata",
|
|
630
|
+
"limit",
|
|
631
|
+
"cursor"
|
|
632
|
+
];
|
|
633
|
+
function tenantIdentityQuery(input) {
|
|
634
|
+
return {
|
|
635
|
+
tenantId: cleanRequiredString(input.tenantId, "tenantId"),
|
|
636
|
+
workspaceId: input.workspaceId,
|
|
637
|
+
principalId: input.principalId,
|
|
638
|
+
limit: input.limit,
|
|
639
|
+
cursor: input.cursor
|
|
640
|
+
};
|
|
641
|
+
}
|
|
642
|
+
function tenantIdentityBody(input, operation) {
|
|
643
|
+
return knownPayload(input, TENANT_IDENTITY_FIELDS, operation);
|
|
644
|
+
}
|
|
645
|
+
function createIdentityClient(config = {}) {
|
|
646
|
+
const gateway = createGatewayRequestClient(config);
|
|
647
|
+
const whoamiClient = createIdentityWhoamiClient(config);
|
|
648
|
+
const requestPrincipalWrite = (method, input, idempotencyKey) => gateway.request({
|
|
649
|
+
path: "/api/platform/v1/identity/principals",
|
|
650
|
+
method,
|
|
651
|
+
body: input,
|
|
652
|
+
idempotencyKey: idempotencyKey ?? randomIdempotencyKey()
|
|
653
|
+
});
|
|
654
|
+
const updatePrincipal = (input, idempotencyKey) => requestPrincipalWrite("PATCH", input, idempotencyKey);
|
|
655
|
+
const deleteKey = (keyId, input = {}, idempotencyKey) => gateway.request({
|
|
656
|
+
path: `/api/platform/v1/identity/keys/${encodeURIComponent(keyId)}/revoke`,
|
|
657
|
+
method: "POST",
|
|
658
|
+
body: input,
|
|
659
|
+
idempotencyKey: idempotencyKey ?? randomIdempotencyKey()
|
|
660
|
+
});
|
|
661
|
+
return {
|
|
662
|
+
/**
|
|
663
|
+
* Resolve the current authenticated identity summary.
|
|
664
|
+
*/
|
|
665
|
+
async whoami() {
|
|
666
|
+
return whoamiClient.whoami().then(
|
|
667
|
+
(response) => mapGatewayData(response, (data) => ({
|
|
668
|
+
principalId: data.principalId,
|
|
669
|
+
principalType: data.principalType,
|
|
670
|
+
tenantId: data.tenantId ?? null,
|
|
671
|
+
workspaceId: data.workspaceId ?? null,
|
|
672
|
+
scopes: Array.isArray(data.scopes) ? data.scopes : [],
|
|
673
|
+
roles: Array.isArray(data.roles) ? data.roles : [],
|
|
674
|
+
isPlatformAdmin: data.isPlatformAdmin === true,
|
|
675
|
+
isTenantAdmin: data.isTenantAdmin === true,
|
|
676
|
+
isWorkspaceAdmin: data.isWorkspaceAdmin === true,
|
|
677
|
+
authMode: data.authMode,
|
|
678
|
+
sessionId: data.sessionId,
|
|
679
|
+
delegatedBy: data.delegatedBy,
|
|
680
|
+
expiresAt: data.expiresAt
|
|
681
|
+
}))
|
|
682
|
+
);
|
|
683
|
+
},
|
|
684
|
+
/**
|
|
685
|
+
* List principals in the current identity scope.
|
|
686
|
+
*/
|
|
687
|
+
async listPrincipals(query = {}) {
|
|
688
|
+
return gateway.request({
|
|
689
|
+
path: `/api/platform/v1/identity/principals${toQueryString(query)}`
|
|
690
|
+
}).then(
|
|
691
|
+
(response) => mapGatewayData(
|
|
692
|
+
response,
|
|
693
|
+
(data) => createListResult(
|
|
694
|
+
Array.isArray(data) ? data : [],
|
|
695
|
+
"principals"
|
|
696
|
+
)
|
|
697
|
+
)
|
|
698
|
+
);
|
|
699
|
+
},
|
|
700
|
+
/**
|
|
701
|
+
* Create a principal.
|
|
702
|
+
*/
|
|
703
|
+
async createPrincipal(input, idempotencyKey) {
|
|
704
|
+
return requestPrincipalWrite("POST", input, idempotencyKey);
|
|
705
|
+
},
|
|
706
|
+
/**
|
|
707
|
+
* Update a principal.
|
|
708
|
+
*/
|
|
709
|
+
updatePrincipal,
|
|
710
|
+
/**
|
|
711
|
+
* @deprecated Use createPrincipal or updatePrincipal.
|
|
712
|
+
*/
|
|
713
|
+
upsertPrincipal: updatePrincipal,
|
|
714
|
+
/**
|
|
715
|
+
* List keys in the current identity scope.
|
|
716
|
+
*/
|
|
717
|
+
async listKeys(query = {}) {
|
|
718
|
+
return gateway.request({
|
|
719
|
+
path: `/api/platform/v1/identity/keys${toQueryString(query)}`
|
|
720
|
+
}).then(
|
|
721
|
+
(response) => mapGatewayData(
|
|
722
|
+
response,
|
|
723
|
+
(data) => createListResult(Array.isArray(data) ? data : [], "keys")
|
|
724
|
+
)
|
|
725
|
+
);
|
|
726
|
+
},
|
|
727
|
+
/**
|
|
728
|
+
* Create an API key.
|
|
729
|
+
*/
|
|
730
|
+
async createKey(input, idempotencyKey) {
|
|
731
|
+
return gateway.request({
|
|
732
|
+
path: "/api/platform/v1/identity/keys",
|
|
733
|
+
method: "POST",
|
|
734
|
+
body: input,
|
|
735
|
+
idempotencyKey: idempotencyKey ?? randomIdempotencyKey()
|
|
736
|
+
});
|
|
737
|
+
},
|
|
738
|
+
/**
|
|
739
|
+
* Rotate an API key.
|
|
740
|
+
*/
|
|
741
|
+
async rotateKey(keyId, input = {}, idempotencyKey) {
|
|
742
|
+
return gateway.request({
|
|
743
|
+
path: `/api/platform/v1/identity/keys/${encodeURIComponent(keyId)}/rotate`,
|
|
744
|
+
method: "POST",
|
|
745
|
+
body: input,
|
|
746
|
+
idempotencyKey: idempotencyKey ?? randomIdempotencyKey()
|
|
747
|
+
});
|
|
748
|
+
},
|
|
749
|
+
/**
|
|
750
|
+
* Delete an API key by revoking it.
|
|
751
|
+
*/
|
|
752
|
+
deleteKey,
|
|
753
|
+
/**
|
|
754
|
+
* @deprecated Use deleteKey.
|
|
755
|
+
*/
|
|
756
|
+
revokeKey: deleteKey,
|
|
757
|
+
/**
|
|
758
|
+
* Search Clerk users by email or display attributes.
|
|
759
|
+
*/
|
|
760
|
+
async searchClerkUsers(q) {
|
|
761
|
+
return gateway.request({
|
|
762
|
+
path: `/api/platform/v1/identity/clerk-users${toQueryString({ q })}`
|
|
763
|
+
});
|
|
764
|
+
},
|
|
765
|
+
async getTenantConfig(input) {
|
|
766
|
+
return gateway.request({
|
|
767
|
+
path: `/api/platform/v1/identity/tenant-config${toQueryString(
|
|
768
|
+
tenantIdentityQuery(input)
|
|
769
|
+
)}`
|
|
770
|
+
});
|
|
771
|
+
},
|
|
772
|
+
async updateTenantConfig(input, idempotencyKey) {
|
|
773
|
+
cleanRequiredString(input.tenantId, "tenantId");
|
|
774
|
+
return gateway.request({
|
|
775
|
+
path: "/api/platform/v1/identity/tenant-config",
|
|
776
|
+
method: "PATCH",
|
|
777
|
+
body: tenantIdentityBody(
|
|
778
|
+
input,
|
|
779
|
+
"identity.updateTenantConfig"
|
|
780
|
+
),
|
|
781
|
+
idempotencyKey: idempotencyKey ?? randomIdempotencyKey()
|
|
782
|
+
});
|
|
783
|
+
},
|
|
784
|
+
async listIntegrations(input) {
|
|
785
|
+
return gateway.request({
|
|
786
|
+
path: `/api/platform/v1/identity/integrations${toQueryString(
|
|
787
|
+
tenantIdentityQuery(input)
|
|
788
|
+
)}`
|
|
789
|
+
}).then(
|
|
790
|
+
(response) => mapGatewayData(
|
|
791
|
+
response,
|
|
792
|
+
(data) => listResultFromEnvelope(
|
|
793
|
+
data,
|
|
794
|
+
"integrations"
|
|
795
|
+
)
|
|
796
|
+
)
|
|
797
|
+
);
|
|
798
|
+
},
|
|
799
|
+
async upsertIntegration(input, idempotencyKey) {
|
|
800
|
+
cleanRequiredString(input.tenantId, "tenantId");
|
|
801
|
+
cleanRequiredString(input.integrationKey, "integrationKey");
|
|
802
|
+
return gateway.request({
|
|
803
|
+
path: "/api/platform/v1/identity/integrations",
|
|
804
|
+
method: "PUT",
|
|
805
|
+
body: tenantIdentityBody(
|
|
806
|
+
input,
|
|
807
|
+
"identity.upsertIntegration"
|
|
808
|
+
),
|
|
809
|
+
idempotencyKey: idempotencyKey ?? randomIdempotencyKey()
|
|
810
|
+
});
|
|
811
|
+
},
|
|
812
|
+
async listSecrets(input) {
|
|
813
|
+
return gateway.request({
|
|
814
|
+
path: `/api/platform/v1/identity/secrets${toQueryString(
|
|
815
|
+
tenantIdentityQuery(input)
|
|
816
|
+
)}`
|
|
817
|
+
}).then(
|
|
818
|
+
(response) => mapGatewayData(
|
|
819
|
+
response,
|
|
820
|
+
(data) => listResultFromEnvelope(
|
|
821
|
+
data,
|
|
822
|
+
"secrets"
|
|
823
|
+
)
|
|
824
|
+
)
|
|
825
|
+
);
|
|
826
|
+
},
|
|
827
|
+
async putSecretReference(input, idempotencyKey) {
|
|
828
|
+
cleanRequiredString(input.tenantId, "tenantId");
|
|
829
|
+
cleanRequiredString(input.secretRef, "secretRef");
|
|
830
|
+
return gateway.request({
|
|
831
|
+
path: "/api/platform/v1/identity/secrets",
|
|
832
|
+
method: "PUT",
|
|
833
|
+
body: tenantIdentityBody(
|
|
834
|
+
input,
|
|
835
|
+
"identity.putSecretReference"
|
|
836
|
+
),
|
|
837
|
+
idempotencyKey: idempotencyKey ?? randomIdempotencyKey()
|
|
838
|
+
});
|
|
839
|
+
},
|
|
840
|
+
async evaluatePolicy(input, idempotencyKey) {
|
|
841
|
+
cleanRequiredString(input.tenantId, "tenantId");
|
|
842
|
+
cleanRequiredString(input.policySubject, "policySubject");
|
|
843
|
+
cleanRequiredString(input.policyAction, "policyAction");
|
|
844
|
+
cleanRequiredString(input.policyResource, "policyResource");
|
|
845
|
+
return gateway.request({
|
|
846
|
+
path: "/api/platform/v1/identity/policy/evaluate",
|
|
847
|
+
method: "POST",
|
|
848
|
+
body: tenantIdentityBody(
|
|
849
|
+
input,
|
|
850
|
+
"identity.evaluatePolicy"
|
|
851
|
+
),
|
|
852
|
+
idempotencyKey: idempotencyKey ?? randomIdempotencyKey()
|
|
853
|
+
});
|
|
854
|
+
},
|
|
855
|
+
async recordPolicyDecision(input, idempotencyKey) {
|
|
856
|
+
cleanRequiredString(input.tenantId, "tenantId");
|
|
857
|
+
cleanRequiredString(input.decision, "decision");
|
|
858
|
+
return gateway.request({
|
|
859
|
+
path: "/api/platform/v1/identity/policy/decisions",
|
|
860
|
+
method: "POST",
|
|
861
|
+
body: tenantIdentityBody(
|
|
862
|
+
input,
|
|
863
|
+
"identity.recordPolicyDecision"
|
|
864
|
+
),
|
|
865
|
+
idempotencyKey: idempotencyKey ?? randomIdempotencyKey()
|
|
866
|
+
});
|
|
867
|
+
}
|
|
868
|
+
};
|
|
869
|
+
}
|
|
870
|
+
|
|
871
|
+
// src/accessControl.ts
|
|
872
|
+
var LucernAccessControlError = class extends LucernSdkAuthContextError {
|
|
873
|
+
policyDecision;
|
|
874
|
+
constructor(reason, message, policyDecision) {
|
|
875
|
+
super(reason, message);
|
|
876
|
+
this.name = "LucernAccessControlError";
|
|
877
|
+
this.policyDecision = policyDecision;
|
|
878
|
+
}
|
|
879
|
+
};
|
|
880
|
+
function cleanString2(value) {
|
|
881
|
+
const normalized = value?.trim();
|
|
882
|
+
return normalized ? normalized : void 0;
|
|
883
|
+
}
|
|
884
|
+
function cleanStringList2(values) {
|
|
885
|
+
if (!values) {
|
|
886
|
+
return [];
|
|
887
|
+
}
|
|
888
|
+
return [
|
|
889
|
+
...new Set(
|
|
890
|
+
values.map((value) => value.trim()).filter((value) => value.length > 0)
|
|
891
|
+
)
|
|
892
|
+
];
|
|
893
|
+
}
|
|
894
|
+
function requireString2(value, reason, label) {
|
|
895
|
+
const normalized = cleanString2(value);
|
|
896
|
+
if (!normalized) {
|
|
897
|
+
throw new LucernAccessControlError(
|
|
898
|
+
reason,
|
|
899
|
+
`Lucern SDK access control requires ${label}.`
|
|
900
|
+
);
|
|
901
|
+
}
|
|
902
|
+
return normalized;
|
|
903
|
+
}
|
|
904
|
+
function normalizePrincipalType(principalType) {
|
|
905
|
+
if (principalType === "agent") {
|
|
906
|
+
return "agent";
|
|
907
|
+
}
|
|
908
|
+
if (principalType === "service") {
|
|
909
|
+
return "service";
|
|
910
|
+
}
|
|
911
|
+
return "human";
|
|
912
|
+
}
|
|
913
|
+
function aliasKey(alias) {
|
|
914
|
+
return `${alias.provider}:${alias.providerProjectId ?? ""}:${alias.externalSubjectId}`;
|
|
915
|
+
}
|
|
916
|
+
function normalizeAliases(input, canonicalClerkUserId) {
|
|
917
|
+
const aliases = /* @__PURE__ */ new Map();
|
|
918
|
+
for (const alias of input ?? []) {
|
|
919
|
+
const externalSubjectId = cleanString2(alias.externalSubjectId);
|
|
920
|
+
if (!externalSubjectId) {
|
|
921
|
+
continue;
|
|
922
|
+
}
|
|
923
|
+
const normalized = {
|
|
924
|
+
provider: cleanString2(alias.provider) ?? "clerk",
|
|
925
|
+
providerProjectId: cleanString2(alias.providerProjectId),
|
|
926
|
+
externalSubjectId,
|
|
927
|
+
status: cleanString2(alias.status)
|
|
928
|
+
};
|
|
929
|
+
aliases.set(aliasKey(normalized), normalized);
|
|
930
|
+
}
|
|
931
|
+
if (canonicalClerkUserId) {
|
|
932
|
+
const canonicalAlias = {
|
|
933
|
+
provider: "clerk",
|
|
934
|
+
externalSubjectId: canonicalClerkUserId,
|
|
935
|
+
status: "active"
|
|
936
|
+
};
|
|
937
|
+
aliases.set(aliasKey(canonicalAlias), canonicalAlias);
|
|
938
|
+
}
|
|
939
|
+
return [...aliases.values()];
|
|
940
|
+
}
|
|
941
|
+
function isKnownClerkSubject(args) {
|
|
942
|
+
if (args.clerkId === args.canonicalClerkUserId) {
|
|
943
|
+
return true;
|
|
944
|
+
}
|
|
945
|
+
return args.aliases.some(
|
|
946
|
+
(alias) => alias.provider === "clerk" && alias.externalSubjectId === args.clerkId
|
|
947
|
+
);
|
|
948
|
+
}
|
|
949
|
+
function authContextToPrincipalInput(input) {
|
|
950
|
+
const normalized = normalizeCanonicalLucernAuthContext(input);
|
|
951
|
+
return {
|
|
952
|
+
principalId: normalized.principalId,
|
|
953
|
+
principalType: normalized.principalType,
|
|
954
|
+
canonicalClerkUserId: normalized.clerkId,
|
|
955
|
+
clerkId: normalized.clerkId,
|
|
956
|
+
tenantId: normalized.tenantId,
|
|
957
|
+
workspaceId: normalized.workspaceId,
|
|
958
|
+
roles: normalized.roles,
|
|
959
|
+
scopes: normalized.scopes
|
|
960
|
+
};
|
|
961
|
+
}
|
|
962
|
+
function isAuthContextInput(input) {
|
|
963
|
+
return "authMode" in input || "permit" in input || "delegationChain" in input;
|
|
964
|
+
}
|
|
965
|
+
function normalizeCanonicalPrincipalIdentity(input, options = {}) {
|
|
966
|
+
const principalInput = isAuthContextInput(input) ? authContextToPrincipalInput(input) : input;
|
|
967
|
+
const principalId = requireString2(
|
|
968
|
+
principalInput.principalId,
|
|
969
|
+
"principal_missing",
|
|
970
|
+
"principalId"
|
|
971
|
+
);
|
|
972
|
+
const principalType = normalizePrincipalType(principalInput.principalType);
|
|
973
|
+
const observedClerkId = cleanString2(options.observedClerkId);
|
|
974
|
+
const canonicalClerkUserId = cleanString2(principalInput.canonicalClerkUserId) ?? cleanString2(principalInput.clerkId);
|
|
975
|
+
if (principalType === "human" && !canonicalClerkUserId) {
|
|
976
|
+
throw new LucernAccessControlError(
|
|
977
|
+
"clerk_alias_missing",
|
|
978
|
+
"Human principals require one canonical Clerk user id."
|
|
979
|
+
);
|
|
980
|
+
}
|
|
981
|
+
const aliases = normalizeAliases(
|
|
982
|
+
principalInput.clerkIdentityAliases,
|
|
983
|
+
canonicalClerkUserId
|
|
984
|
+
);
|
|
985
|
+
if (observedClerkId && !isKnownClerkSubject({
|
|
986
|
+
clerkId: observedClerkId,
|
|
987
|
+
canonicalClerkUserId,
|
|
988
|
+
aliases
|
|
989
|
+
})) {
|
|
990
|
+
throw new LucernAccessControlError(
|
|
991
|
+
"clerk_alias_unrecognized",
|
|
992
|
+
"Observed Clerk user id is not attached to the canonical Lucern principal."
|
|
993
|
+
);
|
|
994
|
+
}
|
|
995
|
+
return {
|
|
996
|
+
principalId,
|
|
997
|
+
principalType,
|
|
998
|
+
canonicalClerkUserId,
|
|
999
|
+
clerkIdentityAliases: aliases,
|
|
1000
|
+
tenantId: cleanString2(principalInput.tenantId),
|
|
1001
|
+
workspaceId: cleanString2(principalInput.workspaceId),
|
|
1002
|
+
roles: cleanStringList2(principalInput.roles),
|
|
1003
|
+
scopes: cleanStringList2(principalInput.scopes)
|
|
1004
|
+
};
|
|
1005
|
+
}
|
|
1006
|
+
function formatPermitResource(resource) {
|
|
1007
|
+
if (typeof resource === "string") {
|
|
1008
|
+
return requireString2(resource, "policy_denied", "policyResource");
|
|
1009
|
+
}
|
|
1010
|
+
const type = requireString2(resource.type, "policy_denied", "resource.type");
|
|
1011
|
+
const key = requireString2(resource.key, "policy_denied", "resource.key");
|
|
1012
|
+
return key.startsWith(`${type}:`) ? key : `${type}:${key}`;
|
|
1013
|
+
}
|
|
1014
|
+
function resourceRequiresWorkspace(resource) {
|
|
1015
|
+
if (typeof resource === "string") {
|
|
1016
|
+
return !resource.startsWith("tenant:");
|
|
1017
|
+
}
|
|
1018
|
+
return resource.type !== "tenant";
|
|
1019
|
+
}
|
|
1020
|
+
function buildPolicyInput(identity, input) {
|
|
1021
|
+
const tenantId = requireString2(
|
|
1022
|
+
input.tenantId ?? identity.tenantId,
|
|
1023
|
+
"tenant_missing",
|
|
1024
|
+
"tenantId"
|
|
1025
|
+
);
|
|
1026
|
+
const workspaceId = cleanString2(input.workspaceId ?? identity.workspaceId);
|
|
1027
|
+
if (resourceRequiresWorkspace(input.resource) && !workspaceId) {
|
|
1028
|
+
throw new LucernAccessControlError(
|
|
1029
|
+
"workspace_missing",
|
|
1030
|
+
"Workspace-scoped Permit checks require workspaceId."
|
|
1031
|
+
);
|
|
1032
|
+
}
|
|
1033
|
+
return {
|
|
1034
|
+
tenantId,
|
|
1035
|
+
workspaceId,
|
|
1036
|
+
principalId: identity.principalId,
|
|
1037
|
+
policySubject: identity.principalId,
|
|
1038
|
+
policyAction: requireString2(input.action, "policy_denied", "policyAction"),
|
|
1039
|
+
policyResource: formatPermitResource(input.resource),
|
|
1040
|
+
metadata: input.context
|
|
1041
|
+
};
|
|
1042
|
+
}
|
|
1043
|
+
async function resolveConfiguredPrincipalInput(authContext) {
|
|
1044
|
+
if (typeof authContext === "function") {
|
|
1045
|
+
return await authContext();
|
|
1046
|
+
}
|
|
1047
|
+
return authContext;
|
|
1048
|
+
}
|
|
1049
|
+
function assertPermitAllowed(decision) {
|
|
1050
|
+
if (decision.decision !== "allow") {
|
|
1051
|
+
throw new LucernAccessControlError(
|
|
1052
|
+
decision.decision === "deny" ? "policy_denied" : "policy_unknown",
|
|
1053
|
+
`Permit denied ${decision.policyAction} on ${decision.policyResource}.`,
|
|
1054
|
+
decision
|
|
1055
|
+
);
|
|
1056
|
+
}
|
|
1057
|
+
}
|
|
1058
|
+
function createAccessControlClient(config = {}) {
|
|
1059
|
+
const identityClient = createIdentityClient(config);
|
|
1060
|
+
async function resolveIdentity(input, observedClerkId) {
|
|
1061
|
+
const identityInput = input ?? await resolveConfiguredPrincipalInput(config.authContext);
|
|
1062
|
+
if (!identityInput) {
|
|
1063
|
+
throw new LucernAccessControlError(
|
|
1064
|
+
"principal_missing",
|
|
1065
|
+
"Lucern SDK access control requires a canonical principal identity."
|
|
1066
|
+
);
|
|
1067
|
+
}
|
|
1068
|
+
return normalizeCanonicalPrincipalIdentity(identityInput, {
|
|
1069
|
+
observedClerkId
|
|
1070
|
+
});
|
|
1071
|
+
}
|
|
1072
|
+
async function checkAccess(input, idempotencyKey) {
|
|
1073
|
+
const identity = await resolveIdentity(input.identity, input.observedClerkId);
|
|
1074
|
+
const policyInput = buildPolicyInput(identity, input);
|
|
1075
|
+
try {
|
|
1076
|
+
const response = await identityClient.evaluatePolicy(
|
|
1077
|
+
policyInput,
|
|
1078
|
+
idempotencyKey
|
|
1079
|
+
);
|
|
1080
|
+
return {
|
|
1081
|
+
identity,
|
|
1082
|
+
policyInput,
|
|
1083
|
+
decision: response.data
|
|
1084
|
+
};
|
|
1085
|
+
} catch (error) {
|
|
1086
|
+
if (error instanceof LucernSdkAuthContextError) {
|
|
1087
|
+
throw error;
|
|
1088
|
+
}
|
|
1089
|
+
throw new LucernAccessControlError(
|
|
1090
|
+
"policy_unavailable",
|
|
1091
|
+
"Permit policy check failed closed before an allow decision was returned."
|
|
1092
|
+
);
|
|
1093
|
+
}
|
|
1094
|
+
}
|
|
1095
|
+
async function requireAccess(input, idempotencyKey) {
|
|
1096
|
+
const result = await checkAccess(input, idempotencyKey);
|
|
1097
|
+
assertPermitAllowed(result.decision);
|
|
1098
|
+
return result;
|
|
1099
|
+
}
|
|
1100
|
+
async function canAccess(input, idempotencyKey) {
|
|
1101
|
+
try {
|
|
1102
|
+
await requireAccess(input, idempotencyKey);
|
|
1103
|
+
return true;
|
|
1104
|
+
} catch {
|
|
1105
|
+
return false;
|
|
1106
|
+
}
|
|
1107
|
+
}
|
|
1108
|
+
return {
|
|
1109
|
+
normalizePrincipal: normalizeCanonicalPrincipalIdentity,
|
|
1110
|
+
checkAccess,
|
|
1111
|
+
requireAccess,
|
|
1112
|
+
canAccess
|
|
1113
|
+
};
|
|
1114
|
+
}
|
|
1115
|
+
|
|
1116
|
+
export { LucernAccessControlError, assertPermitAllowed, createAccessControlClient, formatPermitResource, normalizeCanonicalPrincipalIdentity };
|
|
1117
|
+
//# sourceMappingURL=accessControl.js.map
|
|
1118
|
+
//# sourceMappingURL=accessControl.js.map
|