@nebulr-group/bridge-svelte 1.0.0-alpha.1 → 1.0.0-alpha.3

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.
@@ -3,9 +3,12 @@
3
3
  signs the person in. Opened on another device it says so, and the link
4
4
  still works on the right one.
5
5
 
6
- With `storage: 'memory'` the sign-up's verifier lives only in the tab that
7
- started it, so this page first hands the link to that tab; when one takes
8
- it, this page says to go on there.
6
+ With `storage: 'memory'` the session lives only in the tab that started the
7
+ sign-up, so this page first hands the link to that tab; when one takes it,
8
+ this page says to go on there. When none does, this page finishes itself.
9
+
10
+ Every wait has a bound: finishing fails with an error after a while, and
11
+ once signed in the page goes on, or offers a link when it cannot.
9
12
  -->
10
13
  <script lang="ts">
11
14
  import type { Snippet } from 'svelte';
@@ -22,6 +25,7 @@
22
25
  import Spinner from '../shared/Spinner.svelte';
23
26
  import WorkspaceChooser from './WorkspaceChooser.svelte';
24
27
  import { takeEmailLink } from './email-link.js';
28
+ import { bounded, leave } from './finish-link.js';
25
29
 
26
30
  interface Props extends HTMLAttributes<HTMLDivElement> {
27
31
  /** The link's token. @default read from the page's address */
@@ -42,13 +46,20 @@
42
46
  type State =
43
47
  | { step: 'working' }
44
48
  | { step: 'continued' }
49
+ | { step: 'signed-in'; to: string }
45
50
  | { step: 'workspace'; workspaces: readonly WorkspaceChoice[]; choose: (id: string) => Promise<SignInStep> }
46
51
  | { step: 'failed'; message: string; kind: string | null };
47
52
  let view = $state<State>({ step: 'working' });
48
53
 
49
- function finish() {
50
- if (onSignIn) onSignIn();
51
- else void goto(config?.afterSignIn ?? '/', { invalidateAll: true });
54
+ async function finish() {
55
+ if (onSignIn) {
56
+ onSignIn();
57
+ return;
58
+ }
59
+ // Signing in runs the route guard again, and that newer navigation can cancel this one: go again, then offer a link.
60
+ const to = config?.afterSignIn ?? '/';
61
+ const here = location.pathname;
62
+ if (!(await leave(() => goto(to, { invalidateAll: true }), () => location.pathname !== here))) view = { step: 'signed-in', to };
52
63
  }
53
64
 
54
65
  function fail(error: unknown) {
@@ -57,7 +68,7 @@
57
68
  }
58
69
 
59
70
  async function follow(step: SignInStep) {
60
- if (step.done) finish();
71
+ if (step.done) await finish();
61
72
  else view = { step: 'workspace', workspaces: step.workspaces, choose: step.choose };
62
73
  }
63
74
 
@@ -69,17 +80,22 @@
69
80
  view = { step: 'failed', message: t('verify.missingLink'), kind: null };
70
81
  return;
71
82
  }
72
- if (relayed === null && config?.storage === 'memory') {
73
- // The verifier is in the tab that started the sign-up: offer it the link first.
74
- void offerSignUpLink(config.issuer, found).then((taken) => {
75
- if (taken) view = { step: 'continued' };
76
- else getBridge().signUp.finish(found).then(follow, fail);
77
- });
78
- return;
79
- }
80
- getBridge().signUp.finish(found).then(follow, fail);
83
+ void start(found, relayed !== null);
81
84
  });
82
85
 
86
+ async function start(found: string, relayed: boolean) {
87
+ try {
88
+ // The session belongs in the tab that started the sign-up (memory only): offer it the link first.
89
+ if (!relayed && config?.storage === 'memory' && (await offerSignUpLink(config.issuer, found))) {
90
+ view = { step: 'continued' };
91
+ return;
92
+ }
93
+ await follow(await bounded(getBridge().signUp.finish(found)));
94
+ } catch (error) {
95
+ fail(error);
96
+ }
97
+ }
98
+
83
99
  async function choose(id: string) {
84
100
  if (view.step !== 'workspace') return;
85
101
  try {
@@ -101,6 +117,12 @@
101
117
  <AuthFormWrapper heading={t('signup.heading')} {headingSnippet} class={className} {style} data-bridge-verify-email="continued" {...rest}>
102
118
  <Alert variant="info">{t('verify.continuedElsewhere')}</Alert>
103
119
  </AuthFormWrapper>
120
+ {:else if view.step === 'signed-in'}
121
+ <AuthFormWrapper heading={t('signup.heading')} {headingSnippet} class={className} {style} data-bridge-verify-email="signed-in" {...rest}>
122
+ <div class="bridge-form-footer">
123
+ <a href={view.to} class="bridge-link">{t('invite.continue')}</a>
124
+ </div>
125
+ </AuthFormWrapper>
104
126
  {:else if view.step === 'workspace'}
105
127
  <AuthFormWrapper heading={t('workspace.chooseHeading')} {headingSnippet} class={className} {style} data-bridge-verify-email="workspace" {...rest}>
106
128
  <WorkspaceChooser workspaces={view.workspaces} onChoose={choose} {messages} />
@@ -0,0 +1,16 @@
1
+ /** How long finishing a link may take before the page says it failed. */
2
+ export declare const FINISH_WAIT_MS = 30000;
3
+ /**
4
+ * How many times the page tries to go on once signed in. Signing in makes
5
+ * the route guard run again as the session and the flags settle; SvelteKit
6
+ * lets that newer navigation cancel the one going on.
7
+ */
8
+ export declare const LEAVE_TRIES = 3;
9
+ /** `work`, or an `unavailable` error when it takes longer than `ms`. */
10
+ export declare function bounded<T>(work: Promise<T>, ms?: number): Promise<T>;
11
+ /**
12
+ * Navigates with `go` until `left` says the page was left: a navigation a
13
+ * newer one cancelled still resolves, so only the address tells. True once
14
+ * left; false after `tries`, and the page offers a link instead.
15
+ */
16
+ export declare function leave(go: () => Promise<unknown>, left: () => boolean, tries?: number): Promise<boolean>;
@@ -0,0 +1,45 @@
1
+ /**
2
+ * Bounds for the page that finishes a sign-up from its email link, so it
3
+ * never waits without end: finishing has a time limit, and once signed in
4
+ * the page goes on even when another navigation cancels its first try.
5
+ */
6
+ import { BridgeError } from '@nebulr-group/bridge-auth-core';
7
+ /** How long finishing a link may take before the page says it failed. */
8
+ export const FINISH_WAIT_MS = 30_000;
9
+ /**
10
+ * How many times the page tries to go on once signed in. Signing in makes
11
+ * the route guard run again as the session and the flags settle; SvelteKit
12
+ * lets that newer navigation cancel the one going on.
13
+ */
14
+ export const LEAVE_TRIES = 3;
15
+ /** `work`, or an `unavailable` error when it takes longer than `ms`. */
16
+ export function bounded(work, ms = FINISH_WAIT_MS) {
17
+ return new Promise((resolve, reject) => {
18
+ const timer = setTimeout(() => reject(new BridgeError('unavailable', 'Finishing the link took too long.')), ms);
19
+ work.then((value) => {
20
+ clearTimeout(timer);
21
+ resolve(value);
22
+ }, (error) => {
23
+ clearTimeout(timer);
24
+ reject(error);
25
+ });
26
+ });
27
+ }
28
+ /**
29
+ * Navigates with `go` until `left` says the page was left: a navigation a
30
+ * newer one cancelled still resolves, so only the address tells. True once
31
+ * left; false after `tries`, and the page offers a link instead.
32
+ */
33
+ export async function leave(go, left, tries = LEAVE_TRIES) {
34
+ for (let tried = 0; tried < tries; tried += 1) {
35
+ try {
36
+ await go();
37
+ }
38
+ catch {
39
+ // A failed navigation is tried again like a cancelled one.
40
+ }
41
+ if (left())
42
+ return true;
43
+ }
44
+ return false;
45
+ }
@@ -3,7 +3,7 @@
3
3
  * browser, and every store and component reads it from here. Nothing is made
4
4
  * on a server: the server side has its own helpers (`/server`), per request.
5
5
  */
6
- import { createBridge, memoryStorage } from '@nebulr-group/bridge-auth-core';
6
+ import { createBridge, localStorageAdapter, memoryStorage } from '@nebulr-group/bridge-auth-core';
7
7
  import { get, writable } from 'svelte/store';
8
8
  import { setAppCopy } from './i18n.js';
9
9
  const clientStore = writable(null);
@@ -59,8 +59,9 @@ export function startClient(config, extra) {
59
59
  issuer: config.issuer,
60
60
  tokenOrigins: config.tokenOrigins,
61
61
  ...(config.live ? {} : { live: false }),
62
- // Memory only: the refresh token, a sign-up's verifier and the visitor id stay in this page.
63
- ...(config.storage === 'memory' ? { storage: memoryStorage() } : {}),
62
+ // Memory: the refresh token and the visitor id stay in this page. A sign-up's verifier waits in localStorage
63
+ // for its email link, which opens in a new tab, for the link's 15 minutes at most, and is removed once used.
64
+ ...(config.storage === 'memory' ? { storage: memoryStorage(), signUpStorage: localStorageAdapter() } : {}),
64
65
  ...extra,
65
66
  });
66
67
  client.on('signed-out', ({ reason }) => {
@@ -65,12 +65,17 @@ export interface BridgeConfig {
65
65
  *
66
66
  * - `'local'`: in the browser's localStorage, so a reload and a new tab
67
67
  * stay signed in.
68
- * - `'memory'`: in this page's memory only. Nothing of Bridge's is
69
- * written to localStorage or sessionStorage: not the refresh token, not
70
- * a sign-up's verifier, not the visitor id. A reload signs in again. A new
71
- * tab is signed in by another open tab of the app, passed in memory
72
- * only; with no other tab open, it signs in again. A sign-up's email link, which opens in a new tab, is handed
73
- * to the tab that started the sign-up and finishes there.
68
+ * - `'memory'`: in this page's memory only. The refresh token and the
69
+ * visitor id are never written to localStorage or sessionStorage. A
70
+ * reload signs in again. A new tab is signed in by another open tab of
71
+ * the app, passed in memory only; with no other tab open, it signs in
72
+ * again. The one exception is a sign-up waiting for its email link: its
73
+ * PKCE verifier is kept in localStorage, so the link, which opens in a
74
+ * new tab, finishes the sign-up in this browser even after the tab that
75
+ * started it is closed. It is kept for the link's 15 minutes at most and
76
+ * removed once used; on another device the link is refused. When the
77
+ * tab that started the sign-up is still open, the link is handed to it
78
+ * and finishes there.
74
79
  *
75
80
  * @default 'local'
76
81
  */
@@ -3,13 +3,15 @@
3
3
  * apps that keep the session in memory (`storage: 'memory'`).
4
4
  *
5
5
  * A sign-up finishes only on the device that started it, with the PKCE
6
- * verifier that tab kept. In memory mode the verifier lives in that tab
7
- * alone, and the email link opens in a new one. The new tab offers the link
8
- * on a BroadcastChannel of the page's own origin; the tab that started the
9
- * sign-up takes it and finishes there, and the new tab says so. When no tab
10
- * takes it within a moment, the new tab tries itself, and Bridge answers
11
- * that the link belongs to the device that started the sign-up. The link
12
- * stays usable either way.
6
+ * verifier it kept in localStorage. In memory mode the session lives in the
7
+ * tab that started the sign-up, and the email link opens in a new one. The
8
+ * new tab offers the link on a BroadcastChannel of the page's own origin;
9
+ * the tab that started the sign-up takes it and finishes there, and the new
10
+ * tab says so. When no tab takes it within a moment (it was closed, or the
11
+ * browser put it to sleep), the new tab finishes itself with the stored
12
+ * verifier. On another device there is none, and Bridge answers that the
13
+ * link belongs to the device that started the sign-up; the link stays
14
+ * usable there.
13
15
  *
14
16
  * Only the token crosses, only between tabs of the same origin, and never
15
17
  * through storage or an address.
@@ -3,13 +3,15 @@
3
3
  * apps that keep the session in memory (`storage: 'memory'`).
4
4
  *
5
5
  * A sign-up finishes only on the device that started it, with the PKCE
6
- * verifier that tab kept. In memory mode the verifier lives in that tab
7
- * alone, and the email link opens in a new one. The new tab offers the link
8
- * on a BroadcastChannel of the page's own origin; the tab that started the
9
- * sign-up takes it and finishes there, and the new tab says so. When no tab
10
- * takes it within a moment, the new tab tries itself, and Bridge answers
11
- * that the link belongs to the device that started the sign-up. The link
12
- * stays usable either way.
6
+ * verifier it kept in localStorage. In memory mode the session lives in the
7
+ * tab that started the sign-up, and the email link opens in a new one. The
8
+ * new tab offers the link on a BroadcastChannel of the page's own origin;
9
+ * the tab that started the sign-up takes it and finishes there, and the new
10
+ * tab says so. When no tab takes it within a moment (it was closed, or the
11
+ * browser put it to sleep), the new tab finishes itself with the stored
12
+ * verifier. On another device there is none, and Bridge answers that the
13
+ * link belongs to the device that started the sign-up; the link stays
14
+ * usable there.
13
15
  *
14
16
  * Only the token crosses, only between tabs of the same origin, and never
15
17
  * through storage or an address.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nebulr-group/bridge-svelte",
3
- "version": "1.0.0-alpha.1",
3
+ "version": "1.0.0-alpha.3",
4
4
  "description": "The Bridge for SvelteKit: sign-in in your own pages, workspaces, flag-based route guards, plans and checkout, the team panel and live updates, on one setting: the issuer.",
5
5
  "author": "Iman Pouya",
6
6
  "license": "MIT",
@@ -60,7 +60,7 @@
60
60
  "@sveltejs/kit": "^2.0.0"
61
61
  },
62
62
  "dependencies": {
63
- "@nebulr-group/bridge-auth-core": "1.0.0-alpha.2"
63
+ "@nebulr-group/bridge-auth-core": "1.0.0-alpha.3"
64
64
  },
65
65
  "devDependencies": {
66
66
  "@sveltejs/kit": "^2.16.0",