libshv-js 3.16.1 → 3.17.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/src/vue-shv.ts DELETED
@@ -1,484 +0,0 @@
1
- import {computed, ComputedRef, Ref, ref, watchEffect} from 'vue';
2
- import {WsClient, WsClientOptionsLogin} from './ws-client';
3
- import {useLocalStorage, useSessionStorage} from '@vueuse/core';
4
- import PKCE from 'js-pkce';
5
- import * as z from './zod';
6
- import {RpcValue} from './rpcvalue';
7
-
8
- type GlobalResourceOptions<ResourceType> = {
9
- shvPath: string;
10
- method: string;
11
- validator: z.ZodType<ResourceType>;
12
- signalName: string;
13
- signalHandler: (param: RpcValue, resource: Ref<ResourceType | undefined>, reinit: () => void) => void;
14
- };
15
-
16
- type VueShvOptions = {
17
- wsUri: string;
18
- onRequest: WsClientOptionsLogin['onRequest'];
19
- azureCodeRedirect?: string;
20
- };
21
-
22
- type ShvLocalStorage = {
23
- azureAccessToken?: string;
24
- azureRedirectTo?: string;
25
- };
26
-
27
- type ShvSessionStorage = {
28
- shvLoginUser?: string;
29
- shvLoginPassword?: string;
30
-
31
- azureWorkflow?: z.infer<typeof OAuth2AzureWorkflowZod>;
32
- };
33
-
34
- const OAuth2AzureWorkflowZod = z.map({
35
- type: z.literal('oauth2-azure'),
36
- authorizeUrl: z.string(),
37
- tokenUrl: z.string(),
38
- clientId: z.string(),
39
- scopes: z.string().or(z.array(z.string())),
40
- });
41
-
42
- export enum LoginFailureReason {
43
- NoCredentials,
44
- AzureTimedOut,
45
- AzureUnsupported,
46
- CouldntLogin,
47
- LoggedOut,
48
- }
49
-
50
- type LoginFailure = {
51
- reason: LoginFailureReason;
52
- message?: string;
53
- };
54
-
55
- const makePkce = (oauthOptions: {azureCodeRedirect: string, clientId: string; authorizeUrl: string; tokenUrl: string; scopes: string | string[]}) => {
56
- const pkce = new PKCE({
57
- client_id: oauthOptions.clientId,
58
- redirect_uri: (() => {
59
- const url = new URL(globalThis.location.href);
60
- url.pathname = oauthOptions.azureCodeRedirect;
61
- url.search = '';
62
- return url.toString();
63
- })(),
64
- authorization_endpoint: oauthOptions.authorizeUrl,
65
- token_endpoint: oauthOptions.tokenUrl,
66
- requested_scopes: Array.isArray(oauthOptions.scopes) ? oauthOptions.scopes.join(' ') : oauthOptions.scopes,
67
- });
68
- return pkce;
69
- };
70
-
71
- export {makePkce as azure};
72
-
73
- export function useShv(options: VueShvOptions) {
74
- const shvLocalStorage = useLocalStorage<ShvLocalStorage>('vue-shv', {});
75
- const shvSessionStorage = useSessionStorage<ShvSessionStorage>('vue-shv', {});
76
-
77
- const displayName = ref('Loading...');
78
- const displayShortName = ref('');
79
- const displayFullName = ref('');
80
- const displayEmail = ref('');
81
- const displayPhoto = ref<string>();
82
-
83
- const state = {
84
- ws: undefined as WsClient | undefined,
85
- reconnectService: undefined as ReturnType<typeof globalThis.setTimeout> | undefined,
86
- };
87
-
88
- const waitingForSocket: Array<{
89
- resolve: (value: WsClient) => void;
90
- reject: () => void;
91
- }> = [];
92
-
93
- const resetAzureToken = () => {
94
- shvLocalStorage.value.azureAccessToken = undefined;
95
- };
96
-
97
- const azureAvailable = async () => {
98
- const accessToken = shvLocalStorage.value.azureAccessToken;
99
- if (accessToken === undefined) {
100
- return LoginFailureReason.NoCredentials;
101
- }
102
-
103
- const resp = await fetch('https://graph.microsoft.com/v1.0/me', {
104
- headers: {
105
- Authorization: `Bearer ${accessToken}`,
106
- },
107
- });
108
-
109
- const json = await resp.json() as unknown;
110
-
111
- if (typeof json === 'object' && json !== null) {
112
- if ('displayName' in json && typeof json.displayName === 'string') {
113
- displayName.value = json.displayName;
114
- }
115
-
116
- if ('givenName' in json && typeof json.givenName === 'string'
117
- && 'surname' in json && typeof json.surname === 'string') {
118
- const firstName: string = json.givenName;
119
- const lastname: string = json.surname;
120
- displayShortName.value = firstName.charAt(0) + lastname.charAt(0);
121
- displayFullName.value = firstName + ' ' + lastname;
122
- }
123
-
124
- if ('mail' in json && typeof json.mail === 'string') {
125
- displayEmail.value = json.mail;
126
- }
127
- }
128
-
129
- const photo = await fetch('https://graph.microsoft.com/v1.0/me/photos/48x48/$value', {
130
- headers: {
131
- Authorization: `Bearer ${accessToken}`,
132
- },
133
- });
134
- if (photo.ok) {
135
- displayPhoto.value = URL.createObjectURL(await photo.blob());
136
- }
137
-
138
- if (!resp.ok) {
139
- resetAzureToken();
140
- }
141
-
142
- return resp.ok ? 'azureAvailable' : LoginFailureReason.AzureTimedOut;
143
- };
144
-
145
- const debug = (...args: string[]) => {
146
- logContents.value = logContents.value + args.join(' ') + '\n';
147
- console.debug(...args);
148
- };
149
-
150
- const azureAuth = (redirectTo?: string) => {
151
- if (options.azureCodeRedirect === undefined) {
152
- throw new Error('Azure redirect URL not set');
153
- }
154
-
155
- const {azureCodeRedirect} = options;
156
-
157
- shvLocalStorage.value.azureRedirectTo = redirectTo ?? globalThis.location.pathname;
158
- const noBrokerSupport = () => {
159
- loginFailure.value = {
160
- reason: LoginFailureReason.AzureUnsupported,
161
- message: 'Broker does not support Azure',
162
- };
163
- };
164
-
165
- state.ws = new WsClient({
166
- logDebug: debug,
167
- wsUri: options.wsUri,
168
- onWorkflows(workflows) {
169
- if (!Array.isArray(workflows)) {
170
- noBrokerSupport();
171
- return;
172
- }
173
-
174
- for (const workflow of workflows) {
175
- const parsedWorkflow = OAuth2AzureWorkflowZod.safeParse(workflow);
176
- if (!parsedWorkflow.success) {
177
- continue;
178
- }
179
-
180
- shvSessionStorage.value.azureWorkflow = parsedWorkflow.data;
181
-
182
- globalThis.location.replace(makePkce({...parsedWorkflow.data, azureCodeRedirect}).authorizeUrl());
183
- }
184
- },
185
- onWorkflowsFailed() {
186
- noBrokerSupport();
187
- },
188
- });
189
- };
190
-
191
- const setShvCredentials = (userName: string, password: string) => {
192
- shvLogout();
193
- shvSessionStorage.value.shvLoginUser = userName;
194
- shvSessionStorage.value.shvLoginPassword = password;
195
- };
196
-
197
- const rpcCall = async (shvPath: string, method: string, params?: RpcValue) => {
198
- const shv = await getConnection();
199
- return shv.callRpcMethod(shvPath, method, params);
200
- };
201
-
202
- const makeRpcCall = <ResultType>(shvPath: string, method: string, validator: z.ZodType<ResultType>) => async () => {
203
- const resultOrError = await rpcCall(shvPath, method);
204
- if (resultOrError instanceof Error) {
205
- return resultOrError;
206
- }
207
-
208
- const parsed = validator.safeParse(resultOrError);
209
- if (!parsed.success) {
210
- return new Error(parsed.error.message);
211
- }
212
-
213
- return parsed.data;
214
- };
215
-
216
- const makeRpcCallParam = <ResultType, ParamType extends RpcValue>(shvPath: string, method: string, _paramType: z.ZodType<ParamType>, validator: z.ZodType<ResultType>) => async (param: ParamType) => {
217
- const resultOrError = await rpcCall(shvPath, method, param);
218
- if (resultOrError instanceof Error) {
219
- return resultOrError;
220
- }
221
-
222
- const parsed = validator.safeParse(resultOrError);
223
- if (!parsed.success) {
224
- return new Error(parsed.error.message);
225
- }
226
-
227
- return parsed.data;
228
- };
229
-
230
- const connected = ref<'connected' | 'connecting' | 'disconnected'>('disconnected');
231
- const logContents = ref('');
232
- const shvLogout = () => {
233
- resetAzureToken();
234
- shvSessionStorage.value.shvLoginUser = undefined;
235
- shvSessionStorage.value.shvLoginPassword = undefined;
236
-
237
- for (const waiter of waitingForSocket) {
238
- waiter.reject();
239
- }
240
-
241
- connected.value = 'disconnected';
242
- waitingForSocket.length = 0;
243
- state.ws?.close();
244
- displayName.value = 'Logged out';
245
- displayPhoto.value = undefined;
246
- state.ws = undefined;
247
- };
248
-
249
- const loginFailure = ref<LoginFailure>();
250
-
251
- const getConnection = async () => {
252
- if (connected.value === 'connected') {
253
- return state.ws!;
254
- }
255
-
256
- return new Promise<WsClient>((resolve, reject) => {
257
- waitingForSocket.push({resolve, reject});
258
- if (connected.value === 'connecting') {
259
- // We should try to connect only once at the same time.
260
- return;
261
- }
262
-
263
- connected.value = 'connecting';
264
- const doConnect = (user: string, password: string, loginType: 'PLAIN' | 'TOKEN') => {
265
- console.log('Connecting to', options.wsUri);
266
- const makeLoginOptions = () => {
267
- switch (loginType) {
268
- case 'PLAIN':
269
- return {
270
- type: loginType,
271
- user,
272
- password,
273
- };
274
- case 'TOKEN':
275
- return {
276
- type: loginType,
277
- token: `oauth2-azure:${password}`,
278
- };
279
- }
280
- };
281
-
282
- state.ws = new WsClient({
283
- login: makeLoginOptions(),
284
- wsUri: options.wsUri,
285
- timeout: 120_000,
286
- logDebug: debug,
287
- onConnected() {
288
- for (const waiter of waitingForSocket) {
289
- waiter.resolve(state.ws!);
290
- }
291
-
292
- waitingForSocket.length = 0;
293
- console.log('Connected to', options.wsUri);
294
- connected.value = 'connected';
295
- },
296
- onConnectionFailure(error) {
297
- console.error(`Failed to connect to: ${options.wsUri}`, error);
298
- shvLogout();
299
- loginFailure.value = {
300
- reason: LoginFailureReason.CouldntLogin,
301
- message: error.message,
302
- };
303
- },
304
- onDisconnected() {
305
- connected.value = 'disconnected';
306
- const RECONNECT_INTERVAL = 3000;
307
- if (shvLocalStorage.value.azureAccessToken !== undefined) {
308
- console.log('Disconnected from', options.wsUri, 'reconnecting in', RECONNECT_INTERVAL, 'ms');
309
- state.reconnectService = globalThis.setTimeout(async () => {
310
- await getConnection();
311
- }, RECONNECT_INTERVAL);
312
- }
313
- },
314
- onRequest: options.onRequest,
315
- });
316
- };
317
-
318
- const shvUser = shvSessionStorage.value.shvLoginUser;
319
- const shvPassword = shvSessionStorage.value.shvLoginPassword;
320
- if (shvUser !== undefined && shvPassword !== undefined) {
321
- displayName.value = shvUser;
322
- displayShortName.value = shvUser[0];
323
- displayFullName.value = shvUser;
324
- doConnect(shvUser, shvPassword, 'PLAIN');
325
- return;
326
- }
327
-
328
- azureAvailable().then(isAzureAvailable => {
329
- switch (isAzureAvailable) {
330
- case LoginFailureReason.NoCredentials:
331
- case LoginFailureReason.AzureTimedOut:
332
- shvLogout();
333
- loginFailure.value = {
334
- reason: isAzureAvailable,
335
- };
336
- return;
337
- case 'azureAvailable':
338
- break;
339
- }
340
-
341
- const accessToken = shvLocalStorage.value.azureAccessToken;
342
-
343
- if (accessToken !== undefined) {
344
- doConnect('', accessToken, 'TOKEN');
345
- }
346
- }).catch((error: unknown) => {
347
- console.error('Failed to fetch verify azure info, redirecting to the login page in 3 seconds', error);
348
- setTimeout(() => {
349
- loginFailure.value = {
350
- reason: LoginFailureReason.CouldntLogin,
351
- message: 'Failed to fetch verify azure info',
352
- };
353
- }, 3000);
354
- });
355
- });
356
- };
357
-
358
- function makeGlobalResource<ResourceType>(options: GlobalResourceOptions<ResourceType>): () => Ref<ResourceType | undefined>;
359
- function makeGlobalResource<ResourceType>(options: GlobalResourceOptions<ResourceType> & {default: ResourceType}): () => ComputedRef<ResourceType>;
360
- function makeGlobalResource<ResourceType>(options: GlobalResourceOptions<ResourceType> & {default?: ResourceType}): () => ComputedRef<ResourceType> | Ref<ResourceType | undefined> {
361
- const resource = ref<ResourceType>();
362
- const resIdentifier = `${options.shvPath}:${options.method}`;
363
-
364
- const resourceCall = makeRpcCall<ResourceType>(options.shvPath, options.method, options.validator);
365
- const refreshValue = async () => {
366
- const newResource = await resourceCall();
367
- if (newResource instanceof Error) {
368
- return;
369
- }
370
-
371
- resource.value = newResource;
372
- };
373
-
374
- const initialize = async () => {
375
- try {
376
- await refreshValue();
377
- const connection = await getConnection();
378
- connection.subscribe(`Global-${resIdentifier}:`, options.shvPath, options.signalName, (_path: string, _method: string, param: RpcValue) => {
379
- options.signalHandler(param, resource, async () => refreshValue().catch((error: unknown) => {
380
- console.error(`Failed to initialize ${resIdentifier}`, error);
381
- }));
382
- });
383
- } catch (error) {
384
- console.error(`Failed to initialize ${resIdentifier}`, error);
385
- }
386
- };
387
-
388
- let initialized = false;
389
-
390
- return () => {
391
- if (!initialized) {
392
- initialized = true;
393
- watchEffect(() => {
394
- if (connected.value !== 'connected') {
395
- return;
396
- }
397
-
398
- initialize().catch((error: unknown) => {
399
- console.error(`Failed to initialize ${resIdentifier}`, error);
400
- });
401
- });
402
- }
403
-
404
- if ('default' in options) {
405
- const defaultValue = options.default;
406
- const withDefault = computed(() => {
407
- if (resource.value === undefined) {
408
- return defaultValue;
409
- }
410
-
411
- return resource.value;
412
- });
413
- return withDefault;
414
- }
415
-
416
- return resource;
417
- };
418
- }
419
-
420
- const azureHandlerError = ref('');
421
-
422
- const handleAzureCode = async () => {
423
- if (shvSessionStorage.value.azureWorkflow === undefined) {
424
- azureHandlerError.value = 'Azure error: no active login procedure';
425
- return;
426
- }
427
-
428
- if (options.azureCodeRedirect === undefined) {
429
- throw new Error('Azure redirect URL not set');
430
- }
431
-
432
- const {azureCodeRedirect} = options;
433
-
434
- return makePkce({...shvSessionStorage.value.azureWorkflow, azureCodeRedirect}).exchangeForAccessToken(globalThis.location.href).then(resp => {
435
- shvSessionStorage.value.azureWorkflow = undefined;
436
- const token = resp.access_token;
437
- if (token === undefined) {
438
- azureHandlerError.value = 'Couldn\'t authenticate to Azure: unable to exchange access token';
439
- return;
440
- }
441
-
442
- // Store the token and remove the code from the query params.
443
- shvLogout();
444
- shvLocalStorage.value.azureAccessToken = token;
445
- const redirectTo = shvLocalStorage.value.azureRedirectTo;
446
- if (redirectTo === undefined) {
447
- azureHandlerError.value = 'Couldn\'t authenticate to Azure: no redirect URL';
448
- return;
449
- }
450
-
451
- shvLocalStorage.value.azureRedirectTo = undefined;
452
- return redirectTo;
453
- }).catch((error: unknown) => {
454
- azureHandlerError.value = `Couldn't authenticate to Azure: ${JSON.stringify(error)}`;
455
- });
456
- };
457
-
458
- return {
459
- azureAuth,
460
- azureHandlerError,
461
- connected,
462
- displayEmail,
463
- displayFullName,
464
- displayName,
465
- displayPhoto,
466
- displayShortName,
467
- getConnection,
468
- handleAzureCode,
469
- logContents,
470
- loginFailure,
471
- makeGlobalResource,
472
- makeRpcCall,
473
- makeRpcCallParam,
474
- rpcCall,
475
- setShvCredentials,
476
- shvLocalStorage,
477
- shvLogout,
478
- shvSessionStorage,
479
- };
480
- }
481
-
482
- export const fullReloadHandler = (_param: RpcValue, _resource: unknown, reinit: () => void) => {
483
- reinit();
484
- };