@oneidentity/safeguard 7.4.0 → 8.0.0-pre36954
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/LICENSE +201 -201
- package/README.md +408 -279
- package/dist/browser-C_ziogDF.d.ts +447 -0
- package/dist/browser-C_ziogDF.d.ts.map +1 -0
- package/dist/browser.d.ts +447 -0
- package/dist/browser.js +756 -0
- package/dist/browser.js.map +1 -0
- package/dist/events-RcqBZBsR.d.ts +185 -0
- package/dist/events-RcqBZBsR.d.ts.map +1 -0
- package/dist/events-zHsrmRBj.d.cts +185 -0
- package/dist/events-zHsrmRBj.d.cts.map +1 -0
- package/dist/events.cjs +190 -0
- package/dist/events.cjs.map +1 -0
- package/dist/events.d.cts +166 -0
- package/dist/events.d.ts +166 -0
- package/dist/events.js +188 -0
- package/dist/events.js.map +1 -0
- package/dist/index-BN3IescB.d.cts +668 -0
- package/dist/index-BN3IescB.d.cts.map +1 -0
- package/dist/index-ir5Qeequ.d.ts +668 -0
- package/dist/index-ir5Qeequ.d.ts.map +1 -0
- package/dist/index.cjs +1248 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +668 -0
- package/dist/index.d.ts +668 -0
- package/dist/index.js +1215 -0
- package/dist/index.js.map +1 -0
- package/package.json +100 -45
- package/src/LocalStorage.js +0 -72
- package/src/README.md +0 -67
- package/src/SessionStorage.js +0 -170
- package/src/safeguard.js +0 -937
- package/src/safeguard.min.js +0 -1
- package/src/safeguardJsAccessTokenChecker.js +0 -131
- package/src/safeguardJsAccessTokenChecker.min.js +0 -1
package/dist/browser.js
ADDED
|
@@ -0,0 +1,756 @@
|
|
|
1
|
+
//#region \0rolldown/runtime.js
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __exportAll = (all, no_symbols) => {
|
|
4
|
+
let target = {};
|
|
5
|
+
for (var name in all) __defProp(target, name, {
|
|
6
|
+
get: all[name],
|
|
7
|
+
enumerable: true
|
|
8
|
+
});
|
|
9
|
+
if (!no_symbols) __defProp(target, Symbol.toStringTag, { value: "Module" });
|
|
10
|
+
return target;
|
|
11
|
+
};
|
|
12
|
+
//#endregion
|
|
13
|
+
//#region src/types.ts
|
|
14
|
+
/**
|
|
15
|
+
* Safeguard appliance service endpoints.
|
|
16
|
+
*/
|
|
17
|
+
let Service = /* @__PURE__ */ function(Service) {
|
|
18
|
+
Service["CORE"] = "core";
|
|
19
|
+
Service["APPLIANCE"] = "appliance";
|
|
20
|
+
Service["NOTIFICATION"] = "notification";
|
|
21
|
+
Service["A2A"] = "a2a";
|
|
22
|
+
Service["EVENT"] = "event";
|
|
23
|
+
Service["RSTS"] = "RSTS";
|
|
24
|
+
return Service;
|
|
25
|
+
}({});
|
|
26
|
+
/**
|
|
27
|
+
* HTTP methods supported by the Safeguard API.
|
|
28
|
+
*/
|
|
29
|
+
let HttpMethod = /* @__PURE__ */ function(HttpMethod) {
|
|
30
|
+
HttpMethod["GET"] = "GET";
|
|
31
|
+
HttpMethod["POST"] = "POST";
|
|
32
|
+
HttpMethod["PUT"] = "PUT";
|
|
33
|
+
HttpMethod["DELETE"] = "DELETE";
|
|
34
|
+
HttpMethod["PATCH"] = "PATCH";
|
|
35
|
+
return HttpMethod;
|
|
36
|
+
}({});
|
|
37
|
+
//#endregion
|
|
38
|
+
//#region src/errors.ts
|
|
39
|
+
var errors_exports = /* @__PURE__ */ __exportAll({
|
|
40
|
+
ApiError: () => ApiError,
|
|
41
|
+
AuthenticationError: () => AuthenticationError,
|
|
42
|
+
AuthorizationError: () => AuthorizationError,
|
|
43
|
+
ConfigurationError: () => ConfigurationError,
|
|
44
|
+
NotFoundError: () => NotFoundError,
|
|
45
|
+
SafeguardError: () => SafeguardError,
|
|
46
|
+
TransportError: () => TransportError
|
|
47
|
+
});
|
|
48
|
+
/**
|
|
49
|
+
* Error hierarchy for the Safeguard SDK.
|
|
50
|
+
*
|
|
51
|
+
* SafeguardError
|
|
52
|
+
* ├── ApiError (HTTP errors from Safeguard API)
|
|
53
|
+
* │ ├── AuthenticationError (401)
|
|
54
|
+
* │ ├── AuthorizationError (403)
|
|
55
|
+
* │ └── NotFoundError (404)
|
|
56
|
+
* ├── TransportError (Network/connection failures)
|
|
57
|
+
* └── ConfigurationError (Invalid client options)
|
|
58
|
+
*/
|
|
59
|
+
var SafeguardError = class extends Error {
|
|
60
|
+
constructor(message, options) {
|
|
61
|
+
super(message, options);
|
|
62
|
+
this.name = "SafeguardError";
|
|
63
|
+
}
|
|
64
|
+
};
|
|
65
|
+
var ApiError = class ApiError extends SafeguardError {
|
|
66
|
+
status;
|
|
67
|
+
body;
|
|
68
|
+
constructor(message, status, body = null, options) {
|
|
69
|
+
super(message, options);
|
|
70
|
+
this.name = "ApiError";
|
|
71
|
+
this.status = status;
|
|
72
|
+
this.body = body;
|
|
73
|
+
}
|
|
74
|
+
/**
|
|
75
|
+
* Creates an appropriate ApiError subclass based on HTTP status code.
|
|
76
|
+
*/
|
|
77
|
+
static fromResponse(status, body) {
|
|
78
|
+
const parsed = ApiError.parseBody(body);
|
|
79
|
+
const message = ApiError.buildMessage(status, parsed);
|
|
80
|
+
switch (status) {
|
|
81
|
+
case 401: return new AuthenticationError(message, parsed);
|
|
82
|
+
case 403: return new AuthorizationError(message, parsed);
|
|
83
|
+
case 404: return new NotFoundError(message, parsed);
|
|
84
|
+
default: return new ApiError(message, status, parsed);
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
static parseBody(body) {
|
|
88
|
+
if (body === null || body === void 0) return null;
|
|
89
|
+
if (typeof body === "object") return body;
|
|
90
|
+
try {
|
|
91
|
+
return JSON.parse(body);
|
|
92
|
+
} catch {
|
|
93
|
+
return { Message: body };
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
static buildMessage(status, body) {
|
|
97
|
+
const apiMessage = body?.Message ?? body?.InnerError?.Message;
|
|
98
|
+
if (apiMessage) return `HTTP ${String(status)}: ${apiMessage}`;
|
|
99
|
+
return `HTTP ${String(status)}`;
|
|
100
|
+
}
|
|
101
|
+
};
|
|
102
|
+
var AuthenticationError = class extends ApiError {
|
|
103
|
+
constructor(message, body = null, options) {
|
|
104
|
+
super(message, 401, body, options);
|
|
105
|
+
this.name = "AuthenticationError";
|
|
106
|
+
}
|
|
107
|
+
};
|
|
108
|
+
var AuthorizationError = class extends ApiError {
|
|
109
|
+
constructor(message, body = null, options) {
|
|
110
|
+
super(message, 403, body, options);
|
|
111
|
+
this.name = "AuthorizationError";
|
|
112
|
+
}
|
|
113
|
+
};
|
|
114
|
+
var NotFoundError = class extends ApiError {
|
|
115
|
+
constructor(message, body = null, options) {
|
|
116
|
+
super(message, 404, body, options);
|
|
117
|
+
this.name = "NotFoundError";
|
|
118
|
+
}
|
|
119
|
+
};
|
|
120
|
+
var TransportError = class extends SafeguardError {
|
|
121
|
+
constructor(message, options) {
|
|
122
|
+
super(message, options);
|
|
123
|
+
this.name = "TransportError";
|
|
124
|
+
}
|
|
125
|
+
};
|
|
126
|
+
var ConfigurationError = class extends SafeguardError {
|
|
127
|
+
constructor(message, options) {
|
|
128
|
+
super(message, options);
|
|
129
|
+
this.name = "ConfigurationError";
|
|
130
|
+
}
|
|
131
|
+
};
|
|
132
|
+
//#endregion
|
|
133
|
+
//#region src/secret.ts
|
|
134
|
+
const REDACTED = "[REDACTED]";
|
|
135
|
+
/**
|
|
136
|
+
* A wrapper that prevents accidental logging of sensitive values.
|
|
137
|
+
*
|
|
138
|
+
* - `toString()` returns "[REDACTED]"
|
|
139
|
+
* - `toJSON()` returns "[REDACTED]"
|
|
140
|
+
* - `console.log(secretValue)` prints "[REDACTED]"
|
|
141
|
+
* - `.expose()` returns the raw value when intentionally needed
|
|
142
|
+
*/
|
|
143
|
+
var SecretValue = class {
|
|
144
|
+
#value;
|
|
145
|
+
constructor(value) {
|
|
146
|
+
this.#value = value;
|
|
147
|
+
}
|
|
148
|
+
/** Returns the raw secret. Use only when you intentionally need the plaintext. */
|
|
149
|
+
expose() {
|
|
150
|
+
return this.#value;
|
|
151
|
+
}
|
|
152
|
+
toString() {
|
|
153
|
+
return REDACTED;
|
|
154
|
+
}
|
|
155
|
+
toJSON() {
|
|
156
|
+
return REDACTED;
|
|
157
|
+
}
|
|
158
|
+
/** Node.js custom inspect (prevents leaking in console.log / util.inspect). */
|
|
159
|
+
[Symbol.for("nodejs.util.inspect.custom")]() {
|
|
160
|
+
return REDACTED;
|
|
161
|
+
}
|
|
162
|
+
get [Symbol.toStringTag]() {
|
|
163
|
+
return "SecretValue";
|
|
164
|
+
}
|
|
165
|
+
};
|
|
166
|
+
//#endregion
|
|
167
|
+
//#region src/utils.ts
|
|
168
|
+
/**
|
|
169
|
+
* Validates that a host string is a bare hostname or IP address.
|
|
170
|
+
* Rejects URLs, paths, query strings, userinfo, and embedded ports.
|
|
171
|
+
*
|
|
172
|
+
* @throws {ConfigurationError} if the host contains disallowed characters
|
|
173
|
+
*/
|
|
174
|
+
function validateHost(host) {
|
|
175
|
+
if (!host) throw new ConfigurationError("Host must not be empty");
|
|
176
|
+
if (host.trim() !== host) throw new ConfigurationError("Host must not contain leading or trailing whitespace");
|
|
177
|
+
if (/^[a-z][a-z0-9+.-]*:\/\//i.test(host)) throw new ConfigurationError(`Host must be a bare hostname or IP, not a URL. Remove the protocol prefix (e.g., use "${host.replace(/^[a-z][a-z0-9+.-]*:\/\//i, "")}")`);
|
|
178
|
+
if (/[/?#@]/.test(host)) throw new ConfigurationError("Host must be a bare hostname or IP address — must not contain /, ?, #, or @");
|
|
179
|
+
if (/:\d+$/.test(host) && !host.startsWith("[")) throw new ConfigurationError("Host must not include a port number. The SDK always connects over HTTPS (port 443).");
|
|
180
|
+
return host;
|
|
181
|
+
}
|
|
182
|
+
/**
|
|
183
|
+
* Builds the base URL for a Safeguard service endpoint.
|
|
184
|
+
*
|
|
185
|
+
* @example
|
|
186
|
+
* buildServiceUrl('appliance.example.com', Service.CORE)
|
|
187
|
+
* // => 'https://appliance.example.com/service/core'
|
|
188
|
+
*/
|
|
189
|
+
function buildServiceUrl(host, service) {
|
|
190
|
+
if (service === "RSTS") return `https://${host}/RSTS`;
|
|
191
|
+
return `https://${host}/service/${service}`;
|
|
192
|
+
}
|
|
193
|
+
/**
|
|
194
|
+
* Builds a full API URL including path and optional query parameters.
|
|
195
|
+
*
|
|
196
|
+
* @example
|
|
197
|
+
* buildRequestUrl('appliance.example.com', Service.CORE, 'v4/Users', { filter: 'Name eq "admin"' })
|
|
198
|
+
* // => 'https://appliance.example.com/service/core/v4/Users?filter=Name+eq+%22admin%22'
|
|
199
|
+
*/
|
|
200
|
+
function buildRequestUrl(host, service, relativeUrl, query) {
|
|
201
|
+
const base = buildServiceUrl(host, service);
|
|
202
|
+
const path = relativeUrl.startsWith("/") ? relativeUrl.slice(1) : relativeUrl;
|
|
203
|
+
const url = new URL(`${base}/${path}`);
|
|
204
|
+
if (query) for (const [key, value] of Object.entries(query)) url.searchParams.set(key, String(value));
|
|
205
|
+
return url.toString();
|
|
206
|
+
}
|
|
207
|
+
/**
|
|
208
|
+
* Encodes bytes to a URL-safe base64 string (no padding).
|
|
209
|
+
*/
|
|
210
|
+
function base64UrlEncode(bytes) {
|
|
211
|
+
const binary = String.fromCharCode(...bytes);
|
|
212
|
+
return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
|
|
213
|
+
}
|
|
214
|
+
/**
|
|
215
|
+
* Generates a cryptographically random code verifier for PKCE.
|
|
216
|
+
* Returns a 43-character base64url string (32 random bytes).
|
|
217
|
+
*/
|
|
218
|
+
function generateCodeVerifier() {
|
|
219
|
+
const bytes = new Uint8Array(32);
|
|
220
|
+
crypto.getRandomValues(bytes);
|
|
221
|
+
return base64UrlEncode(bytes);
|
|
222
|
+
}
|
|
223
|
+
/**
|
|
224
|
+
* Computes the S256 code challenge from a code verifier.
|
|
225
|
+
* Uses Web Crypto API (available in Node 20+ and all modern browsers).
|
|
226
|
+
*/
|
|
227
|
+
async function generateCodeChallenge(verifier) {
|
|
228
|
+
const data = new TextEncoder().encode(verifier);
|
|
229
|
+
const digest = await crypto.subtle.digest("SHA-256", data);
|
|
230
|
+
return base64UrlEncode(new Uint8Array(digest));
|
|
231
|
+
}
|
|
232
|
+
/**
|
|
233
|
+
* Generates a random state parameter for OAuth flows.
|
|
234
|
+
*/
|
|
235
|
+
function generateState() {
|
|
236
|
+
const bytes = new Uint8Array(16);
|
|
237
|
+
crypto.getRandomValues(bytes);
|
|
238
|
+
return base64UrlEncode(bytes);
|
|
239
|
+
}
|
|
240
|
+
/**
|
|
241
|
+
* Extracts the `exp` claim from a JWT and returns expiresIn (seconds from now).
|
|
242
|
+
* Returns undefined if the token is not a valid JWT or has no `exp` claim.
|
|
243
|
+
*/
|
|
244
|
+
function getTokenExpiresIn(jwt) {
|
|
245
|
+
try {
|
|
246
|
+
const parts = jwt.split(".");
|
|
247
|
+
if (parts.length !== 3) return void 0;
|
|
248
|
+
const payload = parts[1].replace(/-/g, "+").replace(/_/g, "/");
|
|
249
|
+
const json = atob(payload);
|
|
250
|
+
const claims = JSON.parse(json);
|
|
251
|
+
if (typeof claims.exp !== "number") return void 0;
|
|
252
|
+
const now = Math.floor(Date.now() / 1e3);
|
|
253
|
+
return Math.max(0, claims.exp - now);
|
|
254
|
+
} catch {
|
|
255
|
+
return;
|
|
256
|
+
}
|
|
257
|
+
}
|
|
258
|
+
//#endregion
|
|
259
|
+
//#region src/storage/memory.ts
|
|
260
|
+
/**
|
|
261
|
+
* In-memory storage provider. Default for Node.js environments.
|
|
262
|
+
* Data does not persist across process restarts.
|
|
263
|
+
*/
|
|
264
|
+
var MemoryStorage = class {
|
|
265
|
+
#store = /* @__PURE__ */ new Map();
|
|
266
|
+
get(key) {
|
|
267
|
+
return this.#store.get(key) ?? null;
|
|
268
|
+
}
|
|
269
|
+
set(key, value) {
|
|
270
|
+
this.#store.set(key, value);
|
|
271
|
+
}
|
|
272
|
+
remove(key) {
|
|
273
|
+
this.#store.delete(key);
|
|
274
|
+
}
|
|
275
|
+
clear() {
|
|
276
|
+
this.#store.clear();
|
|
277
|
+
}
|
|
278
|
+
};
|
|
279
|
+
//#endregion
|
|
280
|
+
//#region src/storage/session.ts
|
|
281
|
+
/**
|
|
282
|
+
* Browser sessionStorage adapter. Data persists for the browser tab lifetime.
|
|
283
|
+
* Requires a DOM environment (browser or jsdom).
|
|
284
|
+
*/
|
|
285
|
+
var BrowserSessionStorage = class {
|
|
286
|
+
get(key) {
|
|
287
|
+
return sessionStorage.getItem(key);
|
|
288
|
+
}
|
|
289
|
+
set(key, value) {
|
|
290
|
+
sessionStorage.setItem(key, value);
|
|
291
|
+
}
|
|
292
|
+
remove(key) {
|
|
293
|
+
sessionStorage.removeItem(key);
|
|
294
|
+
}
|
|
295
|
+
clear() {
|
|
296
|
+
sessionStorage.clear();
|
|
297
|
+
}
|
|
298
|
+
};
|
|
299
|
+
//#endregion
|
|
300
|
+
//#region src/storage/types.ts
|
|
301
|
+
/** Well-known storage keys used by the SDK. */
|
|
302
|
+
const StorageKeys = {
|
|
303
|
+
STATE: "safeguard_state",
|
|
304
|
+
CODE_VERIFIER: "safeguard_code_verifier"
|
|
305
|
+
};
|
|
306
|
+
//#endregion
|
|
307
|
+
//#region src/http/browser.ts
|
|
308
|
+
/**
|
|
309
|
+
* Browser HTTP client using native fetch API.
|
|
310
|
+
* No TLS configuration needed — browser handles certificates.
|
|
311
|
+
*/
|
|
312
|
+
var BrowserHttpClient = class {
|
|
313
|
+
#credentials;
|
|
314
|
+
constructor(options) {
|
|
315
|
+
this.#credentials = options?.credentials ?? "include";
|
|
316
|
+
}
|
|
317
|
+
async request(options) {
|
|
318
|
+
const { url, method, headers, body, signal, timeout } = options;
|
|
319
|
+
const requestInit = {
|
|
320
|
+
method,
|
|
321
|
+
credentials: this.#credentials
|
|
322
|
+
};
|
|
323
|
+
if (headers) requestInit.headers = headers;
|
|
324
|
+
if (body != null) requestInit.body = body;
|
|
325
|
+
if (signal || timeout) {
|
|
326
|
+
const controller = new AbortController();
|
|
327
|
+
let timeoutId;
|
|
328
|
+
if (timeout) timeoutId = setTimeout(() => controller.abort(/* @__PURE__ */ new Error("Request timed out")), timeout);
|
|
329
|
+
requestInit.signal = signal ? AbortSignal.any([signal, controller.signal]) : controller.signal;
|
|
330
|
+
try {
|
|
331
|
+
return await this.#doFetch(url, requestInit);
|
|
332
|
+
} finally {
|
|
333
|
+
if (timeoutId !== void 0) clearTimeout(timeoutId);
|
|
334
|
+
}
|
|
335
|
+
}
|
|
336
|
+
return this.#doFetch(url, requestInit);
|
|
337
|
+
}
|
|
338
|
+
async #doFetch(url, init) {
|
|
339
|
+
const response = await fetch(url, init);
|
|
340
|
+
const responseHeaders = {};
|
|
341
|
+
response.headers.forEach((value, key) => {
|
|
342
|
+
responseHeaders[key] = value;
|
|
343
|
+
});
|
|
344
|
+
const responseBody = await response.text();
|
|
345
|
+
return {
|
|
346
|
+
status: response.status,
|
|
347
|
+
headers: responseHeaders,
|
|
348
|
+
body: responseBody
|
|
349
|
+
};
|
|
350
|
+
}
|
|
351
|
+
};
|
|
352
|
+
//#endregion
|
|
353
|
+
//#region src/auth/password.ts
|
|
354
|
+
/**
|
|
355
|
+
* Authenticates using username/password via RSTS Resource Owner grant.
|
|
356
|
+
*/
|
|
357
|
+
var PasswordAuth = class {
|
|
358
|
+
#username;
|
|
359
|
+
#password;
|
|
360
|
+
#provider;
|
|
361
|
+
constructor(options) {
|
|
362
|
+
if (!options.username) throw new ConfigurationError("PasswordAuth requires username");
|
|
363
|
+
if (!options.password) throw new ConfigurationError("PasswordAuth requires password");
|
|
364
|
+
if (!options.provider) throw new ConfigurationError("PasswordAuth requires provider");
|
|
365
|
+
this.#username = options.username;
|
|
366
|
+
this.#password = new SecretValue(options.password);
|
|
367
|
+
this.#provider = options.provider;
|
|
368
|
+
}
|
|
369
|
+
get description() {
|
|
370
|
+
return `PasswordAuth(${this.#username}@${this.#provider})`;
|
|
371
|
+
}
|
|
372
|
+
async authenticate(host, httpClient, _storage) {
|
|
373
|
+
const rstsToken = await this.#getRstsToken(host, httpClient);
|
|
374
|
+
return await this.#exchangeForUserToken(host, httpClient, rstsToken);
|
|
375
|
+
}
|
|
376
|
+
async refreshToken(host, httpClient, storage) {
|
|
377
|
+
return this.authenticate(host, httpClient, storage);
|
|
378
|
+
}
|
|
379
|
+
async #getRstsToken(host, httpClient) {
|
|
380
|
+
const body = JSON.stringify({
|
|
381
|
+
grant_type: "password",
|
|
382
|
+
username: this.#username,
|
|
383
|
+
password: this.#password.expose(),
|
|
384
|
+
scope: "rsts:sts:primaryproviderid:" + this.#provider.toLowerCase()
|
|
385
|
+
});
|
|
386
|
+
const response = await httpClient.request({
|
|
387
|
+
url: `https://${host}/RSTS/oauth2/token`,
|
|
388
|
+
method: "POST",
|
|
389
|
+
headers: { "Content-Type": "application/json" },
|
|
390
|
+
body
|
|
391
|
+
});
|
|
392
|
+
if (response.status !== 200) {
|
|
393
|
+
const { ApiError } = await Promise.resolve().then(() => errors_exports);
|
|
394
|
+
throw ApiError.fromResponse(response.status, response.body);
|
|
395
|
+
}
|
|
396
|
+
return JSON.parse(response.body).access_token;
|
|
397
|
+
}
|
|
398
|
+
async #exchangeForUserToken(host, httpClient, rstsToken) {
|
|
399
|
+
const response = await httpClient.request({
|
|
400
|
+
url: `https://${host}/service/core/v4/Token/LoginResponse`,
|
|
401
|
+
method: "POST",
|
|
402
|
+
headers: {
|
|
403
|
+
"Content-Type": "application/json",
|
|
404
|
+
Authorization: `Bearer ${rstsToken}`
|
|
405
|
+
},
|
|
406
|
+
body: JSON.stringify({ StsAccessToken: rstsToken })
|
|
407
|
+
});
|
|
408
|
+
if (response.status !== 200) {
|
|
409
|
+
const { ApiError } = await Promise.resolve().then(() => errors_exports);
|
|
410
|
+
throw ApiError.fromResponse(response.status, response.body);
|
|
411
|
+
}
|
|
412
|
+
const data = JSON.parse(response.body);
|
|
413
|
+
const tokenSet = {
|
|
414
|
+
accessToken: new SecretValue(data.UserToken),
|
|
415
|
+
acquiredAt: Date.now()
|
|
416
|
+
};
|
|
417
|
+
if (data.ExpiresIn != null) tokenSet.expiresIn = data.ExpiresIn;
|
|
418
|
+
else {
|
|
419
|
+
const expiresIn = getTokenExpiresIn(data.UserToken);
|
|
420
|
+
if (expiresIn != null) tokenSet.expiresIn = expiresIn;
|
|
421
|
+
}
|
|
422
|
+
return tokenSet;
|
|
423
|
+
}
|
|
424
|
+
};
|
|
425
|
+
//#endregion
|
|
426
|
+
//#region src/auth/pkce.ts
|
|
427
|
+
/**
|
|
428
|
+
* Authenticates using PKCE (Proof Key for Code Exchange) with browser redirect.
|
|
429
|
+
* For browser environments where the user is redirected to RSTS login.
|
|
430
|
+
*/
|
|
431
|
+
var PkceAuth = class {
|
|
432
|
+
#redirectUri;
|
|
433
|
+
#provider;
|
|
434
|
+
constructor(options) {
|
|
435
|
+
if (!options.redirectUri) throw new ConfigurationError("PkceAuth requires redirectUri");
|
|
436
|
+
if (!options.provider) throw new ConfigurationError("PkceAuth requires provider");
|
|
437
|
+
this.#redirectUri = options.redirectUri;
|
|
438
|
+
this.#provider = options.provider;
|
|
439
|
+
}
|
|
440
|
+
get description() {
|
|
441
|
+
return `PKCE(redirect=${this.#redirectUri})`;
|
|
442
|
+
}
|
|
443
|
+
/**
|
|
444
|
+
* Initiates the PKCE flow. If a stored authorization code exists (from callback),
|
|
445
|
+
* exchanges it for a token. Otherwise, redirects to RSTS login.
|
|
446
|
+
*/
|
|
447
|
+
async authenticate(host, httpClient, storage) {
|
|
448
|
+
const code = storage.get("safeguard_auth_code");
|
|
449
|
+
if (code) {
|
|
450
|
+
const verifier = storage.get(StorageKeys.CODE_VERIFIER);
|
|
451
|
+
if (!verifier) throw new ConfigurationError("PKCE code verifier not found in storage");
|
|
452
|
+
storage.remove("safeguard_auth_code");
|
|
453
|
+
storage.remove(StorageKeys.CODE_VERIFIER);
|
|
454
|
+
storage.remove(StorageKeys.STATE);
|
|
455
|
+
return this.#exchangeCode(host, httpClient, code, verifier);
|
|
456
|
+
}
|
|
457
|
+
await this.#initiateRedirect(host, storage);
|
|
458
|
+
throw new ConfigurationError("PKCE redirect initiated. Call handlePkceCallback() on the callback page.");
|
|
459
|
+
}
|
|
460
|
+
async #initiateRedirect(host, storage) {
|
|
461
|
+
const verifier = generateCodeVerifier();
|
|
462
|
+
const challenge = await generateCodeChallenge(verifier);
|
|
463
|
+
const state = generateState();
|
|
464
|
+
storage.set(StorageKeys.CODE_VERIFIER, verifier);
|
|
465
|
+
storage.set(StorageKeys.STATE, state);
|
|
466
|
+
const authUrl = `https://${host}/RSTS/Login?${new URLSearchParams({
|
|
467
|
+
response_type: "code",
|
|
468
|
+
client_id: "safeguard.js",
|
|
469
|
+
redirect_uri: this.#redirectUri,
|
|
470
|
+
scope: "rsts:sts:primaryproviderid:" + this.#provider,
|
|
471
|
+
code_challenge: challenge,
|
|
472
|
+
code_challenge_method: "S256",
|
|
473
|
+
state
|
|
474
|
+
}).toString()}`;
|
|
475
|
+
if (typeof window !== "undefined" && window.location) window.location.href = authUrl;
|
|
476
|
+
}
|
|
477
|
+
async #exchangeCode(host, httpClient, code, verifier) {
|
|
478
|
+
const body = new URLSearchParams({
|
|
479
|
+
grant_type: "authorization_code",
|
|
480
|
+
code,
|
|
481
|
+
redirect_uri: this.#redirectUri,
|
|
482
|
+
client_id: "safeguard.js",
|
|
483
|
+
code_verifier: verifier
|
|
484
|
+
});
|
|
485
|
+
const response = await httpClient.request({
|
|
486
|
+
url: `https://${host}/RSTS/oauth2/token`,
|
|
487
|
+
method: "POST",
|
|
488
|
+
headers: { "Content-Type": "application/x-www-form-urlencoded" },
|
|
489
|
+
body: body.toString()
|
|
490
|
+
});
|
|
491
|
+
if (response.status !== 200) {
|
|
492
|
+
const { ApiError } = await Promise.resolve().then(() => errors_exports);
|
|
493
|
+
throw ApiError.fromResponse(response.status, response.body);
|
|
494
|
+
}
|
|
495
|
+
const data = JSON.parse(response.body);
|
|
496
|
+
const userTokenResponse = await httpClient.request({
|
|
497
|
+
url: `https://${host}/service/core/v4/Token/LoginResponse`,
|
|
498
|
+
method: "POST",
|
|
499
|
+
headers: {
|
|
500
|
+
"Content-Type": "application/json",
|
|
501
|
+
Authorization: `Bearer ${data.access_token}`
|
|
502
|
+
},
|
|
503
|
+
body: JSON.stringify({ StsAccessToken: data.access_token })
|
|
504
|
+
});
|
|
505
|
+
if (userTokenResponse.status !== 200) {
|
|
506
|
+
const { ApiError } = await Promise.resolve().then(() => errors_exports);
|
|
507
|
+
throw ApiError.fromResponse(userTokenResponse.status, userTokenResponse.body);
|
|
508
|
+
}
|
|
509
|
+
const userData = JSON.parse(userTokenResponse.body);
|
|
510
|
+
const tokenSet = {
|
|
511
|
+
accessToken: new SecretValue(userData.UserToken),
|
|
512
|
+
acquiredAt: Date.now()
|
|
513
|
+
};
|
|
514
|
+
if (userData.ExpiresIn != null) tokenSet.expiresIn = userData.ExpiresIn;
|
|
515
|
+
return tokenSet;
|
|
516
|
+
}
|
|
517
|
+
};
|
|
518
|
+
//#endregion
|
|
519
|
+
//#region src/auth/pkce-callback.ts
|
|
520
|
+
/**
|
|
521
|
+
* Parses the PKCE callback URL and stores the authorization code.
|
|
522
|
+
* Call this on the callback/redirect page to complete the PKCE flow.
|
|
523
|
+
*
|
|
524
|
+
* This is the explicit replacement for the legacy `safeguardJsAccessTokenChecker.js`
|
|
525
|
+
* script that ran as a side-effect on import.
|
|
526
|
+
*
|
|
527
|
+
* @param storage - StorageProvider to persist the code
|
|
528
|
+
* @param url - The callback URL to parse (defaults to window.location.href)
|
|
529
|
+
* @returns The parsed code and state, or null if not a valid callback
|
|
530
|
+
*/
|
|
531
|
+
function handlePkceCallback(storage, url) {
|
|
532
|
+
const callbackUrl = url ?? (typeof window !== "undefined" ? window.location.href : "");
|
|
533
|
+
if (!callbackUrl) return null;
|
|
534
|
+
const parsed = new URL(callbackUrl);
|
|
535
|
+
const code = parsed.searchParams.get("code");
|
|
536
|
+
const state = parsed.searchParams.get("state");
|
|
537
|
+
if (!code || !state) return null;
|
|
538
|
+
const storedState = storage.get(StorageKeys.STATE);
|
|
539
|
+
if (storedState && storedState !== state) throw new ConfigurationError("PKCE state mismatch — possible CSRF attack");
|
|
540
|
+
storage.set("safeguard_auth_code", code);
|
|
541
|
+
return {
|
|
542
|
+
code,
|
|
543
|
+
state
|
|
544
|
+
};
|
|
545
|
+
}
|
|
546
|
+
//#endregion
|
|
547
|
+
//#region src/auth/token.ts
|
|
548
|
+
/**
|
|
549
|
+
* Uses a pre-existing access token. No authentication flow — the token is assumed valid.
|
|
550
|
+
* Useful when tokens are obtained externally or for service-to-service scenarios.
|
|
551
|
+
*/
|
|
552
|
+
var TokenAuth = class {
|
|
553
|
+
#accessToken;
|
|
554
|
+
constructor(options) {
|
|
555
|
+
if (!options.accessToken) throw new ConfigurationError("TokenAuth requires accessToken");
|
|
556
|
+
this.#accessToken = new SecretValue(options.accessToken);
|
|
557
|
+
}
|
|
558
|
+
get description() {
|
|
559
|
+
return "TokenAuth(pre-existing)";
|
|
560
|
+
}
|
|
561
|
+
async authenticate(_host, _httpClient, _storage) {
|
|
562
|
+
return {
|
|
563
|
+
accessToken: this.#accessToken,
|
|
564
|
+
acquiredAt: Date.now()
|
|
565
|
+
};
|
|
566
|
+
}
|
|
567
|
+
};
|
|
568
|
+
//#endregion
|
|
569
|
+
//#region src/auth/anonymous.ts
|
|
570
|
+
/**
|
|
571
|
+
* Anonymous authentication — no credentials.
|
|
572
|
+
* Used for accessing public Safeguard endpoints (e.g., appliance status).
|
|
573
|
+
*/
|
|
574
|
+
var AnonymousAuth = class {
|
|
575
|
+
get description() {
|
|
576
|
+
return "AnonymousAuth";
|
|
577
|
+
}
|
|
578
|
+
async authenticate(_host, _httpClient, _storage) {
|
|
579
|
+
return {
|
|
580
|
+
accessToken: new SecretValue(""),
|
|
581
|
+
acquiredAt: Date.now()
|
|
582
|
+
};
|
|
583
|
+
}
|
|
584
|
+
};
|
|
585
|
+
//#endregion
|
|
586
|
+
//#region src/client.ts
|
|
587
|
+
const DEFAULT_TIMEOUT = 3e5;
|
|
588
|
+
const DEFAULT_API_VERSION = "v4";
|
|
589
|
+
const TOKEN_REFRESH_MARGIN_MS = 6e4;
|
|
590
|
+
/**
|
|
591
|
+
* Main entry point for the Safeguard SDK.
|
|
592
|
+
* Instance-based — no global state. Multiple clients to different appliances are supported.
|
|
593
|
+
*/
|
|
594
|
+
var SafeguardClient = class {
|
|
595
|
+
#host;
|
|
596
|
+
#auth;
|
|
597
|
+
#apiVersion;
|
|
598
|
+
#timeout;
|
|
599
|
+
#autoRefresh;
|
|
600
|
+
#ca;
|
|
601
|
+
#verify;
|
|
602
|
+
#httpClient;
|
|
603
|
+
#storage;
|
|
604
|
+
#tokenSet;
|
|
605
|
+
#connected = false;
|
|
606
|
+
constructor(host, options) {
|
|
607
|
+
if (!host) throw new ConfigurationError("SafeguardClient requires a host");
|
|
608
|
+
if (!options.auth) throw new ConfigurationError("SafeguardClient requires an auth strategy");
|
|
609
|
+
this.#host = validateHost(host);
|
|
610
|
+
this.#auth = options.auth;
|
|
611
|
+
this.#apiVersion = options.apiVersion ?? DEFAULT_API_VERSION;
|
|
612
|
+
this.#timeout = options.timeout ?? DEFAULT_TIMEOUT;
|
|
613
|
+
this.#autoRefresh = options.autoRefresh !== false;
|
|
614
|
+
this.#ca = options.ca;
|
|
615
|
+
this.#verify = options.verify !== false;
|
|
616
|
+
this.#storage = new MemoryStorage();
|
|
617
|
+
}
|
|
618
|
+
/** The appliance hostname this client connects to. */
|
|
619
|
+
get host() {
|
|
620
|
+
return this.#host;
|
|
621
|
+
}
|
|
622
|
+
/** The API version prefix (e.g. 'v4'). */
|
|
623
|
+
get apiVersion() {
|
|
624
|
+
return this.#apiVersion;
|
|
625
|
+
}
|
|
626
|
+
/** Custom CA certificate, if provided. */
|
|
627
|
+
get ca() {
|
|
628
|
+
return this.#ca;
|
|
629
|
+
}
|
|
630
|
+
/** Whether TLS verification is enabled. */
|
|
631
|
+
get verify() {
|
|
632
|
+
return this.#verify;
|
|
633
|
+
}
|
|
634
|
+
/** Whether the client has an active authenticated session. */
|
|
635
|
+
get isConnected() {
|
|
636
|
+
return this.#connected;
|
|
637
|
+
}
|
|
638
|
+
/**
|
|
639
|
+
* Sets a custom StorageProvider (e.g., BrowserSessionStorage).
|
|
640
|
+
* Must be called before connect().
|
|
641
|
+
*/
|
|
642
|
+
setStorage(storage) {
|
|
643
|
+
this.#storage = storage;
|
|
644
|
+
return this;
|
|
645
|
+
}
|
|
646
|
+
/**
|
|
647
|
+
* Sets the HttpClient implementation. If not called, must be set before connect().
|
|
648
|
+
* The factory pattern allows platform-specific client injection:
|
|
649
|
+
* - Node: `new NodeHttpClient({ ca, rejectUnauthorized })`
|
|
650
|
+
* - Browser: `new BrowserHttpClient()`
|
|
651
|
+
*/
|
|
652
|
+
setHttpClient(httpClient) {
|
|
653
|
+
this.#httpClient = httpClient;
|
|
654
|
+
return this;
|
|
655
|
+
}
|
|
656
|
+
/**
|
|
657
|
+
* Authenticate and establish a session.
|
|
658
|
+
* @throws {AuthenticationError} if authentication fails
|
|
659
|
+
* @throws {ConfigurationError} if httpClient not set
|
|
660
|
+
*/
|
|
661
|
+
async connect() {
|
|
662
|
+
if (!this.#httpClient) throw new ConfigurationError("HttpClient not set. Call setHttpClient() before connect(), or use SafeguardClient.createNode() / SafeguardClient.createBrowser().");
|
|
663
|
+
this.#tokenSet = await this.#auth.authenticate(this.#host, this.#httpClient, this.#storage);
|
|
664
|
+
if (!this.#tokenSet.accessToken.expose()) throw new AuthenticationError("Authentication returned empty access token");
|
|
665
|
+
this.#connected = true;
|
|
666
|
+
}
|
|
667
|
+
/**
|
|
668
|
+
* Disconnect — dispose HTTP client and clear token.
|
|
669
|
+
*/
|
|
670
|
+
async disconnect() {
|
|
671
|
+
this.#tokenSet = void 0;
|
|
672
|
+
this.#connected = false;
|
|
673
|
+
this.#httpClient?.dispose?.();
|
|
674
|
+
}
|
|
675
|
+
/**
|
|
676
|
+
* Returns seconds until the current access token expires, or -1 if unknown.
|
|
677
|
+
*/
|
|
678
|
+
getAccessTokenLifetimeRemaining() {
|
|
679
|
+
if (!this.#tokenSet?.expiresIn) return -1;
|
|
680
|
+
const elapsed = (Date.now() - this.#tokenSet.acquiredAt) / 1e3;
|
|
681
|
+
return Math.max(0, this.#tokenSet.expiresIn - elapsed);
|
|
682
|
+
}
|
|
683
|
+
async get(service, relativeUrl, options) {
|
|
684
|
+
return this.invoke(service, "GET", relativeUrl, options);
|
|
685
|
+
}
|
|
686
|
+
async post(service, relativeUrl, options) {
|
|
687
|
+
return this.invoke(service, "POST", relativeUrl, options);
|
|
688
|
+
}
|
|
689
|
+
async put(service, relativeUrl, options) {
|
|
690
|
+
return this.invoke(service, "PUT", relativeUrl, options);
|
|
691
|
+
}
|
|
692
|
+
async delete(service, relativeUrl, options) {
|
|
693
|
+
return this.invoke(service, "DELETE", relativeUrl, options);
|
|
694
|
+
}
|
|
695
|
+
async patch(service, relativeUrl, options) {
|
|
696
|
+
return this.invoke(service, "PATCH", relativeUrl, options);
|
|
697
|
+
}
|
|
698
|
+
/**
|
|
699
|
+
* Low-level request method. Convenience verbs delegate here.
|
|
700
|
+
*
|
|
701
|
+
* When `options.fullResponse` is true, returns SafeguardResponse<T> with status + headers.
|
|
702
|
+
* Otherwise returns just the parsed response body as T.
|
|
703
|
+
*/
|
|
704
|
+
async invoke(service, method, relativeUrl, options) {
|
|
705
|
+
if (!this.#connected || !this.#httpClient) throw new ConfigurationError("Client not connected. Call connect() first.");
|
|
706
|
+
if (this.#autoRefresh) await this.#ensureValidToken();
|
|
707
|
+
const url = buildRequestUrl(this.#host, service, relativeUrl, options?.query);
|
|
708
|
+
const headers = {
|
|
709
|
+
Authorization: `Bearer ${this.#tokenSet.accessToken.expose()}`,
|
|
710
|
+
Accept: "application/json",
|
|
711
|
+
...options?.headers
|
|
712
|
+
};
|
|
713
|
+
let body = null;
|
|
714
|
+
if (options?.json != null) {
|
|
715
|
+
body = JSON.stringify(options.json);
|
|
716
|
+
headers["Content-Type"] = "application/json";
|
|
717
|
+
} else if (options?.body != null) body = options.body;
|
|
718
|
+
const requestOpts = {
|
|
719
|
+
url,
|
|
720
|
+
method,
|
|
721
|
+
headers,
|
|
722
|
+
body,
|
|
723
|
+
timeout: options?.timeout ?? this.#timeout
|
|
724
|
+
};
|
|
725
|
+
if (options?.signal) requestOpts.signal = options.signal;
|
|
726
|
+
const response = await this.#httpClient.request(requestOpts);
|
|
727
|
+
if (response.status >= 400) throw ApiError.fromResponse(response.status, response.body);
|
|
728
|
+
const data = response.body ? JSON.parse(response.body) : void 0;
|
|
729
|
+
if (options?.fullResponse) return {
|
|
730
|
+
data,
|
|
731
|
+
status: response.status,
|
|
732
|
+
headers: response.headers
|
|
733
|
+
};
|
|
734
|
+
return data;
|
|
735
|
+
}
|
|
736
|
+
async #ensureValidToken() {
|
|
737
|
+
if (!this.#tokenSet) return;
|
|
738
|
+
if (!this.#tokenSet.expiresIn) return;
|
|
739
|
+
const elapsed = Date.now() - this.#tokenSet.acquiredAt;
|
|
740
|
+
const expiresInMs = this.#tokenSet.expiresIn * 1e3;
|
|
741
|
+
if (elapsed + TOKEN_REFRESH_MARGIN_MS >= expiresInMs) {
|
|
742
|
+
if (this.#auth.refreshToken) {
|
|
743
|
+
const refreshed = await this.#auth.refreshToken(this.#host, this.#httpClient, this.#storage);
|
|
744
|
+
if (refreshed) {
|
|
745
|
+
this.#tokenSet = refreshed;
|
|
746
|
+
return;
|
|
747
|
+
}
|
|
748
|
+
}
|
|
749
|
+
this.#tokenSet = await this.#auth.authenticate(this.#host, this.#httpClient, this.#storage);
|
|
750
|
+
}
|
|
751
|
+
}
|
|
752
|
+
};
|
|
753
|
+
//#endregion
|
|
754
|
+
export { AnonymousAuth, ApiError, AuthenticationError, AuthorizationError, BrowserHttpClient, BrowserSessionStorage, ConfigurationError, HttpMethod, MemoryStorage, NotFoundError, PasswordAuth, PkceAuth, SafeguardClient, SafeguardError, SecretValue, Service, StorageKeys, TokenAuth, TransportError, base64UrlEncode, buildRequestUrl, buildServiceUrl, generateCodeChallenge, generateCodeVerifier, generateState, handlePkceCallback };
|
|
755
|
+
|
|
756
|
+
//# sourceMappingURL=browser.js.map
|