@nebulr-group/bridge-svelte 1.0.0-alpha.0 → 1.0.0-alpha.10

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.
Files changed (42) hide show
  1. package/README.md +3 -1
  2. package/dist/bootstrap.js +8 -0
  3. package/dist/components/BridgeBootstrap.svelte +28 -4
  4. package/dist/components/auth/BridgeAuthRoutes.svelte +15 -2
  5. package/dist/components/auth/HostedCallback.svelte +56 -0
  6. package/dist/components/auth/HostedCallback.svelte.d.ts +9 -0
  7. package/dist/components/auth/HostedSignIn.svelte +51 -0
  8. package/dist/components/auth/HostedSignIn.svelte.d.ts +9 -0
  9. package/dist/components/auth/InviteLanding.svelte +102 -28
  10. package/dist/components/auth/InviteLanding.svelte.d.ts +1 -1
  11. package/dist/components/auth/MagicLinkLanding.svelte +124 -0
  12. package/dist/components/auth/MagicLinkLanding.svelte.d.ts +15 -0
  13. package/dist/components/auth/PasskeyManager.svelte +120 -0
  14. package/dist/components/auth/PasskeyManager.svelte.d.ts +14 -0
  15. package/dist/components/auth/PasskeySetupLanding.svelte +117 -0
  16. package/dist/components/auth/PasskeySetupLanding.svelte.d.ts +15 -0
  17. package/dist/components/auth/RecheckDialog.svelte +227 -0
  18. package/dist/components/auth/RecheckDialog.svelte.d.ts +12 -0
  19. package/dist/components/auth/SetPassword.svelte +1 -1
  20. package/dist/components/auth/SignInForm.svelte +146 -18
  21. package/dist/components/auth/SignInForm.svelte.d.ts +0 -2
  22. package/dist/components/auth/SignUpForm.svelte +52 -16
  23. package/dist/components/auth/SignUpForm.svelte.d.ts +6 -1
  24. package/dist/components/auth/VerifyEmail.svelte +49 -6
  25. package/dist/components/auth/finish-link.d.ts +25 -0
  26. package/dist/components/auth/finish-link.js +56 -0
  27. package/dist/core/client.d.ts +7 -1
  28. package/dist/core/client.js +27 -3
  29. package/dist/core/config.d.ts +57 -1
  30. package/dist/core/config.js +9 -0
  31. package/dist/core/i18n.js +10 -3
  32. package/dist/core/link-relay.d.ts +29 -0
  33. package/dist/core/link-relay.js +66 -0
  34. package/dist/core/messages.d.ts +1 -1
  35. package/dist/core/messages.js +576 -0
  36. package/dist/core/recheck.d.ts +25 -0
  37. package/dist/core/recheck.js +52 -0
  38. package/dist/core/routes.d.ts +1 -1
  39. package/dist/core/routes.js +7 -0
  40. package/dist/index.d.ts +10 -2
  41. package/dist/index.js +9 -1
  42. package/package.json +2 -2
package/README.md CHANGED
@@ -69,13 +69,15 @@ In your app's settings in Bridge, add your app's address as a browser address an
69
69
 
70
70
  | Area | Pieces |
71
71
  |---|---|
72
- | Sign-in | `BridgeAuthRoutes` (sign-in, sign-up, verify-email, forgot-password, set-password, invite, workspaces, handoff), `SignInForm`, `SignUpForm`, `VerifyEmail`, `ForgotPassword`, `SetPassword`, `InviteLanding`, `WorkspaceChooser`, `SignOutButton`, `ProfileName` |
72
+ | Sign-in | `BridgeAuthRoutes` (sign-in, sign-up, verify-email, forgot-password, set-password, invite, workspaces, handoff), `SignInForm`, `SignUpForm`, `VerifyEmail`, `ForgotPassword`, `SetPassword`, `InviteLanding`, `WorkspaceChooser`, `SignOutButton`, `ProfileName`, `RecheckDialog` with `withRecheck` and `confirmItIsYou` ("confirm it is you" instead of a sign-out) |
73
73
  | Gates | route `rules`, `FeatureFlag`, `useFlag`, `flag`, `requireFlag`, the paywall: all on flag results, never a role or the plan |
74
74
  | Billing | `BridgeBillingRoutes`, `PlanPicker`, `BillingPortalButton`, `SubscriptionStatus`, `BillingNotice`, `QuotaBanner`, `CheckoutNotice`, `UpgradeDialog`, `bridgeFetch` |
75
75
  | Team | `TeamPanel`, `MemberList`, `InviteDialog`, `InviteList`, `EditMemberDialog`, `WorkspaceForm`, `ProfileForm` |
76
76
  | State | `session`, `user`, `workspace`, `workspaces`, `me`, `flags`, `billing`, `plans`, `usage`, `liveStatus`, `getBridge()` |
77
77
  | Server | `@nebulr-group/bridge-svelte/server`: `bridgeHandle`, `requireActor`, `meter`, `flagsFor` |
78
78
  | Hand-off | `HandoffSignIn`, `readHandoff`, `handoffSignIn`: a sign-in page for a command-line tool |
79
+ | Hosted mode | `hosted: {}` in the config: `/auth/sign-in` sends people to the page Bridge hosts for the app, and `/auth/callback` (`HostedCallback`) finishes the sign-in when they come back. Register the page's origin as a browser address and `https://<your app>/auth/callback` as a sign-in return |
80
+ | Several sign-in pages | `linkAddress` in the config: which of the app's registered email-links addresses its emails link to |
79
81
 
80
82
  All the guides: [the learning docs](https://github.com/thebridgedev/bridge-svelte/tree/v1/learning).
81
83
 
package/dist/bootstrap.js CHANGED
@@ -76,6 +76,14 @@ export function bridgeBootstrap(options = {}) {
76
76
  const { url } = event;
77
77
  // Matched as the router resolves the route: decoded, without a trailing slash.
78
78
  const path = normalizePath(url.pathname);
79
+ // A sign-in request in the address is taken once, then the same page is loaded without it, so the address the
80
+ // navigation ends on never shows it: while it is unspent, anyone holding it could sign in on it.
81
+ if (config.signInRequests && url.searchParams.has('request')) {
82
+ await client.request.use(url.searchParams.get('request') ?? '').catch(() => undefined);
83
+ const clean = new URL(url);
84
+ clean.searchParams.delete('request');
85
+ redirect(307, `${clean.pathname}${clean.search}${clean.hash}`);
86
+ }
79
87
  // An email link lands on the email-links address with its token in the fragment: on to its page.
80
88
  followLink(config, url);
81
89
  if (config.authBase !== '' && path === config.authBase)
@@ -5,17 +5,22 @@
5
5
 
6
6
  It runs the route guard again when the session or the flags change (a
7
7
  sign-out in another tab, a workspace switch, a flag turned off), and
8
- renders the upgrade dialog a plan limit opens.
8
+ renders the dialogs the page opens: the upgrade dialog a plan limit opens,
9
+ and the "confirm it is you" dialog `withRecheck()` and `confirmItIsYou()`
10
+ open.
9
11
  -->
10
12
  <script lang="ts">
11
13
  import type { Snippet } from 'svelte';
12
14
  import { onDestroy } from 'svelte';
13
- import { invalidate } from '$app/navigation';
15
+ import { afterNavigate, invalidate } from '$app/navigation';
16
+ import { navigating } from '$app/state';
14
17
  import { bridgeClient, bridgeConfig } from '../core/client.js';
15
18
  import { closeUpgrade, upgradeRequest } from '../core/upgrade.js';
19
+ import { cancelRecheck, recheckRequest } from '../core/recheck.js';
16
20
  import { canManageBilling } from '../core/flags.js';
17
21
  import { FLAGS_DEPENDENCY, SESSION_DEPENDENCY } from '../bootstrap.js';
18
22
  import UpgradeDialog from './billing/UpgradeDialog.svelte';
23
+ import RecheckDialog from './auth/RecheckDialog.svelte';
19
24
 
20
25
  let { children }: { children?: Snippet } = $props();
21
26
 
@@ -24,6 +29,19 @@
24
29
  const dialogOn = $derived($bridgeConfig?.upgradeDialog !== false);
25
30
  const upgradeHref = $derived($bridgeConfig?.paywall ?? `${$bridgeConfig?.billingBase ?? '/subscription'}/plan`);
26
31
 
32
+ // An invalidation is a navigation to the current address, and a later navigation replaces one under way: a sign-in's
33
+ // own `goto` would be lost to the flag results that arrive just after it. So the guard waits for a navigation to end.
34
+ const waiting = new Set<string>();
35
+ function guardAgain(dependency: string) {
36
+ if (navigating.to !== null) waiting.add(dependency);
37
+ else void invalidate(dependency);
38
+ }
39
+ afterNavigate(() => {
40
+ const due = [...waiting];
41
+ waiting.clear();
42
+ for (const dependency of due) void invalidate(dependency);
43
+ });
44
+
27
45
  let stops: (() => void)[] = [];
28
46
  let flagTimer: ReturnType<typeof setTimeout> | null = null;
29
47
 
@@ -32,8 +50,10 @@
32
50
  for (const stop of stops) stop();
33
51
  stops = [];
34
52
  if (client === null) return;
35
- const again = () => void invalidate(SESSION_DEPENDENCY);
53
+ const again = () => guardAgain(SESSION_DEPENDENCY);
36
54
  stops.push(client.on('signed-in', again), client.on('signed-out', again), client.on('workspace-changed', again));
55
+ // Nobody is left to confirm it is them: the waiting action fails as cancelled.
56
+ stops.push(client.on('signed-out', cancelRecheck));
37
57
  // Flag results change in bursts (a reload after a notice); guard once they settle.
38
58
  let first = true;
39
59
  stops.push(
@@ -43,7 +63,7 @@
43
63
  return;
44
64
  }
45
65
  if (flagTimer !== null) clearTimeout(flagTimer);
46
- flagTimer = setTimeout(() => void invalidate(FLAGS_DEPENDENCY), 150);
66
+ flagTimer = setTimeout(() => guardAgain(FLAGS_DEPENDENCY), 150);
47
67
  }),
48
68
  );
49
69
  });
@@ -59,3 +79,7 @@
59
79
  {#if dialogOn && $upgradeRequest}
60
80
  <Dialog request={$upgradeRequest} {upgradeHref} canUpgrade={$mayUpgrade} onclose={closeUpgrade} />
61
81
  {/if}
82
+
83
+ {#if $recheckRequest}
84
+ <RecheckDialog onconfirm={$recheckRequest.confirmed} oncancel={$recheckRequest.cancelled} />
85
+ {/if}
@@ -5,7 +5,8 @@
5
5
  <BridgeAuthRoutes />
6
6
 
7
7
  Serves sign-in, sign-up, verify-email, forgot-password, set-password,
8
- invite, workspaces and handoff. An unknown page gets the app's own 404.
8
+ invite, workspaces, handoff, magic-link (a sign-in link's landing), passkey-setup (a passkey setup link's landing)
9
+ and callback (hosted mode's return from Bridge's page). An unknown page gets the app's own 404.
9
10
 
10
11
  Customising, in rungs:
11
12
  1. `--bridge-*` CSS tokens restyle the forms.
@@ -34,6 +35,10 @@
34
35
  import InviteLanding from './InviteLanding.svelte';
35
36
  import WorkspaceChooser from './WorkspaceChooser.svelte';
36
37
  import HandoffSignIn from './HandoffSignIn.svelte';
38
+ import MagicLinkLanding from './MagicLinkLanding.svelte';
39
+ import PasskeySetupLanding from './PasskeySetupLanding.svelte';
40
+ import HostedSignIn from './HostedSignIn.svelte';
41
+ import HostedCallback from './HostedCallback.svelte';
37
42
 
38
43
  interface Props {
39
44
  /** Replaces everything around the form, on every page. */
@@ -59,8 +64,12 @@
59
64
  {@render heading?.(p)}
60
65
  {/snippet}
61
66
  {@const pageHeading = heading ? boundHeading : undefined}
62
- {#if p === 'sign-in'}
67
+ {#if p === 'sign-in' && config?.hosted}
68
+ <HostedSignIn headingSnippet={pageHeading} {messages} />
69
+ {:else if p === 'sign-in'}
63
70
  <SignInForm headingSnippet={pageHeading} {messages} />
71
+ {:else if p === 'callback'}
72
+ <HostedCallback headingSnippet={pageHeading} {messages} />
64
73
  {:else if p === 'sign-up'}
65
74
  <SignUpForm headingSnippet={pageHeading} {messages} />
66
75
  {:else if p === 'verify-email'}
@@ -71,6 +80,10 @@
71
80
  <SetPassword headingSnippet={pageHeading} {messages} />
72
81
  {:else if p === 'invite'}
73
82
  <InviteLanding headingSnippet={pageHeading} {messages} />
83
+ {:else if p === 'magic-link'}
84
+ <MagicLinkLanding headingSnippet={pageHeading} {messages} />
85
+ {:else if p === 'passkey-setup'}
86
+ <PasskeySetupLanding headingSnippet={pageHeading} {messages} />
74
87
  {:else if p === 'handoff'}
75
88
  <HandoffSignIn headingSnippet={pageHeading} {messages} />
76
89
  {:else if p === 'workspaces'}
@@ -0,0 +1,56 @@
1
+ <!--
2
+ Hosted mode (`hosted` in the config), `<auth base>/callback`: where Bridge's
3
+ hosted page sends the person back. It checks the return (its `state` and
4
+ issuer) and trades the code with the verifier this browser kept, then goes
5
+ on to where the person was going.
6
+ -->
7
+ <script lang="ts">
8
+ import type { Snippet } from 'svelte';
9
+ import { onMount } from 'svelte';
10
+ import { goto } from '$app/navigation';
11
+ import { takeReturnTo } from '@nebulr-group/bridge-auth-core';
12
+ import { getBridge, peekConfig } from '../../core/client.js';
13
+ import type { BridgeMessages } from '../../core/config.js';
14
+ import { errorMessage, translator } from '../../core/i18n.js';
15
+ import AuthFormWrapper from '../shared/AuthFormWrapper.svelte';
16
+ import Alert from '../shared/Alert.svelte';
17
+ import Spinner from '../shared/Spinner.svelte';
18
+
19
+ interface Props {
20
+ headingSnippet?: Snippet;
21
+ messages?: BridgeMessages;
22
+ }
23
+
24
+ let { headingSnippet, messages }: Props = $props();
25
+ const t = $derived(translator(messages));
26
+ const config = peekConfig();
27
+ const authBase = config?.authBase ?? '/auth';
28
+ let failure = $state<string | null>(null);
29
+
30
+ onMount(async () => {
31
+ const back = location.href;
32
+ // The code and state leave the address bar and the history at once.
33
+ history.replaceState(history.state, '', location.pathname);
34
+ try {
35
+ await getBridge().hosted.finish(back);
36
+ await goto(takeReturnTo() ?? config?.afterSignIn ?? '/', { invalidateAll: true, replaceState: true });
37
+ } catch (error) {
38
+ failure = errorMessage(error, t, 'link.error.invalid');
39
+ }
40
+ });
41
+ </script>
42
+
43
+ {#if failure === null}
44
+ <AuthFormWrapper heading={null} data-bridge-hosted="finishing">
45
+ <div class="bridge-auth-settling" data-bridge-auth-settling>
46
+ <Spinner size={24} />
47
+ </div>
48
+ </AuthFormWrapper>
49
+ {:else}
50
+ <AuthFormWrapper heading={t('login.heading')} {headingSnippet} data-bridge-hosted="failed">
51
+ <Alert variant="error">{failure}</Alert>
52
+ <div class="bridge-form-footer">
53
+ <a href={`${authBase}/sign-in`} class="bridge-link">{t('action.backToSignIn')}</a>
54
+ </div>
55
+ </AuthFormWrapper>
56
+ {/if}
@@ -0,0 +1,9 @@
1
+ import type { Snippet } from 'svelte';
2
+ import type { BridgeMessages } from '../../core/config.js';
3
+ interface Props {
4
+ headingSnippet?: Snippet;
5
+ messages?: BridgeMessages;
6
+ }
7
+ declare const HostedCallback: import("svelte").Component<Props, {}, "">;
8
+ type HostedCallback = ReturnType<typeof HostedCallback>;
9
+ export default HostedCallback;
@@ -0,0 +1,51 @@
1
+ <!--
2
+ Hosted mode (`hosted` in the config), the sign-in page: starts a sign-in
3
+ request at Bridge and sends the browser to the page Bridge hosts for the
4
+ app. `HostedCallback` finishes it when the person comes back.
5
+ -->
6
+ <script lang="ts">
7
+ import type { Snippet } from 'svelte';
8
+ import { onMount } from 'svelte';
9
+ import { page } from '$app/state';
10
+ import { readReturnTo, stashReturnTo } from '@nebulr-group/bridge-auth-core';
11
+ import { getBridge, peekConfig } from '../../core/client.js';
12
+ import type { BridgeMessages } from '../../core/config.js';
13
+ import { errorMessage, translator } from '../../core/i18n.js';
14
+ import AuthFormWrapper from '../shared/AuthFormWrapper.svelte';
15
+ import Alert from '../shared/Alert.svelte';
16
+ import Spinner from '../shared/Spinner.svelte';
17
+
18
+ interface Props {
19
+ headingSnippet?: Snippet;
20
+ messages?: BridgeMessages;
21
+ }
22
+
23
+ let { headingSnippet, messages }: Props = $props();
24
+ const t = $derived(translator(messages));
25
+ const config = peekConfig();
26
+ let failure = $state<string | null>(null);
27
+
28
+ onMount(async () => {
29
+ try {
30
+ const hosted = config?.hosted ?? {};
31
+ const redirectUri = hosted.redirectUri ?? new URL(`${config?.authBase ?? '/auth'}/callback`, location.origin).toString();
32
+ // Where to go once signed in survives the trip to Bridge's page, in this tab.
33
+ stashReturnTo(readReturnTo(page.url, config?.returnToParam));
34
+ location.assign(await getBridge().hosted.start({ redirectUri, ...(hosted.linkAddress === undefined ? {} : { linkAddress: hosted.linkAddress }) }));
35
+ } catch (error) {
36
+ failure = errorMessage(error, t, 'error.unavailable');
37
+ }
38
+ });
39
+ </script>
40
+
41
+ {#if failure === null}
42
+ <AuthFormWrapper heading={null} data-bridge-hosted="starting">
43
+ <div class="bridge-auth-settling" data-bridge-auth-settling>
44
+ <Spinner size={24} />
45
+ </div>
46
+ </AuthFormWrapper>
47
+ {:else}
48
+ <AuthFormWrapper heading={t('login.heading')} {headingSnippet} data-bridge-hosted="failed">
49
+ <Alert variant="error">{failure}</Alert>
50
+ </AuthFormWrapper>
51
+ {/if}
@@ -0,0 +1,9 @@
1
+ import type { Snippet } from 'svelte';
2
+ import type { BridgeMessages } from '../../core/config.js';
3
+ interface Props {
4
+ headingSnippet?: Snippet;
5
+ messages?: BridgeMessages;
6
+ }
7
+ declare const HostedSignIn: import("svelte").Component<Props, {}, "">;
8
+ type HostedSignIn = ReturnType<typeof HostedSignIn>;
9
+ export default HostedSignIn;
@@ -1,19 +1,27 @@
1
1
  <!--
2
- Where an invite email lands. It shows which workspace the invite is for,
3
- then lets the person accept it: at once when signed in, or by signing in or
4
- signing up with the invite. An issuer that does not offer invites yet gets
5
- a plain "not offered here yet" instead.
2
+ Where an invite email lands (`#bridge=invite&token=…`). It takes the token
3
+ from the address, clears it, and shows which workspace the invite is for:
4
+
5
+ - a person with no account signs up from the invite: no email to verify,
6
+ and they land signed in, in the workspace;
7
+ - a person with an account signs in, and the invite is accepted at once;
8
+ - someone signed in already accepts with one button.
9
+
10
+ An invite that no longer works says why: revoked, used or expired. One
11
+ sent to another address says so, and offers to sign out. An issuer that
12
+ does not offer invites gets a plain "not offered here yet".
6
13
  -->
7
14
  <script lang="ts">
8
15
  import type { Snippet } from 'svelte';
9
16
  import type { HTMLAttributes } from 'svelte/elements';
10
17
  import { onMount } from 'svelte';
18
+ import { get } from 'svelte/store';
11
19
  import { goto } from '$app/navigation';
12
- import { isBridgeError } from '@nebulr-group/bridge-auth-core';
20
+ import { isBridgeError, type InvitePreview } from '@nebulr-group/bridge-auth-core';
13
21
  import { getBridge, peekConfig } from '../../core/client.js';
14
22
  import type { BridgeMessages } from '../../core/config.js';
15
- import { errorMessage, translator } from '../../core/i18n.js';
16
- import { signedIn } from '../../core/stores.js';
23
+ import { errorMessage, translator, type BridgeMessageKey } from '../../core/i18n.js';
24
+ import { signedIn, user } from '../../core/stores.js';
17
25
  import AuthFormWrapper from '../shared/AuthFormWrapper.svelte';
18
26
  import Alert from '../shared/Alert.svelte';
19
27
  import Spinner from '../shared/Spinner.svelte';
@@ -25,7 +33,7 @@
25
33
  /** The invite's token. @default read from the page's address */
26
34
  token?: string;
27
35
  headingSnippet?: Snippet;
28
- /** Called once accepted. Without it, the page goes to `auth.afterSignIn`. */
36
+ /** Called once the person is in the workspace. Without it, the page goes to `auth.afterSignIn`. */
29
37
  onAccepted?: () => void;
30
38
  messages?: BridgeMessages;
31
39
  }
@@ -34,21 +42,29 @@
34
42
 
35
43
  const t = $derived(translator(messages));
36
44
  const config = peekConfig();
45
+ const authBase = config?.authBase ?? '/auth';
37
46
 
47
+ type Closed = Exclude<InvitePreview['state'], 'open'>;
38
48
  type View =
39
49
  | { step: 'loading' }
40
50
  | { step: 'not-offered' }
41
51
  | { step: 'failed'; message: string }
42
- | { step: 'ready'; token: string; workspace: string };
52
+ | { step: 'closed'; state: Closed }
53
+ | { step: 'open'; token: string; workspace: string };
43
54
  let view = $state<View>({ step: 'loading' });
44
- let mode = $state<'sign-in' | 'sign-up'>('sign-in');
55
+ /** `auth`: the sign-up or sign-in form. `accept`: signed in, accepting or about to. */
56
+ let phase = $state<'auth' | 'accept'>('auth');
57
+ let mode = $state<'sign-in' | 'sign-up'>('sign-up');
45
58
  let accepting = $state(false);
46
- let failure = $state<string | null>(null);
59
+ let failure = $state<{ message: string; code: string | null } | null>(null);
60
+ let notice = $state<string | null>(null);
47
61
 
48
- function workspaceName(preview: unknown): string {
49
- const p = (preview ?? {}) as { workspace?: { name?: unknown } };
50
- return typeof p.workspace?.name === 'string' && p.workspace.name !== '' ? p.workspace.name : '';
51
- }
62
+ const CLOSED_COPY: Record<Closed, BridgeMessageKey> = {
63
+ revoked: 'invite.state.revoked',
64
+ used: 'invite.state.used',
65
+ expired: 'invite.state.expired',
66
+ };
67
+ const CLOSED_CODES: Record<string, Closed> = { invite_revoked: 'revoked', invite_used: 'used', invite_expired: 'expired' };
52
68
 
53
69
  onMount(() => {
54
70
  const found = token ?? takeEmailLink('invite');
@@ -58,7 +74,15 @@
58
74
  }
59
75
  getBridge()
60
76
  .invites.preview(found)
61
- .then((preview) => (view = { step: 'ready', token: found, workspace: workspaceName(preview) }))
77
+ .then((preview) => {
78
+ if (preview.state !== 'open') {
79
+ view = { step: 'closed', state: preview.state };
80
+ return;
81
+ }
82
+ view = { step: 'open', token: found, workspace: preview.workspace.name ?? '' };
83
+ mode = preview.account ? 'sign-in' : 'sign-up';
84
+ phase = get(signedIn) ? 'accept' : 'auth';
85
+ })
62
86
  .catch((error) => {
63
87
  view = isBridgeError(error, 'not-offered') ? { step: 'not-offered' } : { step: 'failed', message: errorMessage(error, t, 'link.error.invalid') };
64
88
  });
@@ -69,19 +93,53 @@
69
93
  else void goto(config?.afterSignIn ?? '/', { invalidateAll: true });
70
94
  }
71
95
 
96
+ /** What to say about a refused invite call: the server's code first. */
97
+ function refusal(error: unknown): { message: string; code: string | null } {
98
+ const code = isBridgeError(error) ? error.code : null;
99
+ if (code === 'invite_for_another_address') return { message: t('invite.wrongAddress'), code };
100
+ if (code === 'already_member') return { message: t('invite.alreadyMember'), code };
101
+ if (code === 'account_exists') return { message: t('invite.accountExists'), code };
102
+ return { message: errorMessage(error, t, 'link.error.invalid'), code };
103
+ }
104
+
105
+ function closedBy(error: unknown): Closed | null {
106
+ return isBridgeError(error, 'link-invalid') && error.code !== null ? (CLOSED_CODES[error.code] ?? null) : null;
107
+ }
108
+
72
109
  async function accept() {
73
- if (view.step !== 'ready' || accepting) return;
110
+ if (view.step !== 'open' || accepting) return;
111
+ phase = 'accept';
74
112
  accepting = true;
75
113
  failure = null;
76
114
  try {
77
115
  await getBridge().invites.accept(view.token);
78
116
  done();
79
117
  } catch (error) {
80
- failure = errorMessage(error, t, 'link.error.invalid');
118
+ const closed = closedBy(error);
119
+ if (closed !== null) view = { step: 'closed', state: closed };
120
+ else failure = refusal(error);
81
121
  } finally {
82
122
  accepting = false;
83
123
  }
84
124
  }
125
+
126
+ function signUpFailed(error: unknown) {
127
+ const closed = closedBy(error);
128
+ if (closed !== null) {
129
+ view = { step: 'closed', state: closed };
130
+ } else if (isBridgeError(error) && error.code === 'account_exists') {
131
+ // The address has an account after all: sign in, and the invite is accepted on the way.
132
+ mode = 'sign-in';
133
+ notice = t('invite.accountExists');
134
+ }
135
+ }
136
+
137
+ async function signOut() {
138
+ failure = null;
139
+ await getBridge().signOut().catch(() => undefined);
140
+ phase = 'auth';
141
+ mode = 'sign-in';
142
+ }
85
143
  </script>
86
144
 
87
145
  {#if view.step === 'loading'}
@@ -96,7 +154,14 @@
96
154
  <AuthFormWrapper heading={null} {headingSnippet} class={className} {style} data-bridge-invite="failed" {...rest}>
97
155
  <Alert variant="error">{view.message}</Alert>
98
156
  </AuthFormWrapper>
99
- {:else if $signedIn}
157
+ {:else if view.step === 'closed'}
158
+ <AuthFormWrapper heading={null} {headingSnippet} class={className} {style} data-bridge-invite="closed" data-invite-state={view.state} {...rest}>
159
+ <Alert variant={view.state === 'used' ? 'info' : 'error'}>{t(CLOSED_COPY[view.state])}</Alert>
160
+ <div class="bridge-form-footer">
161
+ <a href={`${authBase}/sign-in`} class="bridge-link">{t('action.backToSignIn')}</a>
162
+ </div>
163
+ </AuthFormWrapper>
164
+ {:else if phase === 'accept'}
100
165
  <AuthFormWrapper
101
166
  heading={t('invite.heading', { workspace: view.workspace })}
102
167
  {headingSnippet}
@@ -104,36 +169,45 @@
104
169
  class={className}
105
170
  {style}
106
171
  data-bridge-invite="accept"
172
+ data-invite-error={failure?.code ?? null}
107
173
  {...rest}
108
174
  >
109
- {#if failure}<Alert variant="error">{failure}</Alert>{/if}
110
- <button type="button" class="bridge-btn bridge-btn-primary" disabled={accepting} onclick={accept}>
111
- {#if accepting}<Spinner size={16} />{:else}{t('invite.accept')}{/if}
112
- </button>
175
+ {#if failure}<Alert variant="error">{failure.message}</Alert>{/if}
176
+ {#if failure?.code === 'invite_for_another_address'}
177
+ <button type="button" class="bridge-btn bridge-btn-primary" onclick={signOut}>{t('action.signOut')}</button>
178
+ {:else if failure?.code === 'already_member'}
179
+ <button type="button" class="bridge-btn bridge-btn-primary" onclick={done}>{t('invite.continue')}</button>
180
+ {:else}
181
+ {#if $user?.email}<p class="bridge-step-desc" data-bridge-invite-as>{t('invite.signedInAs', { email: $user.email })}</p>{/if}
182
+ <button type="button" class="bridge-btn bridge-btn-primary" disabled={accepting} onclick={accept}>
183
+ {#if accepting}<Spinner size={16} />{:else}{t('invite.accept')}{/if}
184
+ </button>
185
+ {/if}
113
186
  </AuthFormWrapper>
114
187
  {:else}
115
188
  <AuthFormWrapper
116
189
  heading={t('invite.heading', { workspace: view.workspace })}
117
190
  {headingSnippet}
118
- description={t('invite.signInToAccept')}
191
+ description={mode === 'sign-up' ? t('invite.signUpToAccept') : t('invite.signInToAccept')}
119
192
  class={className}
120
193
  {style}
121
194
  data-bridge-invite={mode}
122
195
  {...rest}
123
196
  >
197
+ {#if notice}<Alert variant="info">{notice}</Alert>{/if}
124
198
  {#if mode === 'sign-in'}
125
- <SignInForm heading={null} invite={view.token} onSignIn={done} {messages}>
199
+ <SignInForm heading={null} onSignIn={accept} {messages}>
126
200
  {#snippet footer()}
127
201
  <div class="bridge-form-footer">
128
- {t('login.signupPrompt')} <button type="button" class="bridge-link" onclick={() => (mode = 'sign-up')}>{t('login.signupLink')}</button>
202
+ {t('login.signupPrompt')} <button type="button" class="bridge-link" onclick={() => ((mode = 'sign-up'), (notice = null))}>{t('login.signupLink')}</button>
129
203
  </div>
130
204
  {/snippet}
131
205
  </SignInForm>
132
206
  {:else}
133
- <SignUpForm heading={null} invite={view.token} {messages}>
207
+ <SignUpForm heading={null} invite={view.token} onSignIn={done} onError={signUpFailed} {messages}>
134
208
  {#snippet footer()}
135
209
  <div class="bridge-form-footer">
136
- {t('signup.loginPrompt')} <button type="button" class="bridge-link" onclick={() => (mode = 'sign-in')}>{t('signup.loginLink')}</button>
210
+ {t('signup.loginPrompt')} <button type="button" class="bridge-link" onclick={() => ((mode = 'sign-in'), (notice = null))}>{t('signup.loginLink')}</button>
137
211
  </div>
138
212
  {/snippet}
139
213
  </SignUpForm>
@@ -5,7 +5,7 @@ interface Props extends HTMLAttributes<HTMLDivElement> {
5
5
  /** The invite's token. @default read from the page's address */
6
6
  token?: string;
7
7
  headingSnippet?: Snippet;
8
- /** Called once accepted. Without it, the page goes to `auth.afterSignIn`. */
8
+ /** Called once the person is in the workspace. Without it, the page goes to `auth.afterSignIn`. */
9
9
  onAccepted?: () => void;
10
10
  messages?: BridgeMessages;
11
11
  }
@@ -0,0 +1,124 @@
1
+ <!--
2
+ Signs in from a sign-in link (a magic link), on the device that asked for
3
+ it. Opened on another device it says so, and the link still works on the
4
+ right one. The link works once: opened again, it says the link is no
5
+ longer valid.
6
+ A link sent to confirm it is you (`bridge.recheck.email`) signs nobody in:
7
+ it renews the session the page that asked is waiting in, and this page says
8
+ to close the tab and go back.
9
+ With `storage: 'memory'` the verifier waited in localStorage, which every
10
+ tab of the origin shares, so the tab the link opens in signs in itself and
11
+ holds the session in its own memory.
12
+ -->
13
+ <script lang="ts">
14
+ import type { Snippet } from 'svelte';
15
+ import type { HTMLAttributes } from 'svelte/elements';
16
+ import { onMount } from 'svelte';
17
+ import { goto } from '$app/navigation';
18
+ import { isBridgeError, type SignInStep, type WorkspaceChoice } from '@nebulr-group/bridge-auth-core';
19
+ import { getBridge, peekConfig } from '../../core/client.js';
20
+ import type { BridgeMessages } from '../../core/config.js';
21
+ import { errorMessage, translator } from '../../core/i18n.js';
22
+ import AuthFormWrapper from '../shared/AuthFormWrapper.svelte';
23
+ import Alert from '../shared/Alert.svelte';
24
+ import Spinner from '../shared/Spinner.svelte';
25
+ import WorkspaceChooser from './WorkspaceChooser.svelte';
26
+ import { takeEmailLink } from './email-link.js';
27
+ import { bounded, handOff, leave } from './finish-link.js';
28
+
29
+ interface Props extends HTMLAttributes<HTMLDivElement> {
30
+ /** The link's token. @default read from the page's address */
31
+ token?: string;
32
+ headingSnippet?: Snippet;
33
+ /** Called once signed in. Without it, the page goes to `auth.afterSignIn`. */
34
+ onSignIn?: () => void;
35
+ onError?: (error: unknown) => void;
36
+ messages?: BridgeMessages;
37
+ }
38
+
39
+ let { token = undefined, headingSnippet, onSignIn, onError, messages, class: className, style, ...rest }: Props = $props();
40
+
41
+ const t = $derived(translator(messages));
42
+ const config = peekConfig();
43
+ const authBase = config?.authBase ?? '/auth';
44
+
45
+ type State =
46
+ | { step: 'working' }
47
+ | { step: 'signed-in'; to: string }
48
+ | { step: 'rechecked' }
49
+ | { step: 'workspace'; workspaces: readonly WorkspaceChoice[]; choose: (id: string) => Promise<SignInStep> }
50
+ | { step: 'failed'; message: string; kind: string | null };
51
+ let view = $state<State>({ step: 'working' });
52
+
53
+ async function finish() {
54
+ if (onSignIn) {
55
+ onSignIn();
56
+ return;
57
+ }
58
+ // Signing in runs the route guard again, and that newer navigation can cancel this one: go again, then offer a link.
59
+ const to = config?.afterSignIn ?? '/';
60
+ const here = location.pathname;
61
+ if (!(await leave(() => goto(to, { invalidateAll: true }), () => location.pathname !== here))) view = { step: 'signed-in', to };
62
+ }
63
+
64
+ function fail(error: unknown) {
65
+ const kind = isBridgeError(error) ? error.kind : null;
66
+ view = { step: 'failed', message: kind === 'wrong-device' ? t('magicLink.wrongDevice') : errorMessage(error, t, 'link.error.invalid'), kind };
67
+ onError?.(error);
68
+ }
69
+
70
+ async function follow(step: SignInStep) {
71
+ if (step.done && step.rechecked === true) view = { step: 'rechecked' };
72
+ else if (handOff(step)) view = { step: 'working' };
73
+ else if (step.done) await finish();
74
+ else view = { step: 'workspace', workspaces: step.workspaces, choose: step.choose };
75
+ }
76
+
77
+ onMount(() => {
78
+ const found = token ?? takeEmailLink('magic-link');
79
+ if (found === null) {
80
+ view = { step: 'failed', message: t('verify.missingLink'), kind: null };
81
+ return;
82
+ }
83
+ bounded(getBridge().magicLink.finish(found)).then(follow).catch(fail);
84
+ });
85
+
86
+ async function choose(id: string) {
87
+ if (view.step !== 'workspace') return;
88
+ try {
89
+ await follow(await view.choose(id));
90
+ } catch (error) {
91
+ fail(error);
92
+ }
93
+ }
94
+ </script>
95
+
96
+ {#if view.step === 'working'}
97
+ <AuthFormWrapper heading={null} class={className} {style} data-bridge-magic-link="working" {...rest}>
98
+ <div class="bridge-auth-settling" data-bridge-auth-settling>
99
+ <Spinner size={24} />
100
+ <span>{t('magicLink.finishing')}</span>
101
+ </div>
102
+ </AuthFormWrapper>
103
+ {:else if view.step === 'rechecked'}
104
+ <AuthFormWrapper heading={t('recheck.heading')} {headingSnippet} class={className} {style} data-bridge-magic-link="rechecked" {...rest}>
105
+ <Alert variant="success">{t('recheck.confirmed')}</Alert>
106
+ </AuthFormWrapper>
107
+ {:else if view.step === 'signed-in'}
108
+ <AuthFormWrapper heading={t('login.heading')} {headingSnippet} class={className} {style} data-bridge-magic-link="signed-in" {...rest}>
109
+ <div class="bridge-form-footer">
110
+ <a href={view.to} class="bridge-link">{t('invite.continue')}</a>
111
+ </div>
112
+ </AuthFormWrapper>
113
+ {:else if view.step === 'workspace'}
114
+ <AuthFormWrapper heading={t('workspace.chooseHeading')} {headingSnippet} class={className} {style} data-bridge-magic-link="workspace" {...rest}>
115
+ <WorkspaceChooser workspaces={view.workspaces} onChoose={choose} {messages} />
116
+ </AuthFormWrapper>
117
+ {:else}
118
+ <AuthFormWrapper heading={t('login.heading')} {headingSnippet} class={className} {style} data-bridge-magic-link="failed" data-error-kind={view.kind} {...rest}>
119
+ <Alert variant="error">{view.message}</Alert>
120
+ <div class="bridge-form-footer">
121
+ <a href={`${authBase}/sign-in`} class="bridge-link">{t('action.backToSignIn')}</a>
122
+ </div>
123
+ </AuthFormWrapper>
124
+ {/if}