@futo-org/backups-orchestrator-ui 1.13.0 → 1.14.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.
@@ -7,14 +7,35 @@
7
7
  import * as Oazapfts from "@oazapfts/runtime";
8
8
  export declare const defaults: Oazapfts.Defaults<Oazapfts.CustomHeaders>;
9
9
  export declare const servers: {};
10
- export type DeviceFlowEventType = "START" | "SUCCESS" | "FAILURE";
10
+ export type DeviceFlowStartDto = {
11
+ /** Device verification code */
12
+ deviceCode: string;
13
+ /** End-user verification code */
14
+ userCode: string;
15
+ /** End-user verification URI */
16
+ verificationUri: string;
17
+ /** Verification URI including the user code */
18
+ verificationUriComplete?: string;
19
+ /** Seconds until the device code expires */
20
+ expiresIn: number;
21
+ /** Minimum seconds between polls */
22
+ interval?: number;
23
+ };
24
+ export type DeviceFlowIdentityPollRequestDto = {
25
+ /** Device verification code */
26
+ deviceCode: string;
27
+ };
28
+ export type DeviceFlowPollStatus = "PENDING" | "SLOW_DOWN" | "SUCCESS" | "FAILURE";
11
29
  export type DeviceFlowFailureReason = "NOT_CONNECTED" | "DEVICE_FLOW_FAILED" | "WRONG_ACCOUNT" | "UNKNOWN";
12
- export type DeviceFlowEventDto = {
13
- "type": DeviceFlowEventType;
14
- userCode?: string;
15
- verificationUri?: string;
16
- token?: string;
30
+ export type DeviceFlowPollDto = {
31
+ status: DeviceFlowPollStatus;
32
+ /** Device session token */
33
+ accessToken?: string;
34
+ /** Connected backend ID */
17
35
  backendId?: string;
36
+ /** Authenticated user ID */
37
+ userId?: string;
38
+ /** Failure reason */
18
39
  reason?: DeviceFlowFailureReason;
19
40
  };
20
41
  export type CreateSessionRequestDto = {
@@ -379,13 +400,21 @@ export type SupportModeUpdateRequestDto = {
379
400
  includePaths: boolean;
380
401
  };
381
402
  /**
382
- * Connect a FUTO Backups account
403
+ * Start connecting a FUTO Backups account
383
404
  */
384
- export declare function futoBackupsConnectDeviceFlow(opts?: Oazapfts.RequestOpts): Promise<DeviceFlowEventDto>;
405
+ export declare function futoBackupsConnectDeviceAuthorize(opts?: Oazapfts.RequestOpts): Promise<DeviceFlowStartDto>;
385
406
  /**
386
- * Sign in with FUTO Backups account
407
+ * Poll a FUTO Backups account connection
387
408
  */
388
- export declare function futoBackupsSessionDeviceFlow(opts?: Oazapfts.RequestOpts): Promise<DeviceFlowEventDto>;
409
+ export declare function futoBackupsConnectDeviceToken(deviceFlowIdentityPollRequestDto: DeviceFlowIdentityPollRequestDto, opts?: Oazapfts.RequestOpts): Promise<DeviceFlowPollDto>;
410
+ /**
411
+ * Start signing in with FUTO Backups account
412
+ */
413
+ export declare function futoBackupsSessionDeviceAuthorize(opts?: Oazapfts.RequestOpts): Promise<DeviceFlowStartDto>;
414
+ /**
415
+ * Poll a FUTO Backups account sign in
416
+ */
417
+ export declare function futoBackupsSessionDeviceToken(deviceFlowIdentityPollRequestDto: DeviceFlowIdentityPollRequestDto, opts?: Oazapfts.RequestOpts): Promise<DeviceFlowPollDto>;
389
418
  /**
390
419
  * Create session
391
420
  */
@@ -13,21 +13,43 @@ export const defaults = {
13
13
  const oazapfts = Oazapfts.runtime(defaults);
14
14
  export const servers = {};
15
15
  /**
16
- * Connect a FUTO Backups account
16
+ * Start connecting a FUTO Backups account
17
17
  */
18
- export function futoBackupsConnectDeviceFlow(opts) {
19
- return oazapfts.ok(oazapfts.fetchJson("/api/futo-backups/auth/oidc/device", {
20
- ...opts
18
+ export function futoBackupsConnectDeviceAuthorize(opts) {
19
+ return oazapfts.ok(oazapfts.fetchJson("/api/futo-backups/auth/oidc/device/authorize", {
20
+ ...opts,
21
+ method: "POST"
21
22
  }));
22
23
  }
23
24
  /**
24
- * Sign in with FUTO Backups account
25
+ * Poll a FUTO Backups account connection
25
26
  */
26
- export function futoBackupsSessionDeviceFlow(opts) {
27
- return oazapfts.ok(oazapfts.fetchJson("/api/futo-backups/auth/session/device", {
28
- ...opts
27
+ export function futoBackupsConnectDeviceToken(deviceFlowIdentityPollRequestDto, opts) {
28
+ return oazapfts.ok(oazapfts.fetchJson("/api/futo-backups/auth/oidc/device/token", oazapfts.json({
29
+ ...opts,
30
+ method: "POST",
31
+ body: deviceFlowIdentityPollRequestDto
32
+ })));
33
+ }
34
+ /**
35
+ * Start signing in with FUTO Backups account
36
+ */
37
+ export function futoBackupsSessionDeviceAuthorize(opts) {
38
+ return oazapfts.ok(oazapfts.fetchJson("/api/futo-backups/auth/session/device/authorize", {
39
+ ...opts,
40
+ method: "POST"
29
41
  }));
30
42
  }
43
+ /**
44
+ * Poll a FUTO Backups account sign in
45
+ */
46
+ export function futoBackupsSessionDeviceToken(deviceFlowIdentityPollRequestDto, opts) {
47
+ return oazapfts.ok(oazapfts.fetchJson("/api/futo-backups/auth/session/device/token", oazapfts.json({
48
+ ...opts,
49
+ method: "POST",
50
+ body: deviceFlowIdentityPollRequestDto
51
+ })));
52
+ }
31
53
  /**
32
54
  * Create session
33
55
  */
@@ -1,13 +1,16 @@
1
- import type { DeviceFlowEventDto } from '../fetch-client';
1
+ import type { DeviceFlowPollDto } from '../fetch-client';
2
2
  import { type DeviceFlowKind } from './session.service';
3
3
  export declare function createDeviceFlow(kind: DeviceFlowKind, handlers: {
4
4
  createSession: (token: string) => Promise<unknown>;
5
- onComplete: (event: DeviceFlowEventDto) => void;
5
+ onComplete: (result: DeviceFlowPollDto) => void;
6
6
  onFailure?: (message: string) => void;
7
7
  }): {
8
8
  state: {
9
9
  userCode: string | undefined;
10
10
  verificationUri: string | undefined;
11
+ deviceCode: string | undefined;
12
+ interval: number;
13
+ polling: boolean;
11
14
  error: string | undefined;
12
15
  pending: boolean;
13
16
  opened: boolean;
@@ -1,5 +1,9 @@
1
- import { startDeviceFlow, } from './session.service';
1
+ import { queryClient } from '../query-client';
2
+ import { deviceFlowEndpoints, } from './session.service';
3
+ import { createQuery } from '@tanstack/svelte-query';
2
4
  import { gt, msg } from 'svelte-i18n-lingui';
5
+ const DEFAULT_POLL_INTERVAL_SECONDS = 5;
6
+ const SLOW_DOWN_BACKOFF_SECONDS = 5;
3
7
  const failures = {
4
8
  NOT_CONNECTED: msg `This instance is not connected to a FUTO Backups account yet.`,
5
9
  DEVICE_FLOW_FAILED: msg `Login was cancelled or timed out.`,
@@ -7,52 +11,108 @@ const failures = {
7
11
  UNKNOWN: msg `Could not reach FUTO Backups. Check your connection.`,
8
12
  };
9
13
  export function createDeviceFlow(kind, handlers) {
14
+ const { authorize, token } = deviceFlowEndpoints[kind];
10
15
  const state = $state({
11
16
  userCode: undefined,
12
17
  verificationUri: undefined,
18
+ deviceCode: undefined,
19
+ interval: DEFAULT_POLL_INTERVAL_SECONDS,
20
+ polling: false,
13
21
  error: undefined,
14
22
  pending: false,
15
23
  opened: false,
16
24
  });
17
- let close;
25
+ let firstPoll;
26
+ let attempt = 0;
27
+ const poll = createQuery(() => ({
28
+ queryKey: ['device-flow', kind, state.deviceCode],
29
+ queryFn: async () => {
30
+ const result = await token({ deviceCode: state.deviceCode });
31
+ if (result.status === 'SLOW_DOWN') {
32
+ state.interval += SLOW_DOWN_BACKOFF_SECONDS;
33
+ }
34
+ return result;
35
+ },
36
+ enabled: state.polling && !!state.deviceCode,
37
+ refetchInterval: (query) => {
38
+ const status = query.state.data?.status;
39
+ return status === 'SUCCESS' || status === 'FAILURE'
40
+ ? false
41
+ : state.interval * 1000;
42
+ },
43
+ refetchIntervalInBackground: true,
44
+ refetchOnWindowFocus: false,
45
+ retry: false,
46
+ gcTime: 0,
47
+ }), () => queryClient);
18
48
  const stop = () => {
19
- close?.();
20
- close = undefined;
49
+ attempt++;
50
+ clearTimeout(firstPoll);
51
+ state.polling = false;
52
+ state.deviceCode = undefined;
53
+ };
54
+ const fail = (reason) => {
55
+ stop();
56
+ state.pending = false;
57
+ state.userCode = undefined;
58
+ state.error = gt(failures[reason ?? 'UNKNOWN']);
59
+ handlers.onFailure?.(state.error);
21
60
  };
22
- const complete = async (event) => {
23
- if (event.token) {
24
- await handlers.createSession(event.token);
61
+ const complete = async (result) => {
62
+ stop();
63
+ if (result.accessToken) {
64
+ await handlers.createSession(result.accessToken);
25
65
  }
26
66
  state.pending = false;
27
- handlers.onComplete(event);
67
+ handlers.onComplete(result);
28
68
  };
69
+ $effect(() => {
70
+ if (!state.polling) {
71
+ return;
72
+ }
73
+ if (poll.isError) {
74
+ fail('UNKNOWN');
75
+ return;
76
+ }
77
+ const result = poll.data;
78
+ switch (result?.status) {
79
+ case 'SUCCESS': {
80
+ void complete(result);
81
+ break;
82
+ }
83
+ case 'FAILURE': {
84
+ fail(result.reason);
85
+ break;
86
+ }
87
+ }
88
+ });
29
89
  const start = () => {
30
90
  stop();
31
91
  state.userCode = undefined;
32
92
  state.error = undefined;
33
93
  state.pending = true;
34
94
  state.opened = false;
35
- close = startDeviceFlow(kind, (event) => {
36
- switch (event.type) {
37
- case 'START': {
38
- state.userCode = event.userCode;
39
- state.verificationUri = event.verificationUri;
40
- break;
41
- }
42
- case 'SUCCESS': {
43
- stop();
44
- void complete(event);
45
- break;
46
- }
47
- case 'FAILURE': {
48
- stop();
49
- state.pending = false;
50
- state.userCode = undefined;
51
- state.error = gt(failures[event.reason ?? 'UNKNOWN']);
52
- handlers.onFailure?.(state.error);
53
- break;
54
- }
95
+ const current = attempt;
96
+ authorize()
97
+ .then((started) => {
98
+ if (current !== attempt) {
99
+ return;
100
+ }
101
+ state.userCode = started.userCode;
102
+ state.verificationUri =
103
+ started.verificationUriComplete ?? started.verificationUri;
104
+ state.deviceCode = started.deviceCode;
105
+ state.interval = started.interval ?? DEFAULT_POLL_INTERVAL_SECONDS;
106
+ firstPoll = setTimeout(() => {
107
+ state.polling = true;
108
+ }, state.interval * 1000);
109
+ })
110
+ .catch((error) => {
111
+ if (current !== attempt) {
112
+ return;
55
113
  }
114
+ const { status } = error;
115
+ fail(kind === 'session' && status === 400 ? 'NOT_CONNECTED' : 'UNKNOWN');
56
116
  });
57
117
  };
58
118
  const open = () => {
@@ -1,4 +1,13 @@
1
- import { type DeviceFlowEventDto } from '../fetch-client';
1
+ import { futoBackupsConnectDeviceAuthorize, futoBackupsConnectDeviceToken, futoBackupsSessionDeviceAuthorize, futoBackupsSessionDeviceToken } from '../fetch-client';
2
2
  export type DeviceFlowKind = 'oidc' | 'session';
3
- export declare const startDeviceFlow: (kind: DeviceFlowKind, onEvent: (event: DeviceFlowEventDto) => void) => () => void;
3
+ export declare const deviceFlowEndpoints: {
4
+ oidc: {
5
+ authorize: typeof futoBackupsConnectDeviceAuthorize;
6
+ token: typeof futoBackupsConnectDeviceToken;
7
+ };
8
+ session: {
9
+ authorize: typeof futoBackupsSessionDeviceAuthorize;
10
+ token: typeof futoBackupsSessionDeviceToken;
11
+ };
12
+ };
4
13
  export declare const useCreateSession: () => import("@tanstack/svelte-query").CreateMutationResult<never, Error, string, unknown>;
@@ -1,19 +1,17 @@
1
- import { futoBackupsCreateSession, } from '../fetch-client';
2
- import { getProvider } from '../providers';
1
+ import { futoBackupsConnectDeviceAuthorize, futoBackupsConnectDeviceToken, futoBackupsCreateSession, futoBackupsSessionDeviceAuthorize, futoBackupsSessionDeviceToken, } from '../fetch-client';
3
2
  import { queryClient } from '../query-client';
4
3
  import { handleError } from '../utils/handle-error';
5
4
  import { createMutation } from '@tanstack/svelte-query';
6
5
  import { gt } from 'svelte-i18n-lingui';
7
- export const startDeviceFlow = (kind, onEvent) => {
8
- const source = new EventSource(`${getProvider().baseUrl}/api/futo-backups/auth/${kind}/device`, { withCredentials: true });
9
- source.addEventListener('message', (event) => {
10
- onEvent(JSON.parse(event.data));
11
- });
12
- source.addEventListener('error', () => {
13
- onEvent({ type: 'FAILURE', reason: 'UNKNOWN' });
14
- source.close();
15
- });
16
- return () => source.close();
6
+ export const deviceFlowEndpoints = {
7
+ oidc: {
8
+ authorize: futoBackupsConnectDeviceAuthorize,
9
+ token: futoBackupsConnectDeviceToken,
10
+ },
11
+ session: {
12
+ authorize: futoBackupsSessionDeviceAuthorize,
13
+ token: futoBackupsSessionDeviceToken,
14
+ },
17
15
  };
18
16
  export const useCreateSession = () => createMutation(() => ({
19
17
  mutationFn: (token) => futoBackupsCreateSession({ token }),
package/package.json CHANGED
@@ -2,7 +2,7 @@
2
2
  "name": "@futo-org/backups-orchestrator-ui",
3
3
  "repository": "https://github.com/futo-org/backups",
4
4
  "description": "Backups orchestrator (UI library)",
5
- "version": "1.13.0",
5
+ "version": "1.14.0",
6
6
  "license": "Source First License 1.1",
7
7
  "files": [
8
8
  "dist",
@@ -69,7 +69,7 @@
69
69
  "luxon": "^3.7.2",
70
70
  "socket.io-client": "^4.8.3",
71
71
  "svelte-i18n-lingui": "^0.2.2",
72
- "@futo-org/backups-api-client": "^1.13.0"
72
+ "@futo-org/backups-api-client": "^1.14.0"
73
73
  },
74
74
  "scripts": {
75
75
  "dev": "vite dev --port 5174",