@haakco/custd-sdk 0.0.0-stage → 2.4.0
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 +412 -2
- package/dist/admin-client-setup.d.ts +100 -0
- package/dist/admin-client-setup.js +398 -0
- package/dist/admin-data-labels.d.ts +124 -0
- package/dist/admin-data-labels.js +51 -0
- package/dist/admin-offboarding.d.ts +109 -0
- package/dist/admin-offboarding.js +108 -0
- package/dist/admin-predictions.d.ts +147 -0
- package/dist/admin-predictions.js +83 -0
- package/dist/admin-privacy-erasures.d.ts +62 -0
- package/dist/admin-privacy-erasures.js +72 -0
- package/dist/admin-retention.d.ts +51 -0
- package/dist/admin-retention.js +35 -0
- package/dist/admin-subject-exports.d.ts +48 -0
- package/dist/admin-subject-exports.js +28 -0
- package/dist/admin-tenant-storage.d.ts +27 -0
- package/dist/admin-tenant-storage.js +25 -0
- package/dist/admin-timeplans.d.ts +238 -0
- package/dist/admin-timeplans.js +146 -0
- package/dist/analytics-events.d.ts +85 -0
- package/dist/analytics-events.js +40 -0
- package/dist/backend-lifecycle.d.ts +85 -0
- package/dist/backend-lifecycle.js +212 -0
- package/dist/browser-manifest.json +7 -0
- package/dist/browser-script-BvgjdZSO.js +429 -0
- package/dist/browser-script.d.ts +1 -0
- package/dist/browser-script.js +5 -0
- package/dist/browser-tracker.d.ts +47 -0
- package/dist/browser-tracker.js +453 -0
- package/dist/browser.d.ts +1 -0
- package/dist/browser.js +1 -0
- package/dist/fixtures.d.ts +10 -0
- package/dist/fixtures.js +57 -0
- package/dist/index.d.ts +1310 -0
- package/dist/index.js +1706 -0
- package/dist/mobile-adapter.d.ts +25 -0
- package/dist/mobile-adapter.js +57 -0
- package/dist/mobile-context.d.ts +32 -0
- package/dist/mobile-context.js +156 -0
- package/dist/mobile-queue.d.ts +22 -0
- package/dist/mobile-queue.js +73 -0
- package/dist/oauth.d.ts +1 -0
- package/dist/oauth.js +8 -0
- package/dist/reporting-state.d.ts +46 -0
- package/dist/reporting-state.js +76 -0
- package/dist/runtime-readiness.d.ts +30 -0
- package/dist/runtime-readiness.js +150 -0
- package/dist/version.d.ts +10 -0
- package/dist/version.js +10 -0
- package/package.json +46 -4
package/dist/index.js
ADDED
|
@@ -0,0 +1,1706 @@
|
|
|
1
|
+
import { ClientSetupClient } from "./admin-client-setup.js";
|
|
2
|
+
import { DataLabelAdminClient } from "./admin-data-labels.js";
|
|
3
|
+
import { OffboardingClient } from "./admin-offboarding.js";
|
|
4
|
+
import { PredictionAdminClient } from "./admin-predictions.js";
|
|
5
|
+
import { PrivacyErasureClient } from "./admin-privacy-erasures.js";
|
|
6
|
+
import { RetentionClient } from "./admin-retention.js";
|
|
7
|
+
import { SubjectExportClient } from "./admin-subject-exports.js";
|
|
8
|
+
import { TenantStorageClient } from "./admin-tenant-storage.js";
|
|
9
|
+
import { TimePlanAdminClient } from "./admin-timeplans.js";
|
|
10
|
+
import { AnalyticsEventClient } from "./analytics-events.js";
|
|
11
|
+
import { BackendLifecycleClient } from "./backend-lifecycle.js";
|
|
12
|
+
import { basicAuthorization } from "./oauth.js";
|
|
13
|
+
import { SDK_IDENTITY } from "./version.js";
|
|
14
|
+
export { ClientSetupClient, validateClientSetupManifest, } from "./admin-client-setup.js";
|
|
15
|
+
export { DataLabelAdminClient, } from "./admin-data-labels.js";
|
|
16
|
+
export { OffboardingClient, } from "./admin-offboarding.js";
|
|
17
|
+
export { PredictionAdminClient, } from "./admin-predictions.js";
|
|
18
|
+
export { PrivacyErasureClient, PrivacyErasureError, } from "./admin-privacy-erasures.js";
|
|
19
|
+
export { RetentionClient, } from "./admin-retention.js";
|
|
20
|
+
export { SubjectExportClient, } from "./admin-subject-exports.js";
|
|
21
|
+
export { TenantStorageClient, } from "./admin-tenant-storage.js";
|
|
22
|
+
export { TimePlanAdminClient, validateTimePlanDefinition, } from "./admin-timeplans.js";
|
|
23
|
+
export { ANALYTICS_MAX_LABEL_FILTERS, AnalyticsEventClient, } from "./analytics-events.js";
|
|
24
|
+
export { BackendLifecycleClient, createVerifiedOffboardingExportReceiver, } from "./backend-lifecycle.js";
|
|
25
|
+
export { classifyReportingData, getReportingViewState, reportingQueryKey, } from "./reporting-state.js";
|
|
26
|
+
export { checkRuntimeReadiness, } from "./runtime-readiness.js";
|
|
27
|
+
export { createMobileAsyncQueueStorage, createMobileFlushTriggers, } from "./mobile-adapter.js";
|
|
28
|
+
export { createMobileEvent, } from "./mobile-context.js";
|
|
29
|
+
export { AsyncEventQueue } from "./mobile-queue.js";
|
|
30
|
+
export class AdminWorkflowError extends Error {
|
|
31
|
+
constructor(status, reason, code, safeNextAction) {
|
|
32
|
+
let message = `custd: ${reason || "admin workflow request failed"} (status ${status})`;
|
|
33
|
+
if (code)
|
|
34
|
+
message += ` [code=${code}]`;
|
|
35
|
+
if (safeNextAction)
|
|
36
|
+
message += ` [safeNextAction=${safeNextAction}]`;
|
|
37
|
+
super(message);
|
|
38
|
+
this.status = status;
|
|
39
|
+
this.reason = reason;
|
|
40
|
+
this.code = code;
|
|
41
|
+
this.safeNextAction = safeNextAction;
|
|
42
|
+
this.name = "AdminWorkflowError";
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
export class CustdRequestError extends Error {
|
|
46
|
+
constructor(status, code, retryability, nextAction, problem, options) {
|
|
47
|
+
super(`custd: request failed [code=${code}]`);
|
|
48
|
+
this.status = status;
|
|
49
|
+
this.code = code;
|
|
50
|
+
this.retryability = retryability;
|
|
51
|
+
this.nextAction = nextAction;
|
|
52
|
+
this.problem = problem;
|
|
53
|
+
this.name = "CustdRequestError";
|
|
54
|
+
this.cause = options?.cause;
|
|
55
|
+
}
|
|
56
|
+
get unavailable() {
|
|
57
|
+
return (this.code === "oauth_unavailable" ||
|
|
58
|
+
this.status === null ||
|
|
59
|
+
this.status === 429 ||
|
|
60
|
+
(this.status !== null && this.status >= 500));
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
function publicAdminSite(site) {
|
|
64
|
+
const { writeKey: _writeKey, ...safeSite } = site;
|
|
65
|
+
return safeSite;
|
|
66
|
+
}
|
|
67
|
+
export class MemoryQueueStorage {
|
|
68
|
+
constructor() {
|
|
69
|
+
this.events = [];
|
|
70
|
+
}
|
|
71
|
+
load() {
|
|
72
|
+
return [...this.events];
|
|
73
|
+
}
|
|
74
|
+
save(events) {
|
|
75
|
+
this.events = [...events];
|
|
76
|
+
}
|
|
77
|
+
clear() {
|
|
78
|
+
this.events = [];
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
export class LocalStorageQueueStorage {
|
|
82
|
+
constructor(key = "custd_event_queue") {
|
|
83
|
+
this.key = key;
|
|
84
|
+
}
|
|
85
|
+
load() {
|
|
86
|
+
if (typeof localStorage === "undefined") {
|
|
87
|
+
return [];
|
|
88
|
+
}
|
|
89
|
+
const raw = localStorage.getItem(this.key);
|
|
90
|
+
if (!raw) {
|
|
91
|
+
return [];
|
|
92
|
+
}
|
|
93
|
+
try {
|
|
94
|
+
const parsed = JSON.parse(raw);
|
|
95
|
+
if (Array.isArray(parsed)) {
|
|
96
|
+
return parsed;
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
catch {
|
|
100
|
+
return [];
|
|
101
|
+
}
|
|
102
|
+
return [];
|
|
103
|
+
}
|
|
104
|
+
save(events) {
|
|
105
|
+
if (typeof localStorage === "undefined") {
|
|
106
|
+
return;
|
|
107
|
+
}
|
|
108
|
+
localStorage.setItem(this.key, JSON.stringify(events));
|
|
109
|
+
}
|
|
110
|
+
clear() {
|
|
111
|
+
if (typeof localStorage === "undefined") {
|
|
112
|
+
return;
|
|
113
|
+
}
|
|
114
|
+
localStorage.removeItem(this.key);
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
export class CustdClient {
|
|
118
|
+
constructor(config) {
|
|
119
|
+
this.queue = [];
|
|
120
|
+
this.onlineHandler = null;
|
|
121
|
+
this.batchTimer = null;
|
|
122
|
+
this.removeFlushTriggers = [];
|
|
123
|
+
this.oauthToken = null;
|
|
124
|
+
this.config = config;
|
|
125
|
+
this.baseUrl = config.baseUrl.replace(/\/$/, "");
|
|
126
|
+
const fetchImpl = config.fetch ?? globalThis.fetch;
|
|
127
|
+
this.fetchImpl = (input, init) => fetchImpl(input, init);
|
|
128
|
+
assertSecureOrLocalHTTP(this.baseUrl, "baseUrl");
|
|
129
|
+
if (config.oauth) {
|
|
130
|
+
assertSecureOrLocalHTTP(config.oauth.tokenUrl, "tokenUrl");
|
|
131
|
+
this.getToken = (options) => this.fetchOAuthToken(config.oauth, options);
|
|
132
|
+
}
|
|
133
|
+
else if (config.getToken) {
|
|
134
|
+
this.getToken = config.getToken;
|
|
135
|
+
}
|
|
136
|
+
else {
|
|
137
|
+
throw new Error("custd: getToken or oauth config is required");
|
|
138
|
+
}
|
|
139
|
+
// The SDK's own identity is authoritative: a caller may add default
|
|
140
|
+
// headers, but cannot accidentally drop the release Custd records.
|
|
141
|
+
this.defaultHeaders = { ...(config.defaultHeaders ?? {}), "X-Custd-Sdk": SDK_IDENTITY };
|
|
142
|
+
this.retry = normalizeRetryOptions(config.retry);
|
|
143
|
+
this.batch = config.batch;
|
|
144
|
+
this.queueEnabled = config.queue?.enabled ?? config.batch != null;
|
|
145
|
+
this.queueStorage = config.queue?.storage ?? new MemoryQueueStorage();
|
|
146
|
+
this.maxQueueSize = config.queue?.maxQueueSize ?? 1000;
|
|
147
|
+
this.flushOnOnline = config.queue?.flushOnOnline ?? true;
|
|
148
|
+
this.compressionEnabled = config.compression?.enabled ?? true;
|
|
149
|
+
this.compressionThresholdBytes = config.compression?.thresholdBytes ?? 1024;
|
|
150
|
+
this.admin = new AdminNamespace((method, path, body, options) => this.adminRequest(method, path, body, options), (method, path, body, options) => this.apiRequest(method, path, body, options), (path, options) => this.offboardingDownload(path, options), (path, options) => this.auditExportDownload(path, options));
|
|
151
|
+
this.provisioning = new ProvisioningNamespace((method, path, body, options) => this.apiRequest(method, path, body, options));
|
|
152
|
+
this.reporting = new ReportingNamespace((method, path, body, options) => this.apiRequest(method, path, body, options), (path, options) => this.apiDownload(path, options));
|
|
153
|
+
this.schemas = new SchemaNamespace((method, path, body) => this.apiRequest(method, path, body));
|
|
154
|
+
this.analytics = new AnalyticsEventClient((method, path, body, options) => this.apiRequest(method, path, body, options));
|
|
155
|
+
if (this.queueEnabled) {
|
|
156
|
+
this.queue = this.queueStorage.load();
|
|
157
|
+
}
|
|
158
|
+
if (this.batch?.flushIntervalMs && this.batch.flushIntervalMs > 0) {
|
|
159
|
+
this.batchTimer = setInterval(() => {
|
|
160
|
+
void this.flush();
|
|
161
|
+
}, this.batch.flushIntervalMs);
|
|
162
|
+
}
|
|
163
|
+
if (this.flushOnOnline && typeof window !== "undefined" && typeof window.addEventListener === "function") {
|
|
164
|
+
this.onlineHandler = () => void this.flush();
|
|
165
|
+
window.addEventListener("online", this.onlineHandler);
|
|
166
|
+
}
|
|
167
|
+
this.removeFlushTriggers = (config.queue?.flushTriggers ?? []).map((install) => install(() => this.flush()));
|
|
168
|
+
}
|
|
169
|
+
// fromProvisionedProducer builds an event-producing client directly from a
|
|
170
|
+
// provisioned producer bundle, hiding the OAuth wiring.
|
|
171
|
+
static fromProvisionedProducer(credentials) {
|
|
172
|
+
if (!credentials.clientSecret) {
|
|
173
|
+
throw new Error("custd: provisioned producer bundle is missing the client secret");
|
|
174
|
+
}
|
|
175
|
+
return new CustdClient({
|
|
176
|
+
baseUrl: credentials.baseUrl,
|
|
177
|
+
oauth: {
|
|
178
|
+
clientId: credentials.clientId,
|
|
179
|
+
clientSecret: credentials.clientSecret,
|
|
180
|
+
tokenUrl: credentials.tokenUrl,
|
|
181
|
+
audience: credentials.audience,
|
|
182
|
+
scopes: credentials.scopes,
|
|
183
|
+
},
|
|
184
|
+
});
|
|
185
|
+
}
|
|
186
|
+
static fromBrokerEnv(env, options = {}) {
|
|
187
|
+
const baseUrl = options.baseUrl ?? brokerBaseUrl(env);
|
|
188
|
+
return new CustdClient({
|
|
189
|
+
...options,
|
|
190
|
+
baseUrl,
|
|
191
|
+
oauth: {
|
|
192
|
+
clientId: requireBrokerEnv(env, "CUSTD_PROVISIONING_CLIENT_ID", "PROVISIONING_CLIENT_ID"),
|
|
193
|
+
clientSecret: requireBrokerEnv(env, "CUSTD_PROVISIONING_CLIENT_SECRET", "PROVISIONING_CLIENT_SECRET"),
|
|
194
|
+
tokenUrl: requireBrokerEnv(env, "CUSTD_PROVISIONING_TOKEN_URL", "PROVISIONING_TOKEN_URL"),
|
|
195
|
+
audience: brokerEnvValue(env, "CUSTD_PROVISIONING_AUDIENCE", "PROVISIONING_AUDIENCE"),
|
|
196
|
+
scopes: options.scopes ?? ["admin", "producers.provision"],
|
|
197
|
+
},
|
|
198
|
+
});
|
|
199
|
+
}
|
|
200
|
+
async fetchOAuthToken(config, options) {
|
|
201
|
+
const now = Date.now();
|
|
202
|
+
if (this.oauthToken && this.oauthToken.expiresAtMs > now + 30000) {
|
|
203
|
+
return this.oauthToken.value;
|
|
204
|
+
}
|
|
205
|
+
const body = new URLSearchParams();
|
|
206
|
+
body.set("grant_type", "client_credentials");
|
|
207
|
+
if (config.audience) {
|
|
208
|
+
body.set("audience", config.audience);
|
|
209
|
+
}
|
|
210
|
+
if (config.scopes && config.scopes.length > 0) {
|
|
211
|
+
body.set("scope", config.scopes.join(" "));
|
|
212
|
+
}
|
|
213
|
+
let response;
|
|
214
|
+
try {
|
|
215
|
+
response = await this.fetchImpl(config.tokenUrl, {
|
|
216
|
+
method: "POST",
|
|
217
|
+
headers: {
|
|
218
|
+
"Content-Type": "application/x-www-form-urlencoded",
|
|
219
|
+
Authorization: basicAuthorization(config.clientId, config.clientSecret),
|
|
220
|
+
},
|
|
221
|
+
body,
|
|
222
|
+
signal: options?.signal,
|
|
223
|
+
});
|
|
224
|
+
if (!response.ok) {
|
|
225
|
+
const requestError = await responseRequestError(response, "oauth_unavailable");
|
|
226
|
+
if (requestError.code !== "oauth_unavailable") {
|
|
227
|
+
throw new CustdRequestError(requestError.status, "oauth_unavailable", requestError.retryability, requestError.nextAction, requestError.problem);
|
|
228
|
+
}
|
|
229
|
+
throw requestError;
|
|
230
|
+
}
|
|
231
|
+
const token = (await response.json());
|
|
232
|
+
if (typeof token?.access_token !== "string" || token.access_token.trim() === "") {
|
|
233
|
+
throw new Error("custd: token response missing access_token");
|
|
234
|
+
}
|
|
235
|
+
this.oauthToken = {
|
|
236
|
+
value: token.access_token,
|
|
237
|
+
expiresAtMs: now + Math.max(0, token.expires_in ?? 300) * 1000,
|
|
238
|
+
};
|
|
239
|
+
return token.access_token;
|
|
240
|
+
}
|
|
241
|
+
catch (error) {
|
|
242
|
+
if (error instanceof CustdRequestError)
|
|
243
|
+
throw error;
|
|
244
|
+
if (error instanceof Error && error.name === "AbortError")
|
|
245
|
+
throw error;
|
|
246
|
+
throw new CustdRequestError(response?.status ?? null, "oauth_unavailable", "bounded", { action: "retry", maxRetries: 1 }, undefined, { cause: error });
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
async ingestEvent(event) {
|
|
250
|
+
const prepared = prepareEvent(event);
|
|
251
|
+
validateEvent(prepared);
|
|
252
|
+
return this.sendWithRetry(prepared);
|
|
253
|
+
}
|
|
254
|
+
// biome-ignore lint/suspicious/noConfusingVoidType: public return type — track() resolves to nothing when queued, or a Response when sent immediately.
|
|
255
|
+
async track(event) {
|
|
256
|
+
const prepared = prepareEvent(event);
|
|
257
|
+
validateEvent(prepared);
|
|
258
|
+
applyEnvironmentLabel(prepared, this.config.environment);
|
|
259
|
+
if (!this.queueEnabled) {
|
|
260
|
+
return this.sendWithRetry(prepared);
|
|
261
|
+
}
|
|
262
|
+
this.enqueue(prepared);
|
|
263
|
+
if (this.batch) {
|
|
264
|
+
const maxBatchSize = this.batch.maxBatchSize ?? 0;
|
|
265
|
+
if (maxBatchSize > 0 && this.queue.length >= maxBatchSize) {
|
|
266
|
+
await this.flush();
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
else if (isOnline()) {
|
|
270
|
+
await this.flush();
|
|
271
|
+
}
|
|
272
|
+
return undefined;
|
|
273
|
+
}
|
|
274
|
+
enqueue(event) {
|
|
275
|
+
if (!this.queueEnabled) {
|
|
276
|
+
return;
|
|
277
|
+
}
|
|
278
|
+
if (this.queue.length >= this.maxQueueSize) {
|
|
279
|
+
this.queue.shift();
|
|
280
|
+
}
|
|
281
|
+
this.queue.push(event);
|
|
282
|
+
this.queueStorage.save(this.queue);
|
|
283
|
+
}
|
|
284
|
+
async flush() {
|
|
285
|
+
if (!this.queueEnabled || this.queue.length === 0) {
|
|
286
|
+
return;
|
|
287
|
+
}
|
|
288
|
+
if (!isOnline()) {
|
|
289
|
+
return;
|
|
290
|
+
}
|
|
291
|
+
const maxBatchSize = this.batch?.maxBatchSize ?? this.queue.length;
|
|
292
|
+
const toSend = this.queue.splice(0, maxBatchSize);
|
|
293
|
+
try {
|
|
294
|
+
await this.sendBatchWithRetry(toSend);
|
|
295
|
+
}
|
|
296
|
+
catch (err) {
|
|
297
|
+
this.queue = [...toSend, ...this.queue];
|
|
298
|
+
this.queueStorage.save(this.queue);
|
|
299
|
+
throw err;
|
|
300
|
+
}
|
|
301
|
+
this.queueStorage.save(this.queue);
|
|
302
|
+
}
|
|
303
|
+
close() {
|
|
304
|
+
if (this.batchTimer) {
|
|
305
|
+
clearInterval(this.batchTimer);
|
|
306
|
+
this.batchTimer = null;
|
|
307
|
+
}
|
|
308
|
+
if (this.onlineHandler && typeof window !== "undefined" && typeof window.removeEventListener === "function") {
|
|
309
|
+
window.removeEventListener("online", this.onlineHandler);
|
|
310
|
+
this.onlineHandler = null;
|
|
311
|
+
}
|
|
312
|
+
for (const remove of this.removeFlushTriggers) {
|
|
313
|
+
remove();
|
|
314
|
+
}
|
|
315
|
+
this.removeFlushTriggers = [];
|
|
316
|
+
}
|
|
317
|
+
async sendWithRetry(event) {
|
|
318
|
+
return withRetry(this.retry, async () => {
|
|
319
|
+
const token = await this.getToken();
|
|
320
|
+
const response = await this.fetchImpl(`${this.baseUrl}/api/v1/events`, {
|
|
321
|
+
method: "POST",
|
|
322
|
+
headers: {
|
|
323
|
+
"Content-Type": "application/json",
|
|
324
|
+
Authorization: `Bearer ${token}`,
|
|
325
|
+
...this.defaultHeaders,
|
|
326
|
+
},
|
|
327
|
+
body: JSON.stringify(event),
|
|
328
|
+
});
|
|
329
|
+
if (!response.ok) {
|
|
330
|
+
const retryable = this.retry.retryOnStatuses.includes(response.status);
|
|
331
|
+
if (retryable) {
|
|
332
|
+
throw new RetryableError(`custd: retryable status ${response.status}`);
|
|
333
|
+
}
|
|
334
|
+
throw await problemError(response, `custd: request failed with status ${response.status}`);
|
|
335
|
+
}
|
|
336
|
+
return response;
|
|
337
|
+
});
|
|
338
|
+
}
|
|
339
|
+
async sendBatchWithRetry(events) {
|
|
340
|
+
const json = JSON.stringify({ events });
|
|
341
|
+
const { body, contentEncoding } = await this.encodeBatchBody(json);
|
|
342
|
+
return withRetry(this.retry, async () => {
|
|
343
|
+
const token = await this.getToken();
|
|
344
|
+
const headers = {
|
|
345
|
+
"Content-Type": "application/json",
|
|
346
|
+
Authorization: `Bearer ${token}`,
|
|
347
|
+
...this.defaultHeaders,
|
|
348
|
+
};
|
|
349
|
+
if (contentEncoding) {
|
|
350
|
+
headers["Content-Encoding"] = contentEncoding;
|
|
351
|
+
}
|
|
352
|
+
const response = await this.fetchImpl(`${this.baseUrl}/api/v1/events/batch`, {
|
|
353
|
+
method: "POST",
|
|
354
|
+
headers,
|
|
355
|
+
body,
|
|
356
|
+
});
|
|
357
|
+
await this.assertBatchResponse(response);
|
|
358
|
+
return response;
|
|
359
|
+
});
|
|
360
|
+
}
|
|
361
|
+
// encodeBatchBody gzip-compresses the serialized batch body when compression
|
|
362
|
+
// is enabled and the body meets the threshold. It falls back to the raw JSON
|
|
363
|
+
// string (no Content-Encoding) when compression is disabled, below threshold,
|
|
364
|
+
// or CompressionStream is unavailable in the runtime.
|
|
365
|
+
async encodeBatchBody(json) {
|
|
366
|
+
if (!this.compressionEnabled || json.length < this.compressionThresholdBytes) {
|
|
367
|
+
return { body: json };
|
|
368
|
+
}
|
|
369
|
+
if (typeof CompressionStream === "undefined") {
|
|
370
|
+
return { body: json };
|
|
371
|
+
}
|
|
372
|
+
const stream = new Blob([json]).stream().pipeThrough(new CompressionStream("gzip"));
|
|
373
|
+
const compressed = new Uint8Array(await new Response(stream).arrayBuffer());
|
|
374
|
+
return { body: compressed, contentEncoding: "gzip" };
|
|
375
|
+
}
|
|
376
|
+
async assertBatchResponse(response) {
|
|
377
|
+
if (!response.ok) {
|
|
378
|
+
const retryable = this.retry.retryOnStatuses.includes(response.status);
|
|
379
|
+
if (retryable) {
|
|
380
|
+
throw new RetryableError(`custd: retryable status ${response.status}`);
|
|
381
|
+
}
|
|
382
|
+
throw await problemError(response, `custd: request failed with status ${response.status}`);
|
|
383
|
+
}
|
|
384
|
+
const text = await response.text();
|
|
385
|
+
if (text === "") {
|
|
386
|
+
return;
|
|
387
|
+
}
|
|
388
|
+
const body = JSON.parse(text);
|
|
389
|
+
// Validate every per-event result, not just HTTP status: a 202 envelope can
|
|
390
|
+
// still carry rejected events with their own non-2xx status and problem.
|
|
391
|
+
const failed = (body.results ?? []).filter((r) => r.success === false);
|
|
392
|
+
if (failed.length > 0) {
|
|
393
|
+
throw new CustdProblemError(this.batchRejectionMessage(response.status, body.results, failed), undefined, failed);
|
|
394
|
+
}
|
|
395
|
+
}
|
|
396
|
+
// Names the rejected events (uuid, status, reason) so a partial batch failure
|
|
397
|
+
// is diagnosable without re-probing the API. The list is capped to keep the
|
|
398
|
+
// message bounded.
|
|
399
|
+
batchRejectionMessage(status, results, failed) {
|
|
400
|
+
const maxList = 10;
|
|
401
|
+
const parts = failed.slice(0, maxList).map((r) => {
|
|
402
|
+
const reason = r.error?.detail || r.error?.title || "no error detail";
|
|
403
|
+
return `${r.eventUuid ?? "unknown"} [status ${r.status ?? status}] ${reason}`;
|
|
404
|
+
});
|
|
405
|
+
if (failed.length > maxList) {
|
|
406
|
+
parts.push(`+${failed.length - maxList} more`);
|
|
407
|
+
}
|
|
408
|
+
return `custd: batch rejected ${failed.length} of ${results?.length ?? failed.length} event(s): ${parts.join("; ")}`;
|
|
409
|
+
}
|
|
410
|
+
async adminRequest(method, path, body, options) {
|
|
411
|
+
return this.apiRequest(method, `/admin${path}`, body, options);
|
|
412
|
+
}
|
|
413
|
+
async offboardingDownload(path, options) {
|
|
414
|
+
const token = await this.getToken(options);
|
|
415
|
+
const response = await this.fetchImpl(`${this.baseUrl}/api/v1/admin${path}`, {
|
|
416
|
+
method: "GET",
|
|
417
|
+
headers: { Authorization: `Bearer ${token}`, ...this.defaultHeaders },
|
|
418
|
+
signal: options?.signal,
|
|
419
|
+
});
|
|
420
|
+
if (!response.ok) {
|
|
421
|
+
throw new Error(`custd: offboarding download failed with status ${response.status}`);
|
|
422
|
+
}
|
|
423
|
+
const lengthHeader = response.headers.get("content-length")?.trim() ?? "";
|
|
424
|
+
const byteSize = Number(lengthHeader);
|
|
425
|
+
if (!/^\d+$/.test(lengthHeader) || !Number.isSafeInteger(byteSize)) {
|
|
426
|
+
throw new Error("custd: offboarding download content length is invalid");
|
|
427
|
+
}
|
|
428
|
+
if (byteSize > maxOffboardingDownloadBytes) {
|
|
429
|
+
throw new Error("custd: offboarding download exceeds 64 MiB");
|
|
430
|
+
}
|
|
431
|
+
const bytes = await readBoundedResponse(response, maxOffboardingDownloadBytes, "offboarding download");
|
|
432
|
+
if (bytes.byteLength !== byteSize) {
|
|
433
|
+
throw new Error("custd: offboarding download content length mismatch");
|
|
434
|
+
}
|
|
435
|
+
const checksumSha256 = (response.headers.get("x-checksum-sha256") ?? "").trim().toLowerCase();
|
|
436
|
+
if (!/^[a-f0-9]{64}$/.test(checksumSha256)) {
|
|
437
|
+
throw new Error("custd: offboarding download checksum header is invalid");
|
|
438
|
+
}
|
|
439
|
+
const actual = await sha256Hex(bytes);
|
|
440
|
+
if (actual !== checksumSha256) {
|
|
441
|
+
throw new Error("custd: offboarding download checksum mismatch");
|
|
442
|
+
}
|
|
443
|
+
return { bytes, checksumSha256, byteSize };
|
|
444
|
+
}
|
|
445
|
+
async auditExportDownload(path, options) {
|
|
446
|
+
const token = await this.getToken(options);
|
|
447
|
+
const response = await this.fetchImpl(`${this.baseUrl}/api/v1/admin${path}`, {
|
|
448
|
+
method: "GET",
|
|
449
|
+
headers: { Authorization: `Bearer ${token}`, ...this.defaultHeaders },
|
|
450
|
+
signal: options?.signal,
|
|
451
|
+
});
|
|
452
|
+
if (!response.ok) {
|
|
453
|
+
throw new Error(`custd: audit export failed with status ${response.status}`);
|
|
454
|
+
}
|
|
455
|
+
const bytes = await readBoundedResponse(response, maxAuditExportBytes, "audit export download");
|
|
456
|
+
return { bytes, contentType: response.headers.get("content-type") ?? "" };
|
|
457
|
+
}
|
|
458
|
+
async apiRequest(method, path, body, options) {
|
|
459
|
+
const token = await this.getToken(options);
|
|
460
|
+
let response;
|
|
461
|
+
try {
|
|
462
|
+
response = await this.fetchImpl(`${this.baseUrl}/api/v1${path}`, {
|
|
463
|
+
method,
|
|
464
|
+
headers: {
|
|
465
|
+
"Content-Type": "application/json",
|
|
466
|
+
Authorization: `Bearer ${token}`,
|
|
467
|
+
...this.defaultHeaders,
|
|
468
|
+
...(options?.idempotencyKey ? { "Idempotency-Key": options.idempotencyKey } : {}),
|
|
469
|
+
},
|
|
470
|
+
body: body === undefined ? undefined : JSON.stringify(body),
|
|
471
|
+
signal: options?.signal,
|
|
472
|
+
});
|
|
473
|
+
}
|
|
474
|
+
catch (error) {
|
|
475
|
+
throw transportRequestError(error);
|
|
476
|
+
}
|
|
477
|
+
if (!response.ok) {
|
|
478
|
+
const text = await response.text().catch(() => "");
|
|
479
|
+
let errorCode = "";
|
|
480
|
+
let detail = "";
|
|
481
|
+
let safeNextAction = "";
|
|
482
|
+
let workflowEnvelope = false;
|
|
483
|
+
if (text.length > 0) {
|
|
484
|
+
try {
|
|
485
|
+
const parsed = JSON.parse(text);
|
|
486
|
+
errorCode = parsed.code || "";
|
|
487
|
+
detail = parsed.detail || parsed.error || parsed.message || parsed.title || "";
|
|
488
|
+
safeNextAction = parsed.safeNextAction || parsed.safe_next_action || "";
|
|
489
|
+
workflowEnvelope = typeof parsed.error === "string" && (errorCode.length > 0 || safeNextAction.length > 0);
|
|
490
|
+
}
|
|
491
|
+
catch {
|
|
492
|
+
detail = text.slice(0, 200);
|
|
493
|
+
}
|
|
494
|
+
}
|
|
495
|
+
let message = detail.length > 0
|
|
496
|
+
? `custd: ${detail} (status ${response.status})`
|
|
497
|
+
: `custd: request failed with status ${response.status}`;
|
|
498
|
+
if (errorCode.length > 0) {
|
|
499
|
+
message = `${message} [error=${errorCode}]`;
|
|
500
|
+
}
|
|
501
|
+
if (safeNextAction.length > 0) {
|
|
502
|
+
message = `${message} [safeNextAction=${safeNextAction}]`;
|
|
503
|
+
}
|
|
504
|
+
if (workflowEnvelope) {
|
|
505
|
+
throw new AdminWorkflowError(response.status, detail, errorCode, safeNextAction);
|
|
506
|
+
}
|
|
507
|
+
throw await responseRequestError(response, errorCode || "request_failed", message, text);
|
|
508
|
+
}
|
|
509
|
+
if (response.status === 204) {
|
|
510
|
+
return undefined;
|
|
511
|
+
}
|
|
512
|
+
return (await response.json());
|
|
513
|
+
}
|
|
514
|
+
async apiDownload(path, options) {
|
|
515
|
+
const token = await this.getToken(options);
|
|
516
|
+
const response = await this.fetchImpl(`${this.baseUrl}/api/v1${path}`, {
|
|
517
|
+
method: "GET",
|
|
518
|
+
headers: { Authorization: `Bearer ${token}`, ...this.defaultHeaders },
|
|
519
|
+
signal: options?.signal,
|
|
520
|
+
});
|
|
521
|
+
if (!response.ok)
|
|
522
|
+
throw new Error(`custd: report export download failed with status ${response.status}`);
|
|
523
|
+
const declared = Number(response.headers.get("content-length") ?? "0");
|
|
524
|
+
if (declared > 64 * 1024 * 1024)
|
|
525
|
+
throw new Error("custd: report export download exceeds 64 MiB");
|
|
526
|
+
const bytes = new Uint8Array(await response.arrayBuffer());
|
|
527
|
+
if (bytes.byteLength > 64 * 1024 * 1024)
|
|
528
|
+
throw new Error("custd: report export download exceeds 64 MiB");
|
|
529
|
+
return bytes;
|
|
530
|
+
}
|
|
531
|
+
}
|
|
532
|
+
async function readBoundedResponse(response, maxBytes, operation) {
|
|
533
|
+
if (!response.body) {
|
|
534
|
+
return new Uint8Array();
|
|
535
|
+
}
|
|
536
|
+
const reader = response.body.getReader();
|
|
537
|
+
const chunks = [];
|
|
538
|
+
let total = 0;
|
|
539
|
+
while (true) {
|
|
540
|
+
const { done, value } = await reader.read();
|
|
541
|
+
if (done)
|
|
542
|
+
break;
|
|
543
|
+
total += value.byteLength;
|
|
544
|
+
if (total > maxBytes) {
|
|
545
|
+
await reader.cancel();
|
|
546
|
+
throw new Error(`custd: ${operation} exceeds 64 MiB`);
|
|
547
|
+
}
|
|
548
|
+
chunks.push(value);
|
|
549
|
+
}
|
|
550
|
+
const result = new Uint8Array(total);
|
|
551
|
+
let offset = 0;
|
|
552
|
+
for (const chunk of chunks) {
|
|
553
|
+
result.set(chunk, offset);
|
|
554
|
+
offset += chunk.byteLength;
|
|
555
|
+
}
|
|
556
|
+
return result;
|
|
557
|
+
}
|
|
558
|
+
async function sha256Hex(bytes) {
|
|
559
|
+
const digest = new Uint8Array(await globalThis.crypto.subtle.digest("SHA-256", Uint8Array.from(bytes).buffer));
|
|
560
|
+
return Array.from(digest, (value) => value.toString(16).padStart(2, "0")).join("");
|
|
561
|
+
}
|
|
562
|
+
const maxOffboardingDownloadBytes = 64 * 1024 * 1024;
|
|
563
|
+
const maxAuditExportBytes = 64 * 1024 * 1024;
|
|
564
|
+
class ReportingNamespace {
|
|
565
|
+
constructor(request, download) {
|
|
566
|
+
this.request = request;
|
|
567
|
+
this.download = download;
|
|
568
|
+
}
|
|
569
|
+
createExport(input, options) {
|
|
570
|
+
if (!input.dashboardKey || input.formats.length < 1 || input.formats.length > 8)
|
|
571
|
+
throw new Error("custd: report export requires a dashboard key and 1 to 8 formats");
|
|
572
|
+
return this.request("POST", "/reporting/exports", input, options);
|
|
573
|
+
}
|
|
574
|
+
listExports(limit = 50, options) {
|
|
575
|
+
if (!Number.isInteger(limit) || limit < 1 || limit > 100)
|
|
576
|
+
throw new Error("custd: report export limit must be between 1 and 100");
|
|
577
|
+
return this.request("GET", `/reporting/exports?limit=${limit}`, undefined, options);
|
|
578
|
+
}
|
|
579
|
+
getExport(exportId, options) {
|
|
580
|
+
assertUuid(exportId, "exportId");
|
|
581
|
+
return this.request("GET", `/reporting/exports/${encodeURIComponent(exportId)}`, undefined, options);
|
|
582
|
+
}
|
|
583
|
+
cancelExport(exportId, reason = "", options) {
|
|
584
|
+
assertUuid(exportId, "exportId");
|
|
585
|
+
return this.request("POST", `/reporting/exports/${encodeURIComponent(exportId)}/cancel`, { reason }, options);
|
|
586
|
+
}
|
|
587
|
+
downloadExport(exportId, artifactId, options) {
|
|
588
|
+
assertUuid(exportId, "exportId");
|
|
589
|
+
assertUuid(artifactId, "artifactId");
|
|
590
|
+
return this.download(`/reporting/exports/${encodeURIComponent(exportId)}/artifacts/${encodeURIComponent(artifactId)}`, options);
|
|
591
|
+
}
|
|
592
|
+
dashboard(key, options) {
|
|
593
|
+
return this.request("GET", `/reporting/dashboards/${encodeURIComponent(key)}`, undefined, options);
|
|
594
|
+
}
|
|
595
|
+
receipt(receiptUuid, options) {
|
|
596
|
+
assertUuid(receiptUuid, "receiptUuid");
|
|
597
|
+
return this.request("GET", `/processing/${encodeURIComponent(receiptUuid)}`, undefined, options);
|
|
598
|
+
}
|
|
599
|
+
outputs(options) {
|
|
600
|
+
return this.request("GET", "/reporting/outputs", undefined, options);
|
|
601
|
+
}
|
|
602
|
+
output(outputUuid, options) {
|
|
603
|
+
assertUuid(outputUuid, "outputUuid");
|
|
604
|
+
return this.request("GET", `/reporting/outputs/${encodeURIComponent(outputUuid)}`, undefined, options);
|
|
605
|
+
}
|
|
606
|
+
queryOutput(outputUuid, request, options) {
|
|
607
|
+
assertUuid(outputUuid, "outputUuid");
|
|
608
|
+
return this.request("POST", `/reporting/outputs/${encodeURIComponent(outputUuid)}/query`, request, options);
|
|
609
|
+
}
|
|
610
|
+
async query(request, options) {
|
|
611
|
+
const data = await this.request("POST", "/reporting/query", request, options);
|
|
612
|
+
if (!isRenderedWidgetData(data)) {
|
|
613
|
+
throw new Error("custd: invalid reporting query response");
|
|
614
|
+
}
|
|
615
|
+
if (data.trust && containsForbiddenReportingTrustKey(data.trust)) {
|
|
616
|
+
throw new Error("custd: unsafe reporting trust diagnostics");
|
|
617
|
+
}
|
|
618
|
+
return data;
|
|
619
|
+
}
|
|
620
|
+
async subjectInsight(request, options) {
|
|
621
|
+
if (!isValidSubjectInsightRequest(request)) {
|
|
622
|
+
throw new Error("custd: invalid subject insight request");
|
|
623
|
+
}
|
|
624
|
+
const response = await this.request("POST", "/reporting/insights/subject", request, options);
|
|
625
|
+
if (!isSubjectInsightResponse(response)) {
|
|
626
|
+
throw new Error("custd: invalid subject insight response");
|
|
627
|
+
}
|
|
628
|
+
if (response.data.trust && containsForbiddenReportingTrustKey(response.data.trust)) {
|
|
629
|
+
throw new Error("custd: unsafe reporting trust diagnostics");
|
|
630
|
+
}
|
|
631
|
+
return response;
|
|
632
|
+
}
|
|
633
|
+
}
|
|
634
|
+
function assertUuid(value, field) {
|
|
635
|
+
if (!/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(value)) {
|
|
636
|
+
throw new Error(`custd: ${field} must be a UUID`);
|
|
637
|
+
}
|
|
638
|
+
}
|
|
639
|
+
function isValidSubjectInsightRequest(request) {
|
|
640
|
+
const allowedKeys = new Set(["template", "subject", "from", "to", "rangeDays"]);
|
|
641
|
+
if (!request ||
|
|
642
|
+
!isRecord(request) ||
|
|
643
|
+
Object.keys(request).some((key) => !allowedKeys.has(key)) ||
|
|
644
|
+
typeof request.template !== "string" ||
|
|
645
|
+
!/^[a-z][a-z0-9_]{0,127}$/.test(request.template) ||
|
|
646
|
+
typeof request.subject !== "string" ||
|
|
647
|
+
request.subject.trim() === "" ||
|
|
648
|
+
request.subject.length > 512) {
|
|
649
|
+
return false;
|
|
650
|
+
}
|
|
651
|
+
const hasRangeDays = request.rangeDays !== undefined;
|
|
652
|
+
const hasFrom = request.from !== undefined;
|
|
653
|
+
const hasTo = request.to !== undefined;
|
|
654
|
+
if (hasRangeDays === (hasFrom || hasTo))
|
|
655
|
+
return false;
|
|
656
|
+
if (request.rangeDays !== undefined) {
|
|
657
|
+
return Number.isInteger(request.rangeDays) && request.rangeDays >= 1 && request.rangeDays <= 366;
|
|
658
|
+
}
|
|
659
|
+
if (typeof request.from !== "string" || typeof request.to !== "string")
|
|
660
|
+
return false;
|
|
661
|
+
if (!isValidRfc3339(request.from) || !isValidRfc3339(request.to))
|
|
662
|
+
return false;
|
|
663
|
+
const from = Date.parse(request.from);
|
|
664
|
+
const to = Date.parse(request.to);
|
|
665
|
+
return Number.isFinite(from) && Number.isFinite(to) && to > from && to - from <= 366 * 24 * 60 * 60 * 1000;
|
|
666
|
+
}
|
|
667
|
+
function isValidRfc3339(value) {
|
|
668
|
+
const match = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.\d+)?(?:Z|[+-](\d{2}):(\d{2}))$/.exec(value);
|
|
669
|
+
if (!match)
|
|
670
|
+
return false;
|
|
671
|
+
const [, yearText, monthText, dayText, hourText, minuteText, secondText, offsetHourText, offsetMinuteText] = match;
|
|
672
|
+
const year = Number(yearText);
|
|
673
|
+
const month = Number(monthText);
|
|
674
|
+
const day = Number(dayText);
|
|
675
|
+
const hour = Number(hourText);
|
|
676
|
+
const minute = Number(minuteText);
|
|
677
|
+
const second = Number(secondText);
|
|
678
|
+
const offsetHour = offsetHourText === undefined ? 0 : Number(offsetHourText);
|
|
679
|
+
const offsetMinute = offsetMinuteText === undefined ? 0 : Number(offsetMinuteText);
|
|
680
|
+
const leapYear = year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);
|
|
681
|
+
const daysInMonth = [31, leapYear ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][month - 1] ?? 0;
|
|
682
|
+
return (month >= 1 &&
|
|
683
|
+
month <= 12 &&
|
|
684
|
+
day >= 1 &&
|
|
685
|
+
day <= daysInMonth &&
|
|
686
|
+
hour <= 23 &&
|
|
687
|
+
minute <= 59 &&
|
|
688
|
+
second <= 59 &&
|
|
689
|
+
offsetHour <= 24 &&
|
|
690
|
+
offsetMinute <= 59 &&
|
|
691
|
+
(offsetHour !== 24 || offsetMinute === 0));
|
|
692
|
+
}
|
|
693
|
+
function isSubjectInsightResponse(value) {
|
|
694
|
+
if (!isRecord(value) || !isRenderedWidgetData(value.data))
|
|
695
|
+
return false;
|
|
696
|
+
return true;
|
|
697
|
+
}
|
|
698
|
+
function isRenderedWidgetData(value) {
|
|
699
|
+
return (isRecord(value) &&
|
|
700
|
+
Array.isArray(value.buckets) &&
|
|
701
|
+
value.buckets.every(isRenderedWidgetBucket) &&
|
|
702
|
+
isRenderedMetricValue(value.value) &&
|
|
703
|
+
isInteger(value.queryDurationMs) &&
|
|
704
|
+
isOptionalInteger(value.parquetUriCount) &&
|
|
705
|
+
isInteger(value.snapshotAgeMs) &&
|
|
706
|
+
isInteger(value.eventLagP95Ms) &&
|
|
707
|
+
(value.metadata === undefined || isReportingQueryMetadata(value.metadata)) &&
|
|
708
|
+
(value.sources === undefined || (Array.isArray(value.sources) && value.sources.every(isReportingSourceSummary))) &&
|
|
709
|
+
isOptionalStringArray(value.warnings) &&
|
|
710
|
+
(value.delta === undefined || isRenderedMetricValue(value.delta)) &&
|
|
711
|
+
isOptionalFiniteNumber(value.deltaPercent) &&
|
|
712
|
+
isOptionalString(value.deltaLabel) &&
|
|
713
|
+
isOptionalString(value.secondaryLabel) &&
|
|
714
|
+
(value.trust === undefined || isRenderedReportingTrust(value.trust)));
|
|
715
|
+
}
|
|
716
|
+
function isRenderedWidgetBucket(value) {
|
|
717
|
+
return (isRecord(value) &&
|
|
718
|
+
typeof value.date === "string" &&
|
|
719
|
+
isRenderedMetricValue(value.value) &&
|
|
720
|
+
typeof value.source === "string" &&
|
|
721
|
+
isInteger(value.queryDurationMs) &&
|
|
722
|
+
isOptionalInteger(value.parquetUriCount) &&
|
|
723
|
+
isOptionalString(value.message) &&
|
|
724
|
+
(value.secondary === undefined || isRenderedMetricValue(value.secondary)));
|
|
725
|
+
}
|
|
726
|
+
function isRenderedMetricValue(value) {
|
|
727
|
+
return (isRecord(value) &&
|
|
728
|
+
isFiniteNumber(value.value) &&
|
|
729
|
+
typeof value.unit === "string" &&
|
|
730
|
+
isInteger(value.sampleCount) &&
|
|
731
|
+
typeof value.dataSufficiency === "string" &&
|
|
732
|
+
typeof value.complete === "boolean" &&
|
|
733
|
+
(value.truncated === undefined || typeof value.truncated === "boolean"));
|
|
734
|
+
}
|
|
735
|
+
function isReportingQueryMetadata(value) {
|
|
736
|
+
return (isRecord(value) &&
|
|
737
|
+
typeof value.resolvedTemplate === "string" &&
|
|
738
|
+
isOptionalString(value.rangeStart) &&
|
|
739
|
+
isOptionalString(value.rangeEnd) &&
|
|
740
|
+
isInteger(value.effectiveMaxRows) &&
|
|
741
|
+
isInteger(value.returnedRows) &&
|
|
742
|
+
isInteger(value.returnedBuckets) &&
|
|
743
|
+
isInteger(value.coveredWindows));
|
|
744
|
+
}
|
|
745
|
+
function isReportingSourceSummary(value) {
|
|
746
|
+
return (isRecord(value) &&
|
|
747
|
+
typeof value.kind === "string" &&
|
|
748
|
+
isInteger(value.count) &&
|
|
749
|
+
isOptionalString(value.coverageStart) &&
|
|
750
|
+
isOptionalString(value.coverageEnd) &&
|
|
751
|
+
typeof value.completeness === "string");
|
|
752
|
+
}
|
|
753
|
+
function isRenderedReportingTrust(value) {
|
|
754
|
+
return (isRecord(value) &&
|
|
755
|
+
typeof value.status === "string" &&
|
|
756
|
+
typeof value.dataFreshness === "string" &&
|
|
757
|
+
typeof value.retryability === "string" &&
|
|
758
|
+
isReportingNextActionHint(value.nextAction) &&
|
|
759
|
+
isOptionalString(value.lastExport) &&
|
|
760
|
+
isOptionalString(value.schemaVersion) &&
|
|
761
|
+
isOptionalString(value.contractVersion) &&
|
|
762
|
+
typeof value.rollupState === "string" &&
|
|
763
|
+
isOptionalStringArray(value.queryWarnings) &&
|
|
764
|
+
typeof value.coverage === "string" &&
|
|
765
|
+
isOptionalString(value.permissionClass) &&
|
|
766
|
+
typeof value.captureState === "string" &&
|
|
767
|
+
typeof value.consentState === "string" &&
|
|
768
|
+
typeof value.exportState === "string" &&
|
|
769
|
+
isOptionalString(value.partialReason) &&
|
|
770
|
+
isOptionalString(value.unavailableReason));
|
|
771
|
+
}
|
|
772
|
+
function isReportingNextActionHint(value) {
|
|
773
|
+
return (isRecord(value) &&
|
|
774
|
+
typeof value.action === "string" &&
|
|
775
|
+
isOptionalInteger(value.pollAfterSeconds) &&
|
|
776
|
+
isOptionalInteger(value.maxRetries));
|
|
777
|
+
}
|
|
778
|
+
function isFiniteNumber(value) {
|
|
779
|
+
return typeof value === "number" && Number.isFinite(value);
|
|
780
|
+
}
|
|
781
|
+
function isInteger(value) {
|
|
782
|
+
return typeof value === "number" && Number.isInteger(value);
|
|
783
|
+
}
|
|
784
|
+
function isOptionalFiniteNumber(value) {
|
|
785
|
+
return value === undefined || isFiniteNumber(value);
|
|
786
|
+
}
|
|
787
|
+
function isOptionalInteger(value) {
|
|
788
|
+
return value === undefined || isInteger(value);
|
|
789
|
+
}
|
|
790
|
+
function isOptionalString(value) {
|
|
791
|
+
return value === undefined || typeof value === "string";
|
|
792
|
+
}
|
|
793
|
+
function isOptionalStringArray(value) {
|
|
794
|
+
return value === undefined || (Array.isArray(value) && value.every((item) => typeof item === "string"));
|
|
795
|
+
}
|
|
796
|
+
function isRecord(value) {
|
|
797
|
+
return typeof value === "object" && value !== null;
|
|
798
|
+
}
|
|
799
|
+
class SchemaNamespace {
|
|
800
|
+
constructor(request) {
|
|
801
|
+
this.request = request;
|
|
802
|
+
}
|
|
803
|
+
validate(input) {
|
|
804
|
+
return this.request("POST", "/schemas/validate", input);
|
|
805
|
+
}
|
|
806
|
+
dryRun(input) {
|
|
807
|
+
return this.request("POST", "/schemas/dry-run", input);
|
|
808
|
+
}
|
|
809
|
+
infer(input) {
|
|
810
|
+
return this.request("POST", "/schemas/infer", input);
|
|
811
|
+
}
|
|
812
|
+
async sendTestEvent(event) {
|
|
813
|
+
const prepared = prepareEvent(event);
|
|
814
|
+
validateEvent(prepared);
|
|
815
|
+
const response = await this.request("POST", "/events", prepared);
|
|
816
|
+
if (!response.success || response.eventUuid !== prepared.eventUuid) {
|
|
817
|
+
throw new Error("custd: test event was not accepted by ingest");
|
|
818
|
+
}
|
|
819
|
+
return response;
|
|
820
|
+
}
|
|
821
|
+
}
|
|
822
|
+
class AdminNamespace {
|
|
823
|
+
constructor(request, nonAdminRequest, offboardingDownload, auditExportDownload) {
|
|
824
|
+
this.dataLabels = new DataLabelAdminClient(request);
|
|
825
|
+
this.tenants = new AdminTenantNamespace(request);
|
|
826
|
+
this.lifecycle = new BackendLifecycleClient(request, offboardingDownload);
|
|
827
|
+
this.clientSetup = new ClientSetupClient(request);
|
|
828
|
+
this.oauthClients = new AdminOAuthClientNamespace(request);
|
|
829
|
+
this.sites = new AdminSiteNamespace(request);
|
|
830
|
+
this.schemas = new AdminSchemaNamespace(request);
|
|
831
|
+
this.measurement = new AdminMeasurementNamespace(request);
|
|
832
|
+
this.predictions = new PredictionAdminClient(request);
|
|
833
|
+
this.privacy = new AdminPrivacyNamespace(request);
|
|
834
|
+
this.retention = new RetentionClient(request);
|
|
835
|
+
this.storageAlerts = new AdminStorageAlertsNamespace(request);
|
|
836
|
+
this.audit = new AdminAuditNamespace(request, auditExportDownload);
|
|
837
|
+
this.offboarding = new OffboardingClient(request, offboardingDownload);
|
|
838
|
+
this.reportingPacks = new AdminReportingPacksNamespace(request);
|
|
839
|
+
this.tenantStorage = new TenantStorageClient(nonAdminRequest);
|
|
840
|
+
this.subjectExports = new SubjectExportClient(request);
|
|
841
|
+
this.privacyErasures = new PrivacyErasureClient(request);
|
|
842
|
+
this.timePlans = new TimePlanAdminClient(request);
|
|
843
|
+
}
|
|
844
|
+
}
|
|
845
|
+
class ProvisioningNamespace {
|
|
846
|
+
constructor(request) {
|
|
847
|
+
this.dataSpaces = new ProvisioningDataSpaceNamespace(request);
|
|
848
|
+
this.producers = new ProvisioningProducerNamespace(request);
|
|
849
|
+
this.reservations = new ProvisioningReservationsNamespace(request);
|
|
850
|
+
}
|
|
851
|
+
}
|
|
852
|
+
class ProvisioningReservationsNamespace {
|
|
853
|
+
constructor(request) {
|
|
854
|
+
this.request = request;
|
|
855
|
+
}
|
|
856
|
+
reserve(dataSpaceSlug, body) {
|
|
857
|
+
return this.request("POST", `/data-spaces/${encodeURIComponent(dataSpaceSlug)}/producer-reservations`, body);
|
|
858
|
+
}
|
|
859
|
+
list(dataSpaceSlug) {
|
|
860
|
+
return this.request("GET", `/data-spaces/${encodeURIComponent(dataSpaceSlug)}/producer-reservations`);
|
|
861
|
+
}
|
|
862
|
+
claim(dataSpaceSlug, producerSlug, body) {
|
|
863
|
+
return this.request("POST", `/data-spaces/${encodeURIComponent(dataSpaceSlug)}/producer-reservations/${encodeURIComponent(producerSlug)}/claim`, body);
|
|
864
|
+
}
|
|
865
|
+
release(dataSpaceSlug, producerSlug) {
|
|
866
|
+
return this.request("DELETE", `/data-spaces/${encodeURIComponent(dataSpaceSlug)}/producer-reservations/${encodeURIComponent(producerSlug)}`);
|
|
867
|
+
}
|
|
868
|
+
}
|
|
869
|
+
class ProvisioningDataSpaceNamespace {
|
|
870
|
+
constructor(request) {
|
|
871
|
+
this.request = request;
|
|
872
|
+
}
|
|
873
|
+
create(dataSpace) {
|
|
874
|
+
return this.request("POST", "/data-spaces", dataSpace);
|
|
875
|
+
}
|
|
876
|
+
list() {
|
|
877
|
+
return this.request("GET", "/data-spaces");
|
|
878
|
+
}
|
|
879
|
+
revoke(slug) {
|
|
880
|
+
return this.request("DELETE", `/data-spaces/${encodeURIComponent(slug)}`);
|
|
881
|
+
}
|
|
882
|
+
}
|
|
883
|
+
class ProvisioningProducerNamespace {
|
|
884
|
+
constructor(request) {
|
|
885
|
+
this.request = request;
|
|
886
|
+
}
|
|
887
|
+
provision(request) {
|
|
888
|
+
return this.request("POST", "/producer-provisioning", request);
|
|
889
|
+
}
|
|
890
|
+
list(companySlug) {
|
|
891
|
+
const query = companySlug ? `?companySlug=${encodeURIComponent(companySlug)}` : "";
|
|
892
|
+
return this.request("GET", `/producer-provisioning${query}`).then((response) => response.producers);
|
|
893
|
+
}
|
|
894
|
+
rotateSecret(clientId) {
|
|
895
|
+
return this.request("POST", `/producer-provisioning/${encodeURIComponent(clientId)}/rotate-secret`);
|
|
896
|
+
}
|
|
897
|
+
/**
|
|
898
|
+
* Sets the environment recorded for this producer. It is the authenticated
|
|
899
|
+
* default for events that do not declare their own, not a per-environment
|
|
900
|
+
* credential: one producer is expected to carry every environment unless an
|
|
901
|
+
* operator deliberately restricts it.
|
|
902
|
+
*/
|
|
903
|
+
updateEnvironment(clientId, environment) {
|
|
904
|
+
return this.request("PATCH", `/producer-provisioning/${encodeURIComponent(clientId)}/environment`, {
|
|
905
|
+
environment,
|
|
906
|
+
});
|
|
907
|
+
}
|
|
908
|
+
revoke(clientId) {
|
|
909
|
+
return this.request("DELETE", `/producer-provisioning/${encodeURIComponent(clientId)}`);
|
|
910
|
+
}
|
|
911
|
+
}
|
|
912
|
+
class AdminTenantNamespace {
|
|
913
|
+
constructor(request) {
|
|
914
|
+
this.request = request;
|
|
915
|
+
}
|
|
916
|
+
create(tenant) {
|
|
917
|
+
return this.request("POST", "/tenants", tenant);
|
|
918
|
+
}
|
|
919
|
+
list() {
|
|
920
|
+
return this.request("GET", "/tenants");
|
|
921
|
+
}
|
|
922
|
+
get(slug) {
|
|
923
|
+
return this.request("GET", `/tenants/${encodeURIComponent(slug)}`);
|
|
924
|
+
}
|
|
925
|
+
delete(slug) {
|
|
926
|
+
return this.request("DELETE", `/tenants/${encodeURIComponent(slug)}`);
|
|
927
|
+
}
|
|
928
|
+
}
|
|
929
|
+
// Custd requires a canonical UUIDv7 Idempotency-Key on every OAuth client
|
|
930
|
+
// mutation, so one is generated when the caller does not supply it. A caller that
|
|
931
|
+
// retries the same mutation should pass its own key to reuse it; a caller that
|
|
932
|
+
// checks for an existing client first, as a reconcile does, is safe either way.
|
|
933
|
+
class AdminOAuthClientNamespace {
|
|
934
|
+
constructor(request) {
|
|
935
|
+
this.request = request;
|
|
936
|
+
}
|
|
937
|
+
create(client, options = {}) {
|
|
938
|
+
return this.request("POST", "/oauth-clients", client, mutationOptions(options));
|
|
939
|
+
}
|
|
940
|
+
list() {
|
|
941
|
+
return this.request("GET", "/oauth-clients");
|
|
942
|
+
}
|
|
943
|
+
get(clientId) {
|
|
944
|
+
return this.request("GET", `/oauth-clients/${encodeURIComponent(clientId)}`);
|
|
945
|
+
}
|
|
946
|
+
delete(clientId, options = {}) {
|
|
947
|
+
return this.request("DELETE", `/oauth-clients/${encodeURIComponent(clientId)}`, undefined, mutationOptions(options));
|
|
948
|
+
}
|
|
949
|
+
rotateSecret(clientId, options = {}) {
|
|
950
|
+
return this.request("POST", `/oauth-clients/${encodeURIComponent(clientId)}/rotate-secret`, undefined, mutationOptions(options));
|
|
951
|
+
}
|
|
952
|
+
updateScopes(clientId, body, options = {}) {
|
|
953
|
+
return this.request("PATCH", `/oauth-clients/${encodeURIComponent(clientId)}/scopes`, body, mutationOptions(options));
|
|
954
|
+
}
|
|
955
|
+
}
|
|
956
|
+
function mutationOptions(options) {
|
|
957
|
+
return { ...options, idempotencyKey: options.idempotencyKey ?? uuidv7() };
|
|
958
|
+
}
|
|
959
|
+
class AdminSiteNamespace {
|
|
960
|
+
constructor(request) {
|
|
961
|
+
this.request = request;
|
|
962
|
+
}
|
|
963
|
+
create(site) {
|
|
964
|
+
return this.request("POST", "/sites", site);
|
|
965
|
+
}
|
|
966
|
+
async list() {
|
|
967
|
+
const response = await this.request("GET", "/sites");
|
|
968
|
+
return { sites: response.sites.map(publicAdminSite) };
|
|
969
|
+
}
|
|
970
|
+
async get(siteUuid) {
|
|
971
|
+
const site = await this.request("GET", `/sites/${encodeURIComponent(siteUuid)}`);
|
|
972
|
+
return publicAdminSite(site);
|
|
973
|
+
}
|
|
974
|
+
delete(siteUuid) {
|
|
975
|
+
return this.request("DELETE", `/sites/${encodeURIComponent(siteUuid)}`);
|
|
976
|
+
}
|
|
977
|
+
rotateWriteKey(siteUuid) {
|
|
978
|
+
return this.request("POST", `/sites/${encodeURIComponent(siteUuid)}/rotate-write-key`);
|
|
979
|
+
}
|
|
980
|
+
}
|
|
981
|
+
class AdminSchemaNamespace {
|
|
982
|
+
constructor(request) {
|
|
983
|
+
this.request = request;
|
|
984
|
+
}
|
|
985
|
+
list() {
|
|
986
|
+
return this.request("GET", "/schemas");
|
|
987
|
+
}
|
|
988
|
+
get(eventTypeSlug) {
|
|
989
|
+
return this.request("GET", `/schemas/${encodeURIComponent(eventTypeSlug)}`);
|
|
990
|
+
}
|
|
991
|
+
register(schema) {
|
|
992
|
+
return this.request("POST", "/schemas", schema);
|
|
993
|
+
}
|
|
994
|
+
createVersion(eventTypeSlug, schema) {
|
|
995
|
+
return this.request("POST", `/schemas/${encodeURIComponent(eventTypeSlug)}/versions`, schema);
|
|
996
|
+
}
|
|
997
|
+
validate(body) {
|
|
998
|
+
return this.request("POST", "/schema/validate", body);
|
|
999
|
+
}
|
|
1000
|
+
enableVersion(tenantSlug, eventTypeSlug, body) {
|
|
1001
|
+
return this.request("POST", `/schema/${encodeURIComponent(tenantSlug)}/${encodeURIComponent(eventTypeSlug)}/enable`, body);
|
|
1002
|
+
}
|
|
1003
|
+
dryRun(tenantSlug, eventTypeSlug, body) {
|
|
1004
|
+
return this.request("POST", `/schema/${encodeURIComponent(tenantSlug)}/${encodeURIComponent(eventTypeSlug)}/dry-run`, body);
|
|
1005
|
+
}
|
|
1006
|
+
audit() {
|
|
1007
|
+
return this.request("GET", "/schema/audit");
|
|
1008
|
+
}
|
|
1009
|
+
}
|
|
1010
|
+
class AdminPrivacyNamespace {
|
|
1011
|
+
constructor(request) {
|
|
1012
|
+
this.request = request;
|
|
1013
|
+
}
|
|
1014
|
+
getRules() {
|
|
1015
|
+
return this.request("GET", "/privacy/rules");
|
|
1016
|
+
}
|
|
1017
|
+
setRules(body) {
|
|
1018
|
+
return this.request("PUT", "/privacy/rules", body);
|
|
1019
|
+
}
|
|
1020
|
+
mapIdentifier(companySlug, body) {
|
|
1021
|
+
return this.request("POST", `/privacy/identifiers/${encodeURIComponent(companySlug)}/map`, body);
|
|
1022
|
+
}
|
|
1023
|
+
listIdentifierMappings(companySlug) {
|
|
1024
|
+
return this.request("GET", `/privacy/identifiers/${encodeURIComponent(companySlug)}`);
|
|
1025
|
+
}
|
|
1026
|
+
}
|
|
1027
|
+
class AdminStorageAlertsNamespace {
|
|
1028
|
+
constructor(request) {
|
|
1029
|
+
this.request = request;
|
|
1030
|
+
}
|
|
1031
|
+
listRules(tenantSlug) {
|
|
1032
|
+
return this.request("GET", `/storage/alerts/${encodeURIComponent(tenantSlug)}`);
|
|
1033
|
+
}
|
|
1034
|
+
createRule(tenantSlug, body) {
|
|
1035
|
+
return this.request("POST", `/storage/alerts/${encodeURIComponent(tenantSlug)}`, body);
|
|
1036
|
+
}
|
|
1037
|
+
deleteRule(tenantSlug, ruleId) {
|
|
1038
|
+
return this.request("DELETE", `/storage/alerts/${encodeURIComponent(tenantSlug)}/${encodeURIComponent(ruleId)}`);
|
|
1039
|
+
}
|
|
1040
|
+
}
|
|
1041
|
+
const auditDisclosureStates = new Set(["available", "redacted", "not_recorded"]);
|
|
1042
|
+
function mapAdminAuditChange(value) {
|
|
1043
|
+
if (!isRecord(value) || typeof value.field !== "string")
|
|
1044
|
+
return undefined;
|
|
1045
|
+
const change = { field: value.field };
|
|
1046
|
+
if ("before" in value)
|
|
1047
|
+
change.before = value.before;
|
|
1048
|
+
if ("after" in value)
|
|
1049
|
+
change.after = value.after;
|
|
1050
|
+
return change;
|
|
1051
|
+
}
|
|
1052
|
+
function mapAdminAuditNetwork(value) {
|
|
1053
|
+
if (!isRecord(value))
|
|
1054
|
+
return undefined;
|
|
1055
|
+
const ipAddressState = value.ipAddressState;
|
|
1056
|
+
const userAgentState = value.userAgentState;
|
|
1057
|
+
if (!auditDisclosureStates.has(ipAddressState) ||
|
|
1058
|
+
!auditDisclosureStates.has(userAgentState))
|
|
1059
|
+
return undefined;
|
|
1060
|
+
return {
|
|
1061
|
+
...(typeof value.ipAddress === "string" ? { ipAddress: value.ipAddress } : {}),
|
|
1062
|
+
ipAddressState: ipAddressState,
|
|
1063
|
+
...(typeof value.userAgent === "string" ? { userAgent: value.userAgent } : {}),
|
|
1064
|
+
userAgentState: userAgentState,
|
|
1065
|
+
};
|
|
1066
|
+
}
|
|
1067
|
+
function mapAdminAuditRetention(value) {
|
|
1068
|
+
if (!isRecord(value) ||
|
|
1069
|
+
typeof value.eventMaxAgeSeconds !== "number" ||
|
|
1070
|
+
typeof value.ipAddressMaxAgeSeconds !== "number" ||
|
|
1071
|
+
typeof value.userAgentMaxAgeSeconds !== "number")
|
|
1072
|
+
return undefined;
|
|
1073
|
+
return {
|
|
1074
|
+
eventMaxAgeSeconds: value.eventMaxAgeSeconds,
|
|
1075
|
+
ipAddressMaxAgeSeconds: value.ipAddressMaxAgeSeconds,
|
|
1076
|
+
userAgentMaxAgeSeconds: value.userAgentMaxAgeSeconds,
|
|
1077
|
+
};
|
|
1078
|
+
}
|
|
1079
|
+
function mapAdminAuditEvent(event) {
|
|
1080
|
+
if (typeof event.eventId !== "string" || !AUDIT_EVENT_UUID_PATTERN.test(event.eventId)) {
|
|
1081
|
+
throw new Error("custd: audit event response eventId must be a UUID");
|
|
1082
|
+
}
|
|
1083
|
+
const details = event.details;
|
|
1084
|
+
const actorRoles = Array.isArray(event.actorRoles)
|
|
1085
|
+
? event.actorRoles.filter((role) => typeof role === "string")
|
|
1086
|
+
: [];
|
|
1087
|
+
const changes = Array.isArray(event.changes)
|
|
1088
|
+
? event.changes.map(mapAdminAuditChange).filter((change) => change !== undefined)
|
|
1089
|
+
: [];
|
|
1090
|
+
const network = mapAdminAuditNetwork(event.network);
|
|
1091
|
+
return {
|
|
1092
|
+
eventId: event.eventId,
|
|
1093
|
+
tenantSlug: event.tenantSlug,
|
|
1094
|
+
actorKind: event.actorKind,
|
|
1095
|
+
...(event.actorReference !== undefined ? { actorReference: event.actorReference } : {}),
|
|
1096
|
+
actorDisplayName: event.actorDisplayName,
|
|
1097
|
+
...(actorRoles.length > 0 ? { actorRoles } : {}),
|
|
1098
|
+
action: event.action,
|
|
1099
|
+
resourceType: event.resourceType,
|
|
1100
|
+
...(event.resourceId !== undefined ? { resourceId: event.resourceId } : {}),
|
|
1101
|
+
outcome: event.outcome,
|
|
1102
|
+
...(event.correlationId !== undefined ? { correlationId: event.correlationId } : {}),
|
|
1103
|
+
...(event.operationId !== undefined ? { operationId: event.operationId } : {}),
|
|
1104
|
+
...(changes.length > 0 ? { changes } : {}),
|
|
1105
|
+
...(details !== undefined && typeof details === "object" && !Array.isArray(details) ? { details } : {}),
|
|
1106
|
+
...(network !== undefined ? { network } : {}),
|
|
1107
|
+
createdAt: event.createdAt,
|
|
1108
|
+
};
|
|
1109
|
+
}
|
|
1110
|
+
function mapAdminReportingPackAuditEvent(event) {
|
|
1111
|
+
return {
|
|
1112
|
+
action: event.action,
|
|
1113
|
+
...(event.actorReference !== undefined ? { actorReference: event.actorReference } : {}),
|
|
1114
|
+
actorDisplayName: event.actorDisplayName,
|
|
1115
|
+
resourceType: event.resourceType,
|
|
1116
|
+
resourceId: event.resourceId,
|
|
1117
|
+
packKey: event.packKey,
|
|
1118
|
+
createdAt: event.createdAt,
|
|
1119
|
+
};
|
|
1120
|
+
}
|
|
1121
|
+
const AUDIT_EVENT_UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
|
|
1122
|
+
class AdminAuditNamespace {
|
|
1123
|
+
constructor(request, download) {
|
|
1124
|
+
this.request = request;
|
|
1125
|
+
this.download = download;
|
|
1126
|
+
}
|
|
1127
|
+
auditQuery(options, includePagination = true) {
|
|
1128
|
+
if (!options) {
|
|
1129
|
+
return "";
|
|
1130
|
+
}
|
|
1131
|
+
const params = new URLSearchParams();
|
|
1132
|
+
if (options.scope)
|
|
1133
|
+
params.set("scope", options.scope);
|
|
1134
|
+
if (options.companySlug)
|
|
1135
|
+
params.set("companySlug", options.companySlug);
|
|
1136
|
+
if (options.affectedTenantSlug)
|
|
1137
|
+
params.set("affectedTenantSlug", options.affectedTenantSlug);
|
|
1138
|
+
if (options.since)
|
|
1139
|
+
params.set("since", options.since);
|
|
1140
|
+
if (options.until)
|
|
1141
|
+
params.set("until", options.until);
|
|
1142
|
+
if (options.actorKind)
|
|
1143
|
+
params.set("actorKind", options.actorKind);
|
|
1144
|
+
if (options.actorReference)
|
|
1145
|
+
params.set("actorReference", options.actorReference);
|
|
1146
|
+
if (options.action)
|
|
1147
|
+
params.set("action", options.action);
|
|
1148
|
+
if (options.resourceType)
|
|
1149
|
+
params.set("resourceType", options.resourceType);
|
|
1150
|
+
if (options.resourceId)
|
|
1151
|
+
params.set("resourceId", options.resourceId);
|
|
1152
|
+
if (options.outcome)
|
|
1153
|
+
params.set("outcome", options.outcome);
|
|
1154
|
+
if (options.correlationId)
|
|
1155
|
+
params.set("correlationId", options.correlationId);
|
|
1156
|
+
if (includePagination && typeof options.limit === "number")
|
|
1157
|
+
params.set("limit", String(options.limit));
|
|
1158
|
+
if (includePagination && options.cursor)
|
|
1159
|
+
params.set("cursor", options.cursor);
|
|
1160
|
+
const query = params.toString();
|
|
1161
|
+
return query.length === 0 ? "" : `?${query}`;
|
|
1162
|
+
}
|
|
1163
|
+
auditLookupQuery(options) {
|
|
1164
|
+
if (!options)
|
|
1165
|
+
return "";
|
|
1166
|
+
const params = new URLSearchParams();
|
|
1167
|
+
if (options.scope)
|
|
1168
|
+
params.set("scope", options.scope);
|
|
1169
|
+
if (options.companySlug)
|
|
1170
|
+
params.set("companySlug", options.companySlug);
|
|
1171
|
+
const query = params.toString();
|
|
1172
|
+
return query.length === 0 ? "" : `?${query}`;
|
|
1173
|
+
}
|
|
1174
|
+
async listEvents(options) {
|
|
1175
|
+
const response = await this.request("GET", `/audit/events${this.auditQuery(options)}`);
|
|
1176
|
+
const retention = mapAdminAuditRetention(response.retention);
|
|
1177
|
+
return {
|
|
1178
|
+
events: response.events.map(mapAdminAuditEvent),
|
|
1179
|
+
nextCursor: response.nextCursor ?? { cursor: "" },
|
|
1180
|
+
...(typeof response.coverageBeginsAt === "string" ? { coverageBeginsAt: response.coverageBeginsAt } : {}),
|
|
1181
|
+
...(retention === undefined ? {} : { retention }),
|
|
1182
|
+
};
|
|
1183
|
+
}
|
|
1184
|
+
async getEvent(eventId, options) {
|
|
1185
|
+
const response = await this.request("GET", `/audit/events/${encodeURIComponent(eventId)}${this.auditLookupQuery(options)}`);
|
|
1186
|
+
return mapAdminAuditEvent(response);
|
|
1187
|
+
}
|
|
1188
|
+
exportEvents(options, format = "json") {
|
|
1189
|
+
if (format !== "csv" && format !== "json") {
|
|
1190
|
+
return Promise.reject(new Error("custd: audit export format must be csv or json"));
|
|
1191
|
+
}
|
|
1192
|
+
const query = this.auditQuery(options, false);
|
|
1193
|
+
const suffix = query.length > 0 ? `${query}&format=${format}` : `?format=${format}`;
|
|
1194
|
+
return this.download(`/audit/events/export${suffix}`);
|
|
1195
|
+
}
|
|
1196
|
+
async listReportingPackEvents(packKey) {
|
|
1197
|
+
const response = await this.request("GET", `/reporting-packs/audit-events?packKey=${encodeURIComponent(packKey)}`);
|
|
1198
|
+
return { events: response.events.map(mapAdminReportingPackAuditEvent) };
|
|
1199
|
+
}
|
|
1200
|
+
}
|
|
1201
|
+
class AdminReportingPacksNamespace {
|
|
1202
|
+
constructor(request) {
|
|
1203
|
+
this.request = request;
|
|
1204
|
+
}
|
|
1205
|
+
listDrafts() {
|
|
1206
|
+
return this.request("GET", "/reporting-packs/drafts");
|
|
1207
|
+
}
|
|
1208
|
+
getDraft(draftId) {
|
|
1209
|
+
return this.request("GET", `/reporting-packs/drafts/${encodeURIComponent(draftId)}`);
|
|
1210
|
+
}
|
|
1211
|
+
createDraft(body) {
|
|
1212
|
+
return this.request("POST", "/reporting-packs/drafts", body);
|
|
1213
|
+
}
|
|
1214
|
+
updateDraft(draftId, body) {
|
|
1215
|
+
return this.request("PUT", `/reporting-packs/drafts/${encodeURIComponent(draftId)}`, body);
|
|
1216
|
+
}
|
|
1217
|
+
validate(body) {
|
|
1218
|
+
return this.request("POST", "/reporting-packs/validate", body);
|
|
1219
|
+
}
|
|
1220
|
+
preview(body) {
|
|
1221
|
+
return this.request("POST", "/reporting-packs/preview", body);
|
|
1222
|
+
}
|
|
1223
|
+
publish(draftId) {
|
|
1224
|
+
return this.request("POST", `/reporting-packs/drafts/${encodeURIComponent(draftId)}/publish`);
|
|
1225
|
+
}
|
|
1226
|
+
restart(draftId) {
|
|
1227
|
+
return this.request("POST", `/reporting-packs/drafts/${encodeURIComponent(draftId)}/restart`);
|
|
1228
|
+
}
|
|
1229
|
+
getGeneration(generationId) {
|
|
1230
|
+
return this.request("GET", `/reporting-packs/generations/${encodeURIComponent(generationId)}`);
|
|
1231
|
+
}
|
|
1232
|
+
getGenerationStatus(generationId) {
|
|
1233
|
+
return this.request("GET", `/reporting-packs/generations/${encodeURIComponent(generationId)}/status`);
|
|
1234
|
+
}
|
|
1235
|
+
rollbackGeneration(generationId) {
|
|
1236
|
+
return this.request("POST", `/reporting-packs/generations/${encodeURIComponent(generationId)}/rollback`);
|
|
1237
|
+
}
|
|
1238
|
+
getRollupProvenance(generationId) {
|
|
1239
|
+
return this.request("GET", `/reporting-packs/generations/${encodeURIComponent(generationId)}/rollup-provenance`);
|
|
1240
|
+
}
|
|
1241
|
+
}
|
|
1242
|
+
class AdminMeasurementNamespace {
|
|
1243
|
+
constructor(request) {
|
|
1244
|
+
this.projects = new AdminMeasurementProjectNamespace(request);
|
|
1245
|
+
}
|
|
1246
|
+
}
|
|
1247
|
+
class AdminMeasurementProjectNamespace {
|
|
1248
|
+
constructor(request) {
|
|
1249
|
+
this.request = request;
|
|
1250
|
+
}
|
|
1251
|
+
create(project) {
|
|
1252
|
+
return this.request("POST", "/measurement/projects", project);
|
|
1253
|
+
}
|
|
1254
|
+
list() {
|
|
1255
|
+
return this.request("GET", "/measurement/projects");
|
|
1256
|
+
}
|
|
1257
|
+
get(projectUuid) {
|
|
1258
|
+
return this.request("GET", `/measurement/projects/${encodeURIComponent(projectUuid)}`);
|
|
1259
|
+
}
|
|
1260
|
+
submitObservation(projectUuid, observation) {
|
|
1261
|
+
return this.submitObservations(projectUuid, { rows: [observation] });
|
|
1262
|
+
}
|
|
1263
|
+
async submitObservations(projectUuid, request) {
|
|
1264
|
+
const response = await this.request("POST", `/measurement/projects/${encodeURIComponent(projectUuid)}/observations:bulk`, request);
|
|
1265
|
+
validateMeasurementResults(response.results, request.rows.length);
|
|
1266
|
+
return response;
|
|
1267
|
+
}
|
|
1268
|
+
async importCSVString(projectUuid, csv, expectedRows) {
|
|
1269
|
+
const response = await this.request("POST", `/measurement/projects/${encodeURIComponent(projectUuid)}/observations:csv`, { csv });
|
|
1270
|
+
validateMeasurementResults(response.results, expectedRows);
|
|
1271
|
+
return response;
|
|
1272
|
+
}
|
|
1273
|
+
}
|
|
1274
|
+
function validateMeasurementResults(results, submittedRows) {
|
|
1275
|
+
if (results.length !== submittedRows) {
|
|
1276
|
+
throw new Error(`custd: measurement result count ${results.length} does not match submitted row count ${submittedRows}`);
|
|
1277
|
+
}
|
|
1278
|
+
results.forEach((result, index) => {
|
|
1279
|
+
if (result.success && !result.observationUuid) {
|
|
1280
|
+
throw new Error(`custd: measurement result ${index} missing observationUuid`);
|
|
1281
|
+
}
|
|
1282
|
+
});
|
|
1283
|
+
}
|
|
1284
|
+
// redactedProvisionedProducer returns the display-safe view of a provisioned
|
|
1285
|
+
// producer bundle, omitting the client secret so it is safe for dashboards.
|
|
1286
|
+
export function redactedProvisionedProducer(credentials) {
|
|
1287
|
+
const { clientSecret: _clientSecret, ...rest } = credentials;
|
|
1288
|
+
return rest;
|
|
1289
|
+
}
|
|
1290
|
+
export function validateEvent(event) {
|
|
1291
|
+
const missing = [];
|
|
1292
|
+
if (!event.eventUuid)
|
|
1293
|
+
missing.push("eventUuid");
|
|
1294
|
+
if (!event.eventTypeSlug)
|
|
1295
|
+
missing.push("eventTypeSlug");
|
|
1296
|
+
if (!event.schemaVersion)
|
|
1297
|
+
missing.push("schemaVersion");
|
|
1298
|
+
if (!event.timestamp)
|
|
1299
|
+
missing.push("timestamp");
|
|
1300
|
+
if (!event.sessionId)
|
|
1301
|
+
missing.push("sessionId");
|
|
1302
|
+
if (!event.anonymousId)
|
|
1303
|
+
missing.push("anonymousId");
|
|
1304
|
+
if (!event.companySlug)
|
|
1305
|
+
missing.push("companySlug");
|
|
1306
|
+
if (!event.context)
|
|
1307
|
+
missing.push("context");
|
|
1308
|
+
if (!event.payload)
|
|
1309
|
+
missing.push("payload");
|
|
1310
|
+
const deviceType = event.context?.device?.type;
|
|
1311
|
+
if (!deviceType)
|
|
1312
|
+
missing.push("context.device.type");
|
|
1313
|
+
if (missing.length > 0) {
|
|
1314
|
+
throw new Error(`custd: missing required fields: ${missing.join(", ")}`);
|
|
1315
|
+
}
|
|
1316
|
+
validateEnvironmentValue(event.environment ?? "");
|
|
1317
|
+
validateProducerLabels(event);
|
|
1318
|
+
}
|
|
1319
|
+
const labelKeyPattern = /^[a-z][a-z0-9]*(?:[._-][a-z0-9]+)*$/;
|
|
1320
|
+
/** Reserved envelope label carrying a declared environment. */
|
|
1321
|
+
export const environmentLabelKey = "custd.environment";
|
|
1322
|
+
const environmentValuePattern = /^[a-z][a-z0-9-]{0,31}$/;
|
|
1323
|
+
/**
|
|
1324
|
+
* Checks a declared environment against the contract ingest applies, so a
|
|
1325
|
+
* rejected declaration fails locally instead of failing the event at the API.
|
|
1326
|
+
*/
|
|
1327
|
+
export function validateEnvironmentValue(value) {
|
|
1328
|
+
if (value === "")
|
|
1329
|
+
return;
|
|
1330
|
+
if (value !== value.trim() || !environmentValuePattern.test(value)) {
|
|
1331
|
+
throw new Error(`custd: environment ${JSON.stringify(value)} must be lowercase letters, digits and hyphens, at most 32 characters`);
|
|
1332
|
+
}
|
|
1333
|
+
if (value === "unclassified") {
|
|
1334
|
+
throw new Error('custd: environment "unclassified" is reserved');
|
|
1335
|
+
}
|
|
1336
|
+
}
|
|
1337
|
+
/**
|
|
1338
|
+
* Stamps the effective environment onto the envelope labels. An event-level
|
|
1339
|
+
* declaration wins over the client default, and a label the caller set is never
|
|
1340
|
+
* overwritten.
|
|
1341
|
+
*/
|
|
1342
|
+
export function applyEnvironmentLabel(event, clientEnvironment) {
|
|
1343
|
+
const effective = event.environment || clientEnvironment || "";
|
|
1344
|
+
if (effective === "")
|
|
1345
|
+
return;
|
|
1346
|
+
event.labels = { ...(event.labels ?? {}) };
|
|
1347
|
+
if (event.labels[environmentLabelKey] === undefined) {
|
|
1348
|
+
event.labels[environmentLabelKey] = effective;
|
|
1349
|
+
}
|
|
1350
|
+
}
|
|
1351
|
+
function validateProducerLabels(event) {
|
|
1352
|
+
if ("resolvedLabels" in event || "vocabularyFingerprint" in event) {
|
|
1353
|
+
throw new Error("custd: server-owned label fields are not accepted");
|
|
1354
|
+
}
|
|
1355
|
+
if (event.labels === undefined)
|
|
1356
|
+
return;
|
|
1357
|
+
if (event.labels === null || typeof event.labels !== "object" || Array.isArray(event.labels)) {
|
|
1358
|
+
throw new Error("custd: labels must be an object of strings");
|
|
1359
|
+
}
|
|
1360
|
+
const entries = Object.entries(event.labels);
|
|
1361
|
+
if (entries.length > 16)
|
|
1362
|
+
throw new Error("custd: labels may contain at most 16 entries");
|
|
1363
|
+
for (const [key, value] of entries) {
|
|
1364
|
+
if (!labelKeyPattern.test(key) || utf8Bytes(key) > 64 || key.startsWith("custd.")) {
|
|
1365
|
+
throw new Error(`custd: labels.${key} has an invalid key`);
|
|
1366
|
+
}
|
|
1367
|
+
if (typeof value !== "string" || value === "" || value !== value.trim() || utf8Bytes(value) > 128) {
|
|
1368
|
+
throw new Error(`custd: labels.${key} has an invalid value`);
|
|
1369
|
+
}
|
|
1370
|
+
}
|
|
1371
|
+
}
|
|
1372
|
+
function utf8Bytes(value) {
|
|
1373
|
+
return new TextEncoder().encode(value).length;
|
|
1374
|
+
}
|
|
1375
|
+
export function validateBrowserEvent(event) {
|
|
1376
|
+
const missing = [];
|
|
1377
|
+
if (!event.eventUuid)
|
|
1378
|
+
missing.push("eventUuid");
|
|
1379
|
+
if (!event.eventTypeSlug)
|
|
1380
|
+
missing.push("eventTypeSlug");
|
|
1381
|
+
if (!event.schemaVersion)
|
|
1382
|
+
missing.push("schemaVersion");
|
|
1383
|
+
if (!event.timestamp)
|
|
1384
|
+
missing.push("timestamp");
|
|
1385
|
+
if (!event.context)
|
|
1386
|
+
missing.push("context");
|
|
1387
|
+
if (!event.payload)
|
|
1388
|
+
missing.push("payload");
|
|
1389
|
+
if (!event.payload?.siteUuid)
|
|
1390
|
+
missing.push("payload.siteUuid");
|
|
1391
|
+
const deviceType = event.context?.device?.type;
|
|
1392
|
+
if (!deviceType)
|
|
1393
|
+
missing.push("context.device.type");
|
|
1394
|
+
if (missing.length > 0) {
|
|
1395
|
+
throw new Error(`custd: missing required browser fields: ${missing.join(", ")}`);
|
|
1396
|
+
}
|
|
1397
|
+
validateEnvironmentValue(event.environment ?? "");
|
|
1398
|
+
validateProducerLabels(event);
|
|
1399
|
+
}
|
|
1400
|
+
export function createDogfoodEvent(input) {
|
|
1401
|
+
const missing = [];
|
|
1402
|
+
if (!input.eventTypeSlug)
|
|
1403
|
+
missing.push("eventTypeSlug");
|
|
1404
|
+
if (!input.schemaVersion)
|
|
1405
|
+
missing.push("schemaVersion");
|
|
1406
|
+
if (!input.companySlug)
|
|
1407
|
+
missing.push("companySlug");
|
|
1408
|
+
if (!input.sourceSystem)
|
|
1409
|
+
missing.push("sourceSystem");
|
|
1410
|
+
if (!input.sourceCompany)
|
|
1411
|
+
missing.push("sourceCompany");
|
|
1412
|
+
if (!input.environment)
|
|
1413
|
+
missing.push("environment");
|
|
1414
|
+
if (missing.length > 0) {
|
|
1415
|
+
throw new Error(`custd: missing dogfood fields: ${missing.join(", ")}`);
|
|
1416
|
+
}
|
|
1417
|
+
const sanitized = sanitizeDogfoodPayload(input.payload ?? {});
|
|
1418
|
+
if (input.strictPayloadKeys && sanitized.droppedKeys.length > 0) {
|
|
1419
|
+
throw new Error(`custd: dropped dogfood payload keys: ${sanitized.droppedKeys.join(", ")}`);
|
|
1420
|
+
}
|
|
1421
|
+
const payload = sanitized.payload;
|
|
1422
|
+
payload.sourceSystem = input.sourceSystem;
|
|
1423
|
+
payload.sourceCompany = input.sourceCompany;
|
|
1424
|
+
payload.environment = input.environment;
|
|
1425
|
+
payload.schemaVersion = input.schemaVersion;
|
|
1426
|
+
if (input.correlationId) {
|
|
1427
|
+
payload.correlationId = input.correlationId;
|
|
1428
|
+
}
|
|
1429
|
+
return prepareEvent({
|
|
1430
|
+
eventTypeSlug: input.eventTypeSlug,
|
|
1431
|
+
schemaVersion: input.schemaVersion,
|
|
1432
|
+
timestamp: new Date().toISOString(),
|
|
1433
|
+
companySlug: input.companySlug,
|
|
1434
|
+
context: { device: { type: "server" } },
|
|
1435
|
+
payload,
|
|
1436
|
+
});
|
|
1437
|
+
}
|
|
1438
|
+
export function prepareEvent(event, options = {}) {
|
|
1439
|
+
if (options.mode === "browser-cookieless") {
|
|
1440
|
+
return {
|
|
1441
|
+
...event,
|
|
1442
|
+
eventUuid: event.eventUuid || randomUUID(),
|
|
1443
|
+
sessionId: event.sessionId ?? "",
|
|
1444
|
+
anonymousId: event.anonymousId ?? "",
|
|
1445
|
+
};
|
|
1446
|
+
}
|
|
1447
|
+
return {
|
|
1448
|
+
...event,
|
|
1449
|
+
eventUuid: event.eventUuid || randomUUID(),
|
|
1450
|
+
sessionId: event.sessionId || randomUUID(),
|
|
1451
|
+
anonymousId: event.anonymousId || randomUUID(),
|
|
1452
|
+
};
|
|
1453
|
+
}
|
|
1454
|
+
export class RetryableError extends Error {
|
|
1455
|
+
}
|
|
1456
|
+
function transportRequestError(error) {
|
|
1457
|
+
if (error instanceof Error && error.name === "AbortError")
|
|
1458
|
+
return error;
|
|
1459
|
+
return new CustdRequestError(null, "transport_unavailable", "bounded", { action: "retry", maxRetries: 1 }, undefined, { cause: error });
|
|
1460
|
+
}
|
|
1461
|
+
async function responseRequestError(response, fallbackCode, fallbackMessage, responseText) {
|
|
1462
|
+
const text = responseText ??
|
|
1463
|
+
(await response
|
|
1464
|
+
.clone()
|
|
1465
|
+
.text()
|
|
1466
|
+
.catch(() => ""));
|
|
1467
|
+
let problem;
|
|
1468
|
+
try {
|
|
1469
|
+
const parsed = JSON.parse(text);
|
|
1470
|
+
if (parsed && typeof parsed === "object" && parsed.status === response.status)
|
|
1471
|
+
problem = parsed;
|
|
1472
|
+
}
|
|
1473
|
+
catch {
|
|
1474
|
+
problem = undefined;
|
|
1475
|
+
}
|
|
1476
|
+
const retryability = problem?.retryability ?? (response.status === 429 || response.status >= 500 ? "bounded" : "none");
|
|
1477
|
+
const nextAction = problem?.nextAction ??
|
|
1478
|
+
(retryability === "bounded" ? { action: "retry", maxRetries: 1 } : { action: "none" });
|
|
1479
|
+
const code = problem?.code || fallbackCode;
|
|
1480
|
+
const requestError = new CustdRequestError(response.status, code, retryability, nextAction, problem);
|
|
1481
|
+
if (fallbackMessage)
|
|
1482
|
+
requestError.message = fallbackMessage;
|
|
1483
|
+
return requestError;
|
|
1484
|
+
}
|
|
1485
|
+
// CustdProblemError carries the decoded RFC 9457 problem document (when the
|
|
1486
|
+
// server sent one) and, for batch sends, the failed per-event results so a
|
|
1487
|
+
// caller can inspect every rejection without re-probing the API.
|
|
1488
|
+
export class CustdProblemError extends Error {
|
|
1489
|
+
constructor(message, problem, failures = []) {
|
|
1490
|
+
super(message);
|
|
1491
|
+
this.name = "CustdProblemError";
|
|
1492
|
+
this.problem = problem;
|
|
1493
|
+
this.failures = failures;
|
|
1494
|
+
}
|
|
1495
|
+
}
|
|
1496
|
+
// problemError decodes an RFC 9457 problem document from an error response and
|
|
1497
|
+
// wraps it in a CustdProblemError. When the body is missing or unparseable it
|
|
1498
|
+
// falls back to the supplied status-only message so callers still get an error.
|
|
1499
|
+
async function problemError(response, fallbackMessage) {
|
|
1500
|
+
const text = await response.text().catch(() => "");
|
|
1501
|
+
if (text === "") {
|
|
1502
|
+
return new CustdProblemError(fallbackMessage);
|
|
1503
|
+
}
|
|
1504
|
+
let problem;
|
|
1505
|
+
try {
|
|
1506
|
+
problem = JSON.parse(text);
|
|
1507
|
+
}
|
|
1508
|
+
catch {
|
|
1509
|
+
return new CustdProblemError(fallbackMessage);
|
|
1510
|
+
}
|
|
1511
|
+
const message = problem.detail || problem.title || fallbackMessage;
|
|
1512
|
+
return new CustdProblemError(`custd: ${message}`, problem);
|
|
1513
|
+
}
|
|
1514
|
+
const dogfoodProtectedPayloadFields = new Set([
|
|
1515
|
+
"sourcesystem",
|
|
1516
|
+
"sourcecompany",
|
|
1517
|
+
"environment",
|
|
1518
|
+
"schemaversion",
|
|
1519
|
+
"correlationid",
|
|
1520
|
+
]);
|
|
1521
|
+
const dogfoodForbiddenPayloadFields = new Set([
|
|
1522
|
+
"apikey",
|
|
1523
|
+
"authorization",
|
|
1524
|
+
"password",
|
|
1525
|
+
"rawapiresponse",
|
|
1526
|
+
"token",
|
|
1527
|
+
"signedurl",
|
|
1528
|
+
"rawprompt",
|
|
1529
|
+
"oauthcode",
|
|
1530
|
+
"devicesecret",
|
|
1531
|
+
"providercredential",
|
|
1532
|
+
]);
|
|
1533
|
+
const forbiddenReportingTrustKeys = new Set([
|
|
1534
|
+
"rawpayload",
|
|
1535
|
+
"sql",
|
|
1536
|
+
"token",
|
|
1537
|
+
"secret",
|
|
1538
|
+
"stack",
|
|
1539
|
+
"email",
|
|
1540
|
+
"ipaddress",
|
|
1541
|
+
"hostname",
|
|
1542
|
+
"orderid",
|
|
1543
|
+
"carttoken",
|
|
1544
|
+
]);
|
|
1545
|
+
function containsForbiddenReportingTrustKey(value) {
|
|
1546
|
+
if (Array.isArray(value)) {
|
|
1547
|
+
return value.some(containsForbiddenReportingTrustKey);
|
|
1548
|
+
}
|
|
1549
|
+
if (!value || typeof value !== "object") {
|
|
1550
|
+
return false;
|
|
1551
|
+
}
|
|
1552
|
+
return Object.entries(value).some(([key, child]) => forbiddenReportingTrustKeys.has(key.toLowerCase()) || containsForbiddenReportingTrustKey(child));
|
|
1553
|
+
}
|
|
1554
|
+
function sanitizeDogfoodPayload(payload, prefix = "") {
|
|
1555
|
+
const cleaned = {};
|
|
1556
|
+
const droppedKeys = [];
|
|
1557
|
+
for (const [key, value] of Object.entries(payload)) {
|
|
1558
|
+
if (!dogfoodPayloadFieldAllowed(key)) {
|
|
1559
|
+
droppedKeys.push(`${prefix}${key}`);
|
|
1560
|
+
continue;
|
|
1561
|
+
}
|
|
1562
|
+
if (value != null && typeof value === "object" && !Array.isArray(value)) {
|
|
1563
|
+
const nested = sanitizeDogfoodPayload(value, `${prefix}${key}.`);
|
|
1564
|
+
cleaned[key] = nested.payload;
|
|
1565
|
+
droppedKeys.push(...nested.droppedKeys);
|
|
1566
|
+
}
|
|
1567
|
+
else {
|
|
1568
|
+
cleaned[key] = value;
|
|
1569
|
+
}
|
|
1570
|
+
}
|
|
1571
|
+
return { payload: cleaned, droppedKeys };
|
|
1572
|
+
}
|
|
1573
|
+
function dogfoodPayloadFieldAllowed(key) {
|
|
1574
|
+
const normalized = key.toLowerCase().replace(/_/g, "");
|
|
1575
|
+
return !dogfoodProtectedPayloadFields.has(normalized) && !dogfoodForbiddenPayloadFields.has(normalized);
|
|
1576
|
+
}
|
|
1577
|
+
function brokerBaseUrl(env) {
|
|
1578
|
+
const explicit = brokerEnvValue(env, "CUSTD_BASE_URL", "CUSTD_API_BASE_URL");
|
|
1579
|
+
if (explicit) {
|
|
1580
|
+
return normalizeCustdBaseUrl(explicit);
|
|
1581
|
+
}
|
|
1582
|
+
const endpoint = brokerEnvValue(env, "CUSTD_PROVISIONING_ENDPOINT", "PROVISIONING_ENDPOINT", "CUSTD_TENANT_ADMIN_ENDPOINT", "TENANT_ADMIN_ENDPOINT");
|
|
1583
|
+
if (!endpoint) {
|
|
1584
|
+
throw new Error("custd: broker env missing CUSTD_BASE_URL or CUSTD_PROVISIONING_ENDPOINT");
|
|
1585
|
+
}
|
|
1586
|
+
return normalizeCustdBaseUrl(endpoint);
|
|
1587
|
+
}
|
|
1588
|
+
function normalizeCustdBaseUrl(rawUrl) {
|
|
1589
|
+
const url = new URL(rawUrl);
|
|
1590
|
+
const suffixes = [
|
|
1591
|
+
"/api/v1/managed-audit/provision",
|
|
1592
|
+
"/api/v1/producer-provisioning",
|
|
1593
|
+
"/api/v1/admin/tenants",
|
|
1594
|
+
"/api/v1",
|
|
1595
|
+
];
|
|
1596
|
+
for (const suffix of suffixes) {
|
|
1597
|
+
if (url.pathname.endsWith(suffix)) {
|
|
1598
|
+
url.pathname = url.pathname.slice(0, -suffix.length) || "/";
|
|
1599
|
+
break;
|
|
1600
|
+
}
|
|
1601
|
+
}
|
|
1602
|
+
url.search = "";
|
|
1603
|
+
url.hash = "";
|
|
1604
|
+
return url.toString().replace(/\/$/, "");
|
|
1605
|
+
}
|
|
1606
|
+
function requireBrokerEnv(env, ...keys) {
|
|
1607
|
+
const value = brokerEnvValue(env, ...keys);
|
|
1608
|
+
if (!value) {
|
|
1609
|
+
throw new Error(`custd: broker env missing ${keys[0]}`);
|
|
1610
|
+
}
|
|
1611
|
+
return value;
|
|
1612
|
+
}
|
|
1613
|
+
function brokerEnvValue(env, ...keys) {
|
|
1614
|
+
for (const key of keys) {
|
|
1615
|
+
const value = env[key];
|
|
1616
|
+
if (typeof value === "string" && value.trim() !== "") {
|
|
1617
|
+
return value;
|
|
1618
|
+
}
|
|
1619
|
+
}
|
|
1620
|
+
return undefined;
|
|
1621
|
+
}
|
|
1622
|
+
function assertSecureOrLocalHTTP(rawUrl, field) {
|
|
1623
|
+
const parsed = new URL(rawUrl);
|
|
1624
|
+
if (parsed.protocol === "https:") {
|
|
1625
|
+
return;
|
|
1626
|
+
}
|
|
1627
|
+
if (parsed.protocol === "http:" && isLocalHostname(parsed.hostname)) {
|
|
1628
|
+
return;
|
|
1629
|
+
}
|
|
1630
|
+
throw new Error(`custd: ${field} must use https unless it targets localhost`);
|
|
1631
|
+
}
|
|
1632
|
+
function isLocalHostname(hostname) {
|
|
1633
|
+
return (hostname === "localhost" || hostname === "127.0.0.1" || hostname === "::1" || hostname === "host.docker.internal");
|
|
1634
|
+
}
|
|
1635
|
+
export function normalizeRetryOptions(options) {
|
|
1636
|
+
return {
|
|
1637
|
+
maxAttempts: options?.maxAttempts ?? 3,
|
|
1638
|
+
baseDelayMs: options?.baseDelayMs ?? 200,
|
|
1639
|
+
maxDelayMs: options?.maxDelayMs ?? 2000,
|
|
1640
|
+
jitter: options?.jitter ?? 0.2,
|
|
1641
|
+
retryOnStatuses: options?.retryOnStatuses ?? [408, 429, 500, 502, 503, 504],
|
|
1642
|
+
};
|
|
1643
|
+
}
|
|
1644
|
+
export async function withRetry(options, op) {
|
|
1645
|
+
let attempt = 0;
|
|
1646
|
+
for (;;) {
|
|
1647
|
+
attempt++;
|
|
1648
|
+
try {
|
|
1649
|
+
return await op();
|
|
1650
|
+
}
|
|
1651
|
+
catch (err) {
|
|
1652
|
+
const retryable = err instanceof RetryableError || err instanceof TypeError;
|
|
1653
|
+
if (!retryable || attempt >= options.maxAttempts) {
|
|
1654
|
+
throw err;
|
|
1655
|
+
}
|
|
1656
|
+
const delay = backoffDelay(options, attempt);
|
|
1657
|
+
await sleep(delay);
|
|
1658
|
+
}
|
|
1659
|
+
}
|
|
1660
|
+
}
|
|
1661
|
+
function backoffDelay(options, attempt) {
|
|
1662
|
+
const exp = options.baseDelayMs * 2 ** (attempt - 1);
|
|
1663
|
+
const capped = Math.min(exp, options.maxDelayMs);
|
|
1664
|
+
const jitter = capped * options.jitter * (Math.random() * 2 - 1);
|
|
1665
|
+
return Math.max(0, capped + jitter);
|
|
1666
|
+
}
|
|
1667
|
+
function sleep(ms) {
|
|
1668
|
+
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
1669
|
+
}
|
|
1670
|
+
function isOnline() {
|
|
1671
|
+
if (typeof navigator === "undefined") {
|
|
1672
|
+
return true;
|
|
1673
|
+
}
|
|
1674
|
+
if (typeof navigator.onLine !== "boolean") {
|
|
1675
|
+
return true;
|
|
1676
|
+
}
|
|
1677
|
+
return navigator.onLine;
|
|
1678
|
+
}
|
|
1679
|
+
// uuidv7 returns a canonical RFC 9562 version 7 UUID. Custd requires one as the
|
|
1680
|
+
// Idempotency-Key of an OAuth client mutation.
|
|
1681
|
+
function uuidv7() {
|
|
1682
|
+
const bytes = new Uint8Array(16);
|
|
1683
|
+
if (typeof crypto !== "undefined" && typeof crypto.getRandomValues === "function") {
|
|
1684
|
+
crypto.getRandomValues(bytes);
|
|
1685
|
+
}
|
|
1686
|
+
else {
|
|
1687
|
+
for (let index = 0; index < bytes.length; index += 1) {
|
|
1688
|
+
bytes[index] = Math.floor(Math.random() * 256);
|
|
1689
|
+
}
|
|
1690
|
+
}
|
|
1691
|
+
let timestamp = Date.now();
|
|
1692
|
+
for (let index = 5; index >= 0; index -= 1) {
|
|
1693
|
+
bytes[index] = timestamp % 256;
|
|
1694
|
+
timestamp = Math.floor(timestamp / 256);
|
|
1695
|
+
}
|
|
1696
|
+
bytes[6] = (bytes[6] & 0x0f) | 0x70;
|
|
1697
|
+
bytes[8] = (bytes[8] & 0x3f) | 0x80;
|
|
1698
|
+
const hex = Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join("");
|
|
1699
|
+
return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
|
|
1700
|
+
}
|
|
1701
|
+
function randomUUID() {
|
|
1702
|
+
if (typeof crypto !== "undefined" && typeof crypto.randomUUID === "function") {
|
|
1703
|
+
return crypto.randomUUID();
|
|
1704
|
+
}
|
|
1705
|
+
return "10000000-1000-4000-8000-100000000000".replace(/[018]/g, (c) => (Number(c) ^ ((Math.random() * 16) >> (Number(c) / 4))).toString(16));
|
|
1706
|
+
}
|