@securitydept/session-context-client 0.3.0-beta.2 → 0.3.0-beta.5
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 +6 -0
- package/dist/index.d.mts +160 -12
- package/dist/index.mjs +657 -2
- package/dist/index.mjs.map +1 -0
- package/package.json +12 -11
- package/dist/client-BcZv4X8b.mjs +0 -183
- package/dist/client-BcZv4X8b.mjs.map +0 -1
- package/dist/client-Dzfx3BXp.d.mts +0 -83
- package/dist/server/index.d.mts +0 -66
- package/dist/server/index.mjs +0 -50
- package/dist/server/index.mjs.map +0 -1
- package/dist/web/index.d.mts +0 -32
- package/dist/web/index.mjs +0 -22
- package/dist/web/index.mjs.map +0 -1
package/dist/index.mjs
CHANGED
|
@@ -1,2 +1,657 @@
|
|
|
1
|
-
import {
|
|
2
|
-
|
|
1
|
+
import { ClientError, ClientErrorKind, ENVIRONMENT_TOKEN, INJECTOR_TOKEN, IdentityPrincipalSchema, IdentityPrincipalWireSchema, ResourceSnapshotUpdateKind, ResourceStatus, RouterNavigationIntent, RouterNavigationMode, SYMBOL_DISPOSE, SecuritydeptDestroyRef, SecuritydeptInjectionToken, UriReferenceString, createCancellationTokenSource, createLinkedCancellationToken, createOnceAsyncLockCallable, createSignal, defineInstrumentMethodDecorator, describeError, formatValidationFailure, injectDisposableStackFrom, mapResource, readonlySignal, reduceResourceSnapshot, resourceFromSnapshots, validateWithSchemaSync, withDisposableStack } from "@securitydept/client";
|
|
2
|
+
import { RxEventReplaySubject, RxEventSubject, RxStateSignal, commandResponseData, concatCommand, dispatchCommandLocallyToStream } from "@securitydept/client/rx";
|
|
3
|
+
import { filter, from, lastValueFrom, take, takeUntil } from "rxjs";
|
|
4
|
+
import { v7 } from "uuid";
|
|
5
|
+
import { type } from "arktype";
|
|
6
|
+
//#region src/types.ts
|
|
7
|
+
const SessionContextErrorCode = {
|
|
8
|
+
OperationFailed: "session.operation_failed",
|
|
9
|
+
ClientDisposed: "session.client_disposed",
|
|
10
|
+
RouterUnavailable: "session.router_unavailable",
|
|
11
|
+
InvalidSessionPayload: "session.invalid_user_info_payload"
|
|
12
|
+
};
|
|
13
|
+
const SessionContextSource = { SessionContext: "session-context" };
|
|
14
|
+
const SessionContextEventType = {
|
|
15
|
+
SessionRefreshStarted: "session.refresh.started",
|
|
16
|
+
SessionRefreshSucceeded: "session.refresh.succeeded",
|
|
17
|
+
SessionRefreshFailed: "session.refresh.failed",
|
|
18
|
+
SessionLogoutStarted: "session.logout.started",
|
|
19
|
+
SessionLogoutSucceeded: "session.logout.succeeded",
|
|
20
|
+
SessionLogoutFailed: "session.logout.failed"
|
|
21
|
+
};
|
|
22
|
+
//#endregion
|
|
23
|
+
//#region src/contracts/schemas.ts
|
|
24
|
+
const SessionInfoSchema = type({
|
|
25
|
+
principal: IdentityPrincipalSchema,
|
|
26
|
+
"attributes?": "object",
|
|
27
|
+
"extra?": "object"
|
|
28
|
+
}).pipe((input) => ({
|
|
29
|
+
principal: input.principal,
|
|
30
|
+
attributes: input.attributes,
|
|
31
|
+
extra: input.extra
|
|
32
|
+
}));
|
|
33
|
+
const SessionUserInfoResponseSchema = IdentityPrincipalWireSchema.pipe((principal) => ({ principal }));
|
|
34
|
+
//#endregion
|
|
35
|
+
//#region src/contracts/parsers.ts
|
|
36
|
+
function parseSessionInfoPayload(body) {
|
|
37
|
+
const infoResult = validateWithSchemaSync(SessionInfoSchema, body);
|
|
38
|
+
if (infoResult.success) return infoResult.value;
|
|
39
|
+
const userInfoResult = validateWithSchemaSync(SessionUserInfoResponseSchema, body);
|
|
40
|
+
if (userInfoResult.success) return userInfoResult.value;
|
|
41
|
+
const failure = {
|
|
42
|
+
success: false,
|
|
43
|
+
issues: [...infoResult.issues, ...userInfoResult.issues]
|
|
44
|
+
};
|
|
45
|
+
const issueSummary = formatValidationFailure(failure);
|
|
46
|
+
throw new ClientError({
|
|
47
|
+
kind: ClientErrorKind.Protocol,
|
|
48
|
+
code: SessionContextErrorCode.InvalidSessionPayload,
|
|
49
|
+
message: issueSummary ? `Session /user-info payload is invalid: ${issueSummary}.` : "Session /user-info payload is invalid.",
|
|
50
|
+
source: SessionContextSource.SessionContext,
|
|
51
|
+
cause: failure.issues
|
|
52
|
+
});
|
|
53
|
+
}
|
|
54
|
+
//#endregion
|
|
55
|
+
//#region src/tokens.ts
|
|
56
|
+
const SESSION_CONTEXT_CLIENT = new SecuritydeptInjectionToken("SESSION_CONTEXT_CLIENT");
|
|
57
|
+
const SESSION_CONTEXT_CLIENT_CONFIG = new SecuritydeptInjectionToken("SESSION_CONTEXT_CLIENT_CONFIG");
|
|
58
|
+
//#endregion
|
|
59
|
+
//#region src/client.ts
|
|
60
|
+
function toPrimitive(input, hint) {
|
|
61
|
+
if (typeof input !== "object" || input === null) return input;
|
|
62
|
+
var prim = input[Symbol.toPrimitive];
|
|
63
|
+
if (prim !== void 0) {
|
|
64
|
+
var res = prim.call(input, hint || "default");
|
|
65
|
+
if (typeof res !== "object") return res;
|
|
66
|
+
throw new TypeError("@@toPrimitive must return a primitive value.");
|
|
67
|
+
}
|
|
68
|
+
return (hint === "string" ? String : Number)(input);
|
|
69
|
+
}
|
|
70
|
+
function toPropertyKey(arg) {
|
|
71
|
+
var key = toPrimitive(arg, "string");
|
|
72
|
+
return typeof key === "symbol" ? key : String(key);
|
|
73
|
+
}
|
|
74
|
+
function checkInRHS(value) {
|
|
75
|
+
if (Object(value) !== value) throw TypeError("right-hand side of 'in' should be an object, got " + (value !== null ? typeof value : "null"));
|
|
76
|
+
return value;
|
|
77
|
+
}
|
|
78
|
+
function setFunctionName(fn, name, prefix) {
|
|
79
|
+
if (typeof name === "symbol") {
|
|
80
|
+
name = name.description;
|
|
81
|
+
name = name ? "[" + name + "]" : "";
|
|
82
|
+
}
|
|
83
|
+
try {
|
|
84
|
+
Object.defineProperty(fn, "name", {
|
|
85
|
+
configurable: true,
|
|
86
|
+
value: prefix ? prefix + " " + name : name
|
|
87
|
+
});
|
|
88
|
+
} catch (_) {}
|
|
89
|
+
return fn;
|
|
90
|
+
}
|
|
91
|
+
function _apply_decs_2311(targetClass, classDecs, memberDecs, classDecsHaveThis, instanceBrand, parentClass) {
|
|
92
|
+
var symbolMetadata = Symbol.metadata || Symbol.for("Symbol.metadata");
|
|
93
|
+
var defineProperty = Object.defineProperty;
|
|
94
|
+
var create = Object.create;
|
|
95
|
+
var metadata;
|
|
96
|
+
var existingNonFields = [create(null), create(null)];
|
|
97
|
+
var hasClassDecs = classDecs.length;
|
|
98
|
+
var _;
|
|
99
|
+
function createRunInitializers(initializers, useStaticThis, hasValue) {
|
|
100
|
+
return function(thisArg, value) {
|
|
101
|
+
if (useStaticThis) {
|
|
102
|
+
value = thisArg;
|
|
103
|
+
thisArg = targetClass;
|
|
104
|
+
}
|
|
105
|
+
for (var i = 0; i < initializers.length; i++) value = initializers[i].apply(thisArg, hasValue ? [value] : []);
|
|
106
|
+
return hasValue ? value : thisArg;
|
|
107
|
+
};
|
|
108
|
+
}
|
|
109
|
+
function assertCallable(fn, hint1, hint2, throwUndefined) {
|
|
110
|
+
if (typeof fn !== "function") {
|
|
111
|
+
if (throwUndefined || fn !== void 0) throw new TypeError(hint1 + " must " + (hint2 || "be") + " a function" + (throwUndefined ? "" : " or undefined"));
|
|
112
|
+
}
|
|
113
|
+
return fn;
|
|
114
|
+
}
|
|
115
|
+
function applyDec(Class, decInfo, decoratorsHaveThis, name, kind, initializers, ret, isStatic, isPrivate, isField, hasPrivateBrand) {
|
|
116
|
+
function assertInstanceIfPrivate(target) {
|
|
117
|
+
if (!hasPrivateBrand(target)) throw new TypeError("Attempted to access private element on non-instance");
|
|
118
|
+
}
|
|
119
|
+
var decs = [].concat(decInfo[0]);
|
|
120
|
+
var decVal = decInfo[3];
|
|
121
|
+
var isClass = !ret;
|
|
122
|
+
var isAccessor = kind === 1;
|
|
123
|
+
var isGetter = kind === 3;
|
|
124
|
+
var isSetter = kind === 4;
|
|
125
|
+
var isMethod = kind === 2;
|
|
126
|
+
function bindPropCall(name, useStaticThis, before) {
|
|
127
|
+
return function(_this, value) {
|
|
128
|
+
if (useStaticThis) {
|
|
129
|
+
value = _this;
|
|
130
|
+
_this = Class;
|
|
131
|
+
}
|
|
132
|
+
if (before) before(_this);
|
|
133
|
+
return desc[name].call(_this, value);
|
|
134
|
+
};
|
|
135
|
+
}
|
|
136
|
+
var desc1 = {};
|
|
137
|
+
var init = [];
|
|
138
|
+
var key = isGetter ? "get" : isSetter || isAccessor ? "set" : "value";
|
|
139
|
+
if (!isClass) {
|
|
140
|
+
if (isPrivate) {
|
|
141
|
+
if (isField || isAccessor) desc1 = {
|
|
142
|
+
get: setFunctionName(function() {
|
|
143
|
+
return decVal(this);
|
|
144
|
+
}, name, "get"),
|
|
145
|
+
set: function(value) {
|
|
146
|
+
decInfo[4](this, value);
|
|
147
|
+
}
|
|
148
|
+
};
|
|
149
|
+
else desc1[key] = decVal;
|
|
150
|
+
if (!isField) setFunctionName(desc1[key], name, isMethod ? "" : key);
|
|
151
|
+
} else if (!isField) desc1 = Object.getOwnPropertyDescriptor(Class, name);
|
|
152
|
+
if (!isField && !isPrivate) {
|
|
153
|
+
_ = existingNonFields[+isStatic][name];
|
|
154
|
+
if (_ && (_ ^ kind) !== 7) throw new Error("Decorating two elements with the same name (" + desc1[key].name + ") is not supported yet");
|
|
155
|
+
existingNonFields[+isStatic][name] = kind < 3 ? 1 : kind;
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
var newValue = Class;
|
|
159
|
+
for (var i = decs.length - 1; i >= 0; i -= decoratorsHaveThis ? 2 : 1) {
|
|
160
|
+
var dec = assertCallable(decs[i], "A decorator", "be", true);
|
|
161
|
+
var decThis = decoratorsHaveThis ? decs[i - 1] : void 0;
|
|
162
|
+
var decoratorFinishedRef = {};
|
|
163
|
+
var ctx = {
|
|
164
|
+
kind: [
|
|
165
|
+
"field",
|
|
166
|
+
"accessor",
|
|
167
|
+
"method",
|
|
168
|
+
"getter",
|
|
169
|
+
"setter",
|
|
170
|
+
"class"
|
|
171
|
+
][kind],
|
|
172
|
+
name,
|
|
173
|
+
metadata,
|
|
174
|
+
addInitializer: (function(decoratorFinishedRef, initializer) {
|
|
175
|
+
if (decoratorFinishedRef.v) throw new TypeError("attempted to call addInitializer after decoration was finished");
|
|
176
|
+
assertCallable(initializer, "An initializer", "be", true);
|
|
177
|
+
initializers.push(initializer);
|
|
178
|
+
}).bind(null, decoratorFinishedRef)
|
|
179
|
+
};
|
|
180
|
+
if (isClass) {
|
|
181
|
+
_ = dec.call(decThis, newValue, ctx);
|
|
182
|
+
decoratorFinishedRef.v = 1;
|
|
183
|
+
if (assertCallable(_, "class decorators", "return")) newValue = _;
|
|
184
|
+
continue;
|
|
185
|
+
}
|
|
186
|
+
ctx.static = isStatic;
|
|
187
|
+
ctx.private = isPrivate;
|
|
188
|
+
_ = ctx.access = { has: isPrivate ? hasPrivateBrand.bind() : function(target) {
|
|
189
|
+
return name in target;
|
|
190
|
+
} };
|
|
191
|
+
if (!isSetter) _.get = isPrivate ? isMethod ? function(_this) {
|
|
192
|
+
assertInstanceIfPrivate(_this);
|
|
193
|
+
return desc1.value;
|
|
194
|
+
} : bindPropCall("get", 0, assertInstanceIfPrivate) : function(target) {
|
|
195
|
+
return target[name];
|
|
196
|
+
};
|
|
197
|
+
if (!isMethod && !isGetter) _.set = isPrivate ? bindPropCall("set", 0, assertInstanceIfPrivate) : function(target, value) {
|
|
198
|
+
target[name] = value;
|
|
199
|
+
};
|
|
200
|
+
newValue = dec.call(decThis, isAccessor ? {
|
|
201
|
+
get: desc1.get,
|
|
202
|
+
set: desc1.set
|
|
203
|
+
} : desc1[key], ctx);
|
|
204
|
+
decoratorFinishedRef.v = 1;
|
|
205
|
+
if (isAccessor) {
|
|
206
|
+
if (typeof newValue === "object" && newValue) {
|
|
207
|
+
if (_ = assertCallable(newValue.get, "accessor.get")) desc1.get = _;
|
|
208
|
+
if (_ = assertCallable(newValue.set, "accessor.set")) desc1.set = _;
|
|
209
|
+
if (_ = assertCallable(newValue.init, "accessor.init")) init.unshift(_);
|
|
210
|
+
} else if (newValue !== void 0) throw new TypeError("accessor decorators must return an object with get, set, or init properties or undefined");
|
|
211
|
+
} else if (assertCallable(newValue, (isField ? "field" : "method") + " decorators", "return")) if (isField) init.unshift(newValue);
|
|
212
|
+
else desc1[key] = newValue;
|
|
213
|
+
}
|
|
214
|
+
if (kind < 2) ret.push(createRunInitializers(init, isStatic, 1), createRunInitializers(initializers, isStatic, 0));
|
|
215
|
+
if (!isField && !isClass) if (isPrivate) if (isAccessor) ret.splice(-1, 0, bindPropCall("get", isStatic), bindPropCall("set", isStatic));
|
|
216
|
+
else ret.push(isMethod ? desc1[key] : assertCallable.call.bind(desc1[key]));
|
|
217
|
+
else defineProperty(Class, name, desc1);
|
|
218
|
+
return newValue;
|
|
219
|
+
}
|
|
220
|
+
function applyMemberDecs() {
|
|
221
|
+
var ret = [];
|
|
222
|
+
var protoInitializers;
|
|
223
|
+
var staticInitializers;
|
|
224
|
+
var pushInitializers = function(initializers) {
|
|
225
|
+
if (initializers) ret.push(createRunInitializers(initializers));
|
|
226
|
+
};
|
|
227
|
+
var applyMemberDecsOfKind = function(isStatic, isField) {
|
|
228
|
+
for (var i = 0; i < memberDecs.length; i++) {
|
|
229
|
+
var decInfo = memberDecs[i];
|
|
230
|
+
var kind = decInfo[1];
|
|
231
|
+
var kindOnly = kind & 7;
|
|
232
|
+
if ((kind & 8) == isStatic && !kindOnly == isField) {
|
|
233
|
+
var name = decInfo[2];
|
|
234
|
+
var isPrivate = !!decInfo[3];
|
|
235
|
+
var decoratorsHaveThis = kind & 16;
|
|
236
|
+
applyDec(isStatic ? targetClass : targetClass.prototype, decInfo, decoratorsHaveThis, isPrivate ? "#" + name : toPropertyKey(name), kindOnly, kindOnly < 2 ? [] : isStatic ? staticInitializers = staticInitializers || [] : protoInitializers = protoInitializers || [], ret, !!isStatic, isPrivate, isField, isStatic && isPrivate ? function(_) {
|
|
237
|
+
return checkInRHS(_) === targetClass;
|
|
238
|
+
} : instanceBrand);
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
};
|
|
242
|
+
applyMemberDecsOfKind(8, 0);
|
|
243
|
+
applyMemberDecsOfKind(0, 0);
|
|
244
|
+
applyMemberDecsOfKind(8, 1);
|
|
245
|
+
applyMemberDecsOfKind(0, 1);
|
|
246
|
+
pushInitializers(protoInitializers);
|
|
247
|
+
pushInitializers(staticInitializers);
|
|
248
|
+
return ret;
|
|
249
|
+
}
|
|
250
|
+
function defineMetadata(Class) {
|
|
251
|
+
return defineProperty(Class, symbolMetadata, {
|
|
252
|
+
configurable: true,
|
|
253
|
+
enumerable: true,
|
|
254
|
+
value: metadata
|
|
255
|
+
});
|
|
256
|
+
}
|
|
257
|
+
if (parentClass !== void 0) metadata = parentClass[symbolMetadata];
|
|
258
|
+
metadata = create(metadata == null ? null : metadata);
|
|
259
|
+
_ = applyMemberDecs();
|
|
260
|
+
if (!hasClassDecs) defineMetadata(targetClass);
|
|
261
|
+
return {
|
|
262
|
+
e: _,
|
|
263
|
+
get c() {
|
|
264
|
+
var initializers = [];
|
|
265
|
+
return hasClassDecs && [defineMetadata(targetClass = applyDec(targetClass, [classDecs], classDecsHaveThis, targetClass.name, 5, initializers)), createRunInitializers(initializers, 1)];
|
|
266
|
+
}
|
|
267
|
+
};
|
|
268
|
+
}
|
|
269
|
+
let _dec, _dec1, _dec2, _dec3, _dec4, _dec5, _dec6, _initProto;
|
|
270
|
+
const POST_AUTH_REDIRECT_PARAM = "post_auth_redirect_uri";
|
|
271
|
+
const instrumentSessionMethod = defineInstrumentMethodDecorator(({ factoryArgs: [operation] }) => function() {
|
|
272
|
+
return {
|
|
273
|
+
environment: this.environment,
|
|
274
|
+
span: this.span,
|
|
275
|
+
name: `${this.config.tracing.prefix}.${operation}`,
|
|
276
|
+
target: this.config.tracing.target,
|
|
277
|
+
fields: { operation },
|
|
278
|
+
normalizeError: (error) => ClientError.fromUnknown(error, {
|
|
279
|
+
code: SessionContextErrorCode.OperationFailed,
|
|
280
|
+
message: "The session operation failed unexpectedly",
|
|
281
|
+
source: SessionContextSource.SessionContext
|
|
282
|
+
})
|
|
283
|
+
};
|
|
284
|
+
});
|
|
285
|
+
_dec = instrumentSessionMethod("start"), _dec1 = withDisposableStack(0, true), _dec2 = instrumentSessionMethod("refresh"), _dec3 = withDisposableStack(0, true), _dec4 = instrumentSessionMethod("logout"), _dec5 = withDisposableStack(0, true), _dec6 = instrumentSessionMethod("login.redirect");
|
|
286
|
+
/**
|
|
287
|
+
* Session Context Client.
|
|
288
|
+
*
|
|
289
|
+
* Owns session state, lifecycle, login/logout navigation, and tracing.
|
|
290
|
+
* Host capabilities are resolved once through FoundationEnvironment at
|
|
291
|
+
* construction time.
|
|
292
|
+
*/ var SessionContextClient = class SessionContextClient {
|
|
293
|
+
static {
|
|
294
|
+
({e: [_initProto]} = _apply_decs_2311(this, [], [
|
|
295
|
+
[
|
|
296
|
+
_dec,
|
|
297
|
+
2,
|
|
298
|
+
"start"
|
|
299
|
+
],
|
|
300
|
+
[
|
|
301
|
+
_dec1,
|
|
302
|
+
2,
|
|
303
|
+
"refresh"
|
|
304
|
+
],
|
|
305
|
+
[
|
|
306
|
+
_dec2,
|
|
307
|
+
2,
|
|
308
|
+
"_refresh"
|
|
309
|
+
],
|
|
310
|
+
[
|
|
311
|
+
_dec3,
|
|
312
|
+
2,
|
|
313
|
+
"logout"
|
|
314
|
+
],
|
|
315
|
+
[
|
|
316
|
+
_dec4,
|
|
317
|
+
2,
|
|
318
|
+
"_logout"
|
|
319
|
+
],
|
|
320
|
+
[
|
|
321
|
+
_dec5,
|
|
322
|
+
2,
|
|
323
|
+
"loginWithRedirect"
|
|
324
|
+
],
|
|
325
|
+
[
|
|
326
|
+
_dec6,
|
|
327
|
+
2,
|
|
328
|
+
"_loginWithRedirect"
|
|
329
|
+
]
|
|
330
|
+
]));
|
|
331
|
+
}
|
|
332
|
+
static defaultOptions = {
|
|
333
|
+
loginPath: "/auth/session/login",
|
|
334
|
+
logoutPath: "/auth/session/logout",
|
|
335
|
+
userInfoPath: "/auth/session/user-info",
|
|
336
|
+
tracing: {
|
|
337
|
+
target: "session-context-client",
|
|
338
|
+
prefix: "session_context"
|
|
339
|
+
}
|
|
340
|
+
};
|
|
341
|
+
_environment;
|
|
342
|
+
_config;
|
|
343
|
+
_span;
|
|
344
|
+
_rootCancellation = (_initProto(this), createCancellationTokenSource());
|
|
345
|
+
_destroyed = RxStateSignal.fromInitialValue(false);
|
|
346
|
+
destroyed$ = from(this._destroyed).pipe(filter((value) => value), take(1));
|
|
347
|
+
_sessionSnapshotSignal = RxStateSignal.fromInitialValue({ status: ResourceStatus.Idle });
|
|
348
|
+
_operationSignals = {
|
|
349
|
+
startPending: createSignal(false),
|
|
350
|
+
refreshPending: createSignal(false),
|
|
351
|
+
logoutPending: createSignal(false),
|
|
352
|
+
loginRedirectPending: createSignal(false)
|
|
353
|
+
};
|
|
354
|
+
_eventSubject = new RxEventReplaySubject(100);
|
|
355
|
+
_refreshCommandSubject = new RxEventSubject();
|
|
356
|
+
_refreshResponseSubject = new RxEventSubject();
|
|
357
|
+
_logoutCommandSubject = new RxEventSubject();
|
|
358
|
+
_logoutResponseSubject = new RxEventSubject();
|
|
359
|
+
_startOnce = createOnceAsyncLockCallable(async (cancellationToken, operationSpan) => {
|
|
360
|
+
cancellationToken.throwIfCancellationRequested();
|
|
361
|
+
this._operationSignals.startPending.set(true);
|
|
362
|
+
try {
|
|
363
|
+
return await this._dispatchRefresh(cancellationToken, operationSpan);
|
|
364
|
+
} finally {
|
|
365
|
+
this._operationSignals.startPending.set(false);
|
|
366
|
+
}
|
|
367
|
+
});
|
|
368
|
+
id;
|
|
369
|
+
sessionSnapshot;
|
|
370
|
+
sessionResource;
|
|
371
|
+
isAuthenticated;
|
|
372
|
+
sessionOperations;
|
|
373
|
+
events;
|
|
374
|
+
get environment() {
|
|
375
|
+
return this._environment;
|
|
376
|
+
}
|
|
377
|
+
get span() {
|
|
378
|
+
return this._span;
|
|
379
|
+
}
|
|
380
|
+
get config() {
|
|
381
|
+
return this._config;
|
|
382
|
+
}
|
|
383
|
+
static fromEnvironmentConfig(options) {
|
|
384
|
+
return new SessionContextClient(options.config, options.environment);
|
|
385
|
+
}
|
|
386
|
+
static fromInjector(injector) {
|
|
387
|
+
const client = SessionContextClient.fromEnvironmentConfig({
|
|
388
|
+
config: injector.get(SESSION_CONTEXT_CLIENT_CONFIG),
|
|
389
|
+
environment: injector.get(ENVIRONMENT_TOKEN)
|
|
390
|
+
});
|
|
391
|
+
injector.get(SecuritydeptDestroyRef, null)?.onDestroy(() => client.dispose());
|
|
392
|
+
return client;
|
|
393
|
+
}
|
|
394
|
+
constructor(config, environment) {
|
|
395
|
+
this._environment = environment;
|
|
396
|
+
const baseUrl = config.baseUrl.replace(/\/+$/, "");
|
|
397
|
+
this._config = {
|
|
398
|
+
id: config.id ?? v7(),
|
|
399
|
+
baseUrl,
|
|
400
|
+
loginPath: config.loginPath ?? SessionContextClient.defaultOptions.loginPath,
|
|
401
|
+
logoutPath: config.logoutPath ?? SessionContextClient.defaultOptions.logoutPath,
|
|
402
|
+
userInfoPath: config.userInfoPath ?? SessionContextClient.defaultOptions.userInfoPath,
|
|
403
|
+
tracing: {
|
|
404
|
+
target: config.tracing?.target ?? SessionContextClient.defaultOptions.tracing.target,
|
|
405
|
+
prefix: config.tracing?.prefix ?? SessionContextClient.defaultOptions.tracing.prefix
|
|
406
|
+
}
|
|
407
|
+
};
|
|
408
|
+
this.id = this._config.id;
|
|
409
|
+
this._span = environment.span.fork({ attributes: {
|
|
410
|
+
clientName: this.constructor.name,
|
|
411
|
+
id: this.id
|
|
412
|
+
} });
|
|
413
|
+
this.sessionSnapshot = readonlySignal(this._sessionSnapshotSignal);
|
|
414
|
+
this.sessionResource = resourceFromSnapshots(() => this._sessionSnapshotSignal.get());
|
|
415
|
+
this.isAuthenticated = mapResource(this.sessionResource, (sessionInfo) => sessionInfo !== null);
|
|
416
|
+
this.sessionOperations = {
|
|
417
|
+
startPending: readonlySignal(this._operationSignals.startPending),
|
|
418
|
+
refreshPending: readonlySignal(this._operationSignals.refreshPending),
|
|
419
|
+
logoutPending: readonlySignal(this._operationSignals.logoutPending),
|
|
420
|
+
loginRedirectPending: readonlySignal(this._operationSignals.loginRedirectPending)
|
|
421
|
+
};
|
|
422
|
+
this.events = this._eventSubject;
|
|
423
|
+
this.destroyed$.subscribe(() => {
|
|
424
|
+
this._rootCancellation.cancel(new ClientError({
|
|
425
|
+
kind: ClientErrorKind.Cancelled,
|
|
426
|
+
code: SessionContextErrorCode.ClientDisposed,
|
|
427
|
+
message: "SessionContextClient has been disposed.",
|
|
428
|
+
source: SessionContextSource.SessionContext
|
|
429
|
+
}));
|
|
430
|
+
this.isAuthenticated.dispose();
|
|
431
|
+
this.sessionResource.dispose();
|
|
432
|
+
});
|
|
433
|
+
from(this._refreshCommandSubject).pipe(takeUntil(this.destroyed$), concatCommand((command) => this._executeRefresh(command.cancellationToken, command.operationSpan))).subscribe(this._refreshResponseSubject);
|
|
434
|
+
from(this._logoutCommandSubject).pipe(takeUntil(this.destroyed$), concatCommand((command) => this._executeLogout(command.cancellationToken, command.operationSpan))).subscribe(this._logoutResponseSubject);
|
|
435
|
+
if (config.autoStart === true) this.start().catch(() => {});
|
|
436
|
+
}
|
|
437
|
+
async start(operationSpan) {
|
|
438
|
+
const cancellationToken = this._rootCancellation.token;
|
|
439
|
+
return await this._startOnce(cancellationToken, operationSpan);
|
|
440
|
+
}
|
|
441
|
+
async refresh(options = {}) {
|
|
442
|
+
const disposableStack = injectDisposableStackFrom(options, true);
|
|
443
|
+
const cancellationToken = createLinkedCancellationToken(this._rootCancellation.token, options.cancellationToken);
|
|
444
|
+
disposableStack?.use(cancellationToken);
|
|
445
|
+
return await this._refresh(cancellationToken);
|
|
446
|
+
}
|
|
447
|
+
async _refresh(cancellationToken, operationSpan) {
|
|
448
|
+
cancellationToken.throwIfCancellationRequested();
|
|
449
|
+
return await this._dispatchRefresh(cancellationToken, operationSpan);
|
|
450
|
+
}
|
|
451
|
+
async logout(options = {}) {
|
|
452
|
+
const disposableStack = injectDisposableStackFrom(options, true);
|
|
453
|
+
const cancellationToken = createLinkedCancellationToken(this._rootCancellation.token, options.cancellationToken);
|
|
454
|
+
disposableStack?.use(cancellationToken);
|
|
455
|
+
await this._logout(cancellationToken);
|
|
456
|
+
}
|
|
457
|
+
async _logout(cancellationToken, operationSpan) {
|
|
458
|
+
cancellationToken.throwIfCancellationRequested();
|
|
459
|
+
await this._dispatchLogout(cancellationToken, operationSpan);
|
|
460
|
+
}
|
|
461
|
+
async loginWithRedirect(options = {}) {
|
|
462
|
+
const disposableStack = injectDisposableStackFrom(options, true);
|
|
463
|
+
const cancellationToken = createLinkedCancellationToken(this._rootCancellation.token, options.cancellationToken);
|
|
464
|
+
disposableStack?.use(cancellationToken);
|
|
465
|
+
await this._loginWithRedirect(options, cancellationToken);
|
|
466
|
+
}
|
|
467
|
+
async _loginWithRedirect(options, cancellationToken, _operationSpan) {
|
|
468
|
+
cancellationToken.throwIfCancellationRequested();
|
|
469
|
+
const router = this._environment.router;
|
|
470
|
+
if (!router) throw new ClientError({
|
|
471
|
+
kind: ClientErrorKind.Configuration,
|
|
472
|
+
code: SessionContextErrorCode.RouterUnavailable,
|
|
473
|
+
message: "loginWithRedirect() requires environment.router.",
|
|
474
|
+
source: SessionContextSource.SessionContext
|
|
475
|
+
});
|
|
476
|
+
this._operationSignals.loginRedirectPending.set(true);
|
|
477
|
+
try {
|
|
478
|
+
await router.navigate({
|
|
479
|
+
url: UriReferenceString.parse(this._createLoginRedirectUrl(options.postAuthRedirectUri)),
|
|
480
|
+
intent: RouterNavigationIntent.AuthRedirect,
|
|
481
|
+
mode: RouterNavigationMode.External
|
|
482
|
+
});
|
|
483
|
+
cancellationToken.throwIfCancellationRequested();
|
|
484
|
+
} finally {
|
|
485
|
+
this._operationSignals.loginRedirectPending.set(false);
|
|
486
|
+
}
|
|
487
|
+
}
|
|
488
|
+
dispose() {
|
|
489
|
+
this._destroyed.set(true);
|
|
490
|
+
}
|
|
491
|
+
[SYMBOL_DISPOSE]() {
|
|
492
|
+
this.dispose();
|
|
493
|
+
}
|
|
494
|
+
async _dispatchRefresh(cancellationToken, operationSpan) {
|
|
495
|
+
cancellationToken.throwIfCancellationRequested();
|
|
496
|
+
const sessionInfo = await lastValueFrom(dispatchCommandLocallyToStream({
|
|
497
|
+
payload: void 0,
|
|
498
|
+
requestStream: this._refreshCommandSubject,
|
|
499
|
+
responseStream: this._refreshResponseSubject,
|
|
500
|
+
createCommandExtra: () => ({
|
|
501
|
+
cancellationToken,
|
|
502
|
+
operationSpan
|
|
503
|
+
})
|
|
504
|
+
}).pipe(commandResponseData()));
|
|
505
|
+
cancellationToken.throwIfCancellationRequested();
|
|
506
|
+
return sessionInfo;
|
|
507
|
+
}
|
|
508
|
+
async _dispatchLogout(cancellationToken, operationSpan) {
|
|
509
|
+
cancellationToken.throwIfCancellationRequested();
|
|
510
|
+
await lastValueFrom(dispatchCommandLocallyToStream({
|
|
511
|
+
payload: void 0,
|
|
512
|
+
requestStream: this._logoutCommandSubject,
|
|
513
|
+
responseStream: this._logoutResponseSubject,
|
|
514
|
+
createCommandExtra: () => ({
|
|
515
|
+
cancellationToken,
|
|
516
|
+
operationSpan
|
|
517
|
+
})
|
|
518
|
+
}).pipe(commandResponseData()));
|
|
519
|
+
cancellationToken.throwIfCancellationRequested();
|
|
520
|
+
}
|
|
521
|
+
async _executeRefresh(cancellationToken, operationSpan) {
|
|
522
|
+
cancellationToken.throwIfCancellationRequested();
|
|
523
|
+
this._operationSignals.refreshPending.set(true);
|
|
524
|
+
const previous = this._sessionSnapshotSignal.get();
|
|
525
|
+
const previousValue = previous.status === ResourceStatus.Reloading || previous.status === ResourceStatus.Resolved || previous.status === ResourceStatus.Error ? previous.value : null;
|
|
526
|
+
const loadingSnapshot = reduceResourceSnapshot(previous, { kind: ResourceSnapshotUpdateKind.Load });
|
|
527
|
+
this._sessionSnapshotSignal.set(loadingSnapshot);
|
|
528
|
+
this._emitSessionEvent({
|
|
529
|
+
type: SessionContextEventType.SessionRefreshStarted,
|
|
530
|
+
session: previousValue
|
|
531
|
+
});
|
|
532
|
+
try {
|
|
533
|
+
const sessionInfo = await this._fetchSessionInfo(cancellationToken);
|
|
534
|
+
cancellationToken.throwIfCancellationRequested();
|
|
535
|
+
this._sessionSnapshotSignal.set(reduceResourceSnapshot(loadingSnapshot, {
|
|
536
|
+
kind: ResourceSnapshotUpdateKind.Resolve,
|
|
537
|
+
value: sessionInfo
|
|
538
|
+
}));
|
|
539
|
+
operationSpan?.setAttributes({ authenticated: sessionInfo !== null });
|
|
540
|
+
this._emitSessionEvent({
|
|
541
|
+
type: SessionContextEventType.SessionRefreshSucceeded,
|
|
542
|
+
session: sessionInfo
|
|
543
|
+
});
|
|
544
|
+
return sessionInfo;
|
|
545
|
+
} catch (error) {
|
|
546
|
+
this._sessionSnapshotSignal.set(reduceResourceSnapshot(loadingSnapshot, {
|
|
547
|
+
kind: ResourceSnapshotUpdateKind.Fail,
|
|
548
|
+
error
|
|
549
|
+
}));
|
|
550
|
+
this._emitSessionEvent({
|
|
551
|
+
type: SessionContextEventType.SessionRefreshFailed,
|
|
552
|
+
session: previousValue,
|
|
553
|
+
errorSummary: describeError(error)
|
|
554
|
+
});
|
|
555
|
+
throw error;
|
|
556
|
+
} finally {
|
|
557
|
+
this._operationSignals.refreshPending.set(false);
|
|
558
|
+
}
|
|
559
|
+
}
|
|
560
|
+
async _executeLogout(cancellationToken, operationSpan) {
|
|
561
|
+
cancellationToken.throwIfCancellationRequested();
|
|
562
|
+
this._operationSignals.logoutPending.set(true);
|
|
563
|
+
const loadingSnapshot = reduceResourceSnapshot(this._sessionSnapshotSignal.get(), { kind: ResourceSnapshotUpdateKind.Load });
|
|
564
|
+
this._sessionSnapshotSignal.set(loadingSnapshot);
|
|
565
|
+
this._emitSessionEvent({
|
|
566
|
+
type: SessionContextEventType.SessionLogoutStarted,
|
|
567
|
+
session: this._readCurrentSession()
|
|
568
|
+
});
|
|
569
|
+
try {
|
|
570
|
+
const response = await this._environment.transport.execute({
|
|
571
|
+
url: this._createLogoutUrl(),
|
|
572
|
+
method: "POST",
|
|
573
|
+
headers: { "content-type": "application/json" },
|
|
574
|
+
body: JSON.stringify({}),
|
|
575
|
+
cancellationToken
|
|
576
|
+
});
|
|
577
|
+
if (response.status < 200 || response.status >= 300) throw ClientError.fromHttpResponse({
|
|
578
|
+
status: response.status,
|
|
579
|
+
body: response.body
|
|
580
|
+
});
|
|
581
|
+
cancellationToken.throwIfCancellationRequested();
|
|
582
|
+
this._sessionSnapshotSignal.set(reduceResourceSnapshot(loadingSnapshot, {
|
|
583
|
+
kind: ResourceSnapshotUpdateKind.Resolve,
|
|
584
|
+
value: null
|
|
585
|
+
}));
|
|
586
|
+
operationSpan?.setAttributes({ authenticated: false });
|
|
587
|
+
this._emitSessionEvent({
|
|
588
|
+
type: SessionContextEventType.SessionLogoutSucceeded,
|
|
589
|
+
session: null
|
|
590
|
+
});
|
|
591
|
+
} catch (error) {
|
|
592
|
+
this._sessionSnapshotSignal.set(reduceResourceSnapshot(loadingSnapshot, {
|
|
593
|
+
kind: ResourceSnapshotUpdateKind.Fail,
|
|
594
|
+
error
|
|
595
|
+
}));
|
|
596
|
+
this._emitSessionEvent({
|
|
597
|
+
type: SessionContextEventType.SessionLogoutFailed,
|
|
598
|
+
session: this._readCurrentSession(),
|
|
599
|
+
errorSummary: describeError(error)
|
|
600
|
+
});
|
|
601
|
+
throw error;
|
|
602
|
+
} finally {
|
|
603
|
+
this._operationSignals.logoutPending.set(false);
|
|
604
|
+
}
|
|
605
|
+
}
|
|
606
|
+
async _fetchSessionInfo(cancellationToken) {
|
|
607
|
+
cancellationToken.throwIfCancellationRequested();
|
|
608
|
+
const response = await this._environment.transport.execute({
|
|
609
|
+
url: this._config.baseUrl + this._config.userInfoPath,
|
|
610
|
+
method: "GET",
|
|
611
|
+
headers: {},
|
|
612
|
+
cancellationToken
|
|
613
|
+
});
|
|
614
|
+
cancellationToken.throwIfCancellationRequested();
|
|
615
|
+
if (response.status === 401 || response.status === 403) return null;
|
|
616
|
+
if (response.status >= 200 && response.status < 300) return parseSessionInfoPayload(response.body);
|
|
617
|
+
throw ClientError.fromHttpResponse({
|
|
618
|
+
status: response.status,
|
|
619
|
+
body: response.body
|
|
620
|
+
});
|
|
621
|
+
}
|
|
622
|
+
_createLoginRedirectUrl(postAuthRedirectUri) {
|
|
623
|
+
const base = this._config.baseUrl + this._config.loginPath;
|
|
624
|
+
if (postAuthRedirectUri) return `${base}?${new URLSearchParams({ [POST_AUTH_REDIRECT_PARAM]: postAuthRedirectUri }).toString()}`;
|
|
625
|
+
return base;
|
|
626
|
+
}
|
|
627
|
+
_createLogoutUrl() {
|
|
628
|
+
return this._config.baseUrl + this._config.logoutPath;
|
|
629
|
+
}
|
|
630
|
+
_readCurrentSession() {
|
|
631
|
+
const snapshot = this._sessionSnapshotSignal.get();
|
|
632
|
+
return snapshot.status === ResourceStatus.Reloading || snapshot.status === ResourceStatus.Resolved || snapshot.status === ResourceStatus.Error ? snapshot.value : null;
|
|
633
|
+
}
|
|
634
|
+
_emitSessionEvent(input) {
|
|
635
|
+
this._eventSubject.next({
|
|
636
|
+
...input,
|
|
637
|
+
at: this._environment.time.now(),
|
|
638
|
+
client: { id: this.id }
|
|
639
|
+
});
|
|
640
|
+
}
|
|
641
|
+
};
|
|
642
|
+
//#endregion
|
|
643
|
+
//#region src/providers.ts
|
|
644
|
+
function provideSessionContext(options) {
|
|
645
|
+
return [{
|
|
646
|
+
provide: SESSION_CONTEXT_CLIENT_CONFIG,
|
|
647
|
+
useValue: options.config
|
|
648
|
+
}, {
|
|
649
|
+
provide: SESSION_CONTEXT_CLIENT,
|
|
650
|
+
useFactory: (injector) => SessionContextClient.fromInjector(injector),
|
|
651
|
+
deps: [INJECTOR_TOKEN]
|
|
652
|
+
}];
|
|
653
|
+
}
|
|
654
|
+
//#endregion
|
|
655
|
+
export { SESSION_CONTEXT_CLIENT, SESSION_CONTEXT_CLIENT_CONFIG, SessionContextClient, SessionContextErrorCode, SessionContextEventType, SessionContextSource, SessionInfoSchema, SessionUserInfoResponseSchema, parseSessionInfoPayload, provideSessionContext };
|
|
656
|
+
|
|
657
|
+
//# sourceMappingURL=index.mjs.map
|