@aiveth/react 0.11.0 → 0.13.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/CHANGELOG.md CHANGED
@@ -1,5 +1,14 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.13.0 — unreleased
4
+
5
+ - `<SignIn />` and `<SignUp />`: a ready-made sign-in box for your own page. One line, and it runs every step of `signInHere` — address, password, email code, Google / Microsoft / GitHub / SSO, second factor, a new password, sign-up details, your organization's terms — in your organization's look and the person's language (the sign-in card's own translations; `locale` to choose). `invitation` opens an invitation link's token. A step only Aiveth's page can do goes there and comes back. "Secured by Aiveth" shows on Free and Pro only. `signInHere.settings()` returns what the box reads.
6
+ - An email code sent during a sign-in now answers `needs_email_code`.
7
+
8
+ ## 0.12.0 — 2026-11-30
9
+
10
+ - `signInHere` (on the client and from `useAiveth()`): sign-in on your own page through Aiveth's sign-in API — `start({ email })`, `signUp({ email })`, `invitation(token)` answer a `flow` and its first `Step`; then `flow.password()`, `sendEmailCode()` / `verifyEmailCode()`, `secondFactor()`, `acceptTerms()`, `sendResetCode()` / `verifyResetCode()` / `setNewPassword()`, `verifySignUpCode()` / `resendSignUpCode()`, `details()`, `continueOnAiveth()`. The code is swapped here at the end (`signed_in`). A refused step throws `StepRefused` with its HTTP status.
11
+
3
12
  ## 0.11.0 — unreleased
4
13
 
5
14
  - `signIn` and `<SignInButton>` / `<AivethButton>` take `invitation`: the token your own sign-in page got from an invitation email (`?invitation=`). The person joins the organization, signs in and comes back to your app. `authorizeHints()` passes it too.
package/README.md CHANGED
@@ -44,6 +44,42 @@ Add `audience="https://api.your-app.com"` (registered under Developers → Your
44
44
  `signIn` and both buttons take `connection` (`'google' | 'microsoft' | 'github' | 'sso'`, when your
45
45
  organization has it on), `loginHint`, `locale` and `screenHint: 'sign-up'`.
46
46
 
47
+ ## Sign in on your own page
48
+
49
+ Turn on **Sign-in on your page** for the app in Aiveth, then run the steps from your own form —
50
+ people never leave your app. The code is swapped here at the end.
51
+
52
+ ```tsx
53
+ const { signInHere } = useAiveth();
54
+ const { flow, step } = await signInHere.start({ email });
55
+ // step.status === 'needs_first_factor', step.ways: ['password', 'email_code', 'google', …]
56
+ let next = await flow.password(password); // or sendEmailCode() + verifyEmailCode(code)
57
+ if (next.status === 'needs_second_factor') next = await flow.secondFactor(code);
58
+ if (next.status === 'needs_aiveth') flow.continueOnAiveth(); // a step only Aiveth's page does
59
+ if (next.status === 'signed_in') navigate(next.returnTo ?? '/');
60
+ ```
61
+
62
+ Also `signInHere.signUp({ email })` (`verifySignUpCode`, `details`), `signInHere.invitation(token)`
63
+ (`details`), and on a sign-in `sendResetCode` / `verifyResetCode` / `setNewPassword` and
64
+ `acceptTerms`. A refused step throws `StepRefused` with its HTTP `status` (401, 422, 429, 404).
65
+
66
+ ## A ready-made sign-in box
67
+
68
+ `<SignIn />` runs every step above in your organization's look (Aiveth → Branding) and the person's
69
+ language — one line on your page:
70
+
71
+ ```tsx
72
+ import { SignIn, SignUp } from '@aiveth/react';
73
+
74
+ <SignIn returnTo="/dashboard" onSignedIn={(to) => navigate(to ?? '/')} />
75
+ <SignUp /> {/* opens on "Create an account" */}
76
+ ```
77
+
78
+ It reads `?invitation=` from the address (or take `invitation`), and `locale` picks the language
79
+ (the browser's otherwise). A step only Aiveth's page can do goes there and comes back. "Secured by
80
+ Aiveth" shows on the Free and Pro plans only. The tokens stay in memory, so a reload signs the
81
+ person out — use `<SignInButton>` or Next.js when sessions must survive a reload.
82
+
47
83
  ## Sign in in your organization's own look
48
84
 
49
85
  `<AivethButton>` draws "Sign in" with what you set in Aiveth → Branding — colours (light and
package/dist/box.d.ts ADDED
@@ -0,0 +1,66 @@
1
+ import { type CSSProperties } from 'react';
2
+ import { type HereFlow, type Step } from './here.js';
3
+ /** What Aiveth tells the box: the organization's name and look, the words, the badge. */
4
+ export interface BoxSettings {
5
+ name: string;
6
+ lang: string;
7
+ dir: 'ltr' | 'rtl';
8
+ words: Record<string, string>;
9
+ look: {
10
+ custom: boolean;
11
+ radius?: number;
12
+ button_style?: 'filled' | 'outlined';
13
+ appearance?: 'system' | 'light' | 'dark';
14
+ font?: {
15
+ family: string;
16
+ url: string | null;
17
+ };
18
+ colours?: Record<'light' | 'dark', {
19
+ page: string;
20
+ button: string;
21
+ button_text: string;
22
+ link: string;
23
+ }>;
24
+ more_colours?: Record<'light' | 'dark', {
25
+ card: string;
26
+ input: string;
27
+ border: string;
28
+ button_hover: string;
29
+ }>;
30
+ logo?: string | null;
31
+ logo_dark?: string | null;
32
+ };
33
+ secured_by: boolean;
34
+ sign_up: boolean;
35
+ }
36
+ /** How a package plugs in: where the settings are, how a flow starts, how a provider opens. */
37
+ export interface BoxSetup {
38
+ settings: (lang?: string) => Promise<BoxSettings>;
39
+ start: (email: string) => Promise<{
40
+ flow: HereFlow;
41
+ step: Step;
42
+ }>;
43
+ signUp: (email: string) => Promise<{
44
+ flow: HereFlow;
45
+ step: Step;
46
+ }>;
47
+ invitation: (token: string) => Promise<{
48
+ flow: HereFlow;
49
+ step: Step;
50
+ }>;
51
+ /** Google, Microsoft, GitHub or single sign-on: a redirect to that way in. */
52
+ withProvider: (connection: string, email: string) => void;
53
+ onSignedIn: (step: Step) => void;
54
+ }
55
+ export interface BoxProps {
56
+ /** `ui_locales`-like, e.g. `'hi'` or `'ta en'`; the browser's language when left out. */
57
+ locale?: string;
58
+ /** An invitation's token (your sign-in page's `?invitation=`); read from the address when left out. */
59
+ invitation?: string;
60
+ className?: string;
61
+ style?: CSSProperties;
62
+ }
63
+ export declare function SignInBox({ setup, mode, locale, invitation, className, style }: BoxProps & {
64
+ setup: BoxSetup;
65
+ mode: 'sign-in' | 'sign-up';
66
+ }): import("react/jsx-runtime").JSX.Element | null;
package/dist/box.js ADDED
@@ -0,0 +1,166 @@
1
+ 'use client';
2
+ import { Fragment as _Fragment, jsxs as _jsxs, jsx as _jsx } from "react/jsx-runtime";
3
+ /* The ready-made sign-in on your own page (`<SignIn />`, `<SignUp />`; Clerk's components): every
4
+ * step of Aiveth's sign-in API (`here.ts`), in your organization's look, in the person's language
5
+ * — the sign-in card's own words, from Aiveth (`/v1/sign-in/{client_id}/box`) — with "Secured by
6
+ * Aiveth" below on Free and Pro. The same file is in `@aiveth/react` and `@aiveth/nextjs`. */
7
+ import { useEffect, useRef, useState } from 'react';
8
+ import { StepRefused } from './here.js';
9
+ const AIVETH_LOOK = {
10
+ light: { page: '#ffffff', button: '#1d4ed8', button_text: '#ffffff', link: '#1d4ed8', card: '#ffffff', input: '#ffffff', border: '#d4d4d8', text: '#18181b', muted: '#52525b' },
11
+ dark: { page: '#09090b', button: '#3b82f6', button_text: '#ffffff', link: '#93c5fd', card: '#18181b', input: '#09090b', border: '#3f3f46', text: '#fafafa', muted: '#a1a1aa' },
12
+ };
13
+ const PROVIDERS = { google: 'Google', microsoft: 'Microsoft', github: 'GitHub' };
14
+ function dark(look) {
15
+ if (look.appearance === 'dark')
16
+ return true;
17
+ if (look.appearance === 'light')
18
+ return false;
19
+ return typeof window !== 'undefined' && window.matchMedia?.('(prefers-color-scheme: dark)').matches === true;
20
+ }
21
+ function palette(look) {
22
+ const mode = dark(look) ? 'dark' : 'light';
23
+ return { ...AIVETH_LOOK[mode], ...(look.colours?.[mode] ?? {}), ...(look.more_colours?.[mode] ?? {}) };
24
+ }
25
+ /** A sentence in the person's language, its `{values}` filled in. */
26
+ function say(words, text, values = {}) {
27
+ return (words[text] ?? text).replace(/\{(\w+)\}/g, (_m, k) => values[k] ?? `{${k}}`);
28
+ }
29
+ /** A sentence with a link (or links) in its middle: the translation decides where it sits. */
30
+ function sayAround(words, text, slot, node, values = {}) {
31
+ const [before, after = ''] = say(words, text, { ...values, [slot]: '\u0000' }).split('\u0000');
32
+ return _jsxs(_Fragment, { children: [before, node, after] });
33
+ }
34
+ function inviteFromAddress() {
35
+ if (typeof window === 'undefined')
36
+ return '';
37
+ return new URLSearchParams(window.location.search).get('invitation') ?? '';
38
+ }
39
+ export function SignInBox({ setup, mode, locale, invitation, className, style }) {
40
+ const [settings, setSettings] = useState(null);
41
+ const [step, setStep] = useState(null);
42
+ const [email, setEmail] = useState('');
43
+ const [asSignUp, setAsSignUp] = useState(mode === 'sign-up');
44
+ const [problem, setProblem] = useState('');
45
+ const [busy, setBusy] = useState(false);
46
+ const flow = useRef(null);
47
+ const started = useRef(false);
48
+ useEffect(() => {
49
+ let live = true;
50
+ setup.settings(locale).then((s) => { if (live)
51
+ setSettings(s); }).catch(() => { if (live)
52
+ setProblem('Sign-in is not available here.'); });
53
+ return () => { live = false; };
54
+ }, [setup, locale]);
55
+ const run = async (work) => {
56
+ setBusy(true);
57
+ setProblem('');
58
+ try {
59
+ const got = await work();
60
+ const next = 'flow' in got ? (flow.current = got.flow, got.step) : got;
61
+ if (next.status === 'needs_aiveth') {
62
+ flow.current?.continueOnAiveth();
63
+ return;
64
+ }
65
+ if (next.status === 'signed_in') {
66
+ setup.onSignedIn(next);
67
+ return;
68
+ }
69
+ if (next.status === 'refused')
70
+ setProblem(next.errorDescription ?? next.error ?? '');
71
+ if (next.status === 'needs_first_factor')
72
+ setAsSignUp(false); // an account already: its sign-in
73
+ if (next.email)
74
+ setEmail(next.email);
75
+ setStep(next);
76
+ }
77
+ catch (e) {
78
+ setProblem(e instanceof StepRefused ? e.message : 'Something went wrong. Try again.');
79
+ }
80
+ finally {
81
+ setBusy(false);
82
+ }
83
+ };
84
+ useEffect(() => {
85
+ const token = invitation ?? inviteFromAddress();
86
+ if (!settings || !token || started.current)
87
+ return;
88
+ started.current = true;
89
+ void run(() => setup.invitation(token));
90
+ // eslint-disable-next-line react-hooks/exhaustive-deps -- once, when the settings arrive
91
+ }, [settings]);
92
+ if (!settings)
93
+ return problem ? _jsx("p", { role: "alert", children: problem }) : null;
94
+ const w = settings.words;
95
+ const c = palette(settings.look);
96
+ const radius = settings.look.radius ?? 10;
97
+ const outlined = settings.look.button_style === 'outlined';
98
+ const font = settings.look.font?.family;
99
+ const s = {
100
+ card: { boxSizing: 'border-box', width: '100%', maxWidth: 400, padding: 28, background: c.card, color: c.text, border: `1px solid ${c.border}`, borderRadius: radius + 4, fontFamily: font ? `'${font}', system-ui, sans-serif` : 'system-ui, sans-serif', ...style },
101
+ title: { margin: '0 0 16px', fontSize: 20, fontWeight: 600, textAlign: 'center' },
102
+ label: { display: 'block', fontSize: 14, fontWeight: 500, margin: '12px 0 6px' },
103
+ input: { boxSizing: 'border-box', width: '100%', minHeight: 44, padding: '0 12px', background: c.input, color: c.text, border: `1px solid ${c.border}`, borderRadius: radius, fontSize: 16, fontFamily: 'inherit' },
104
+ button: { width: '100%', minHeight: 44, marginTop: 16, border: outlined ? `1px solid ${c.button}` : 'none', borderRadius: radius, background: outlined ? 'transparent' : c.button, color: outlined ? c.button : c.button_text, fontSize: 15, fontWeight: 600, cursor: 'pointer', fontFamily: 'inherit' },
105
+ quiet: { width: '100%', minHeight: 44, marginTop: 10, background: 'transparent', color: c.text, border: `1px solid ${c.border}`, borderRadius: radius, fontSize: 15, cursor: 'pointer', fontFamily: 'inherit' },
106
+ link: { background: 'none', border: 'none', padding: 0, color: c.link, cursor: 'pointer', fontSize: 14, fontFamily: 'inherit' },
107
+ note: { fontSize: 14, color: c.muted, margin: '8px 0 0', textAlign: 'center' },
108
+ alert: { fontSize: 14, color: '#dc2626', margin: '12px 0 0' },
109
+ foot: { fontSize: 12, color: c.muted, textAlign: 'center', margin: '18px 0 0' },
110
+ };
111
+ const logo = dark(settings.look) ? settings.look.logo_dark ?? settings.look.logo : settings.look.logo;
112
+ const field = (id, label, props) => (_jsxs(_Fragment, { children: [_jsx("label", { htmlFor: id, style: s.label, children: label }), _jsx("input", { id: id, name: id, required: true, style: s.input, ...props })] }));
113
+ const submit = (work) => (e) => {
114
+ e.preventDefault();
115
+ const form = new FormData(e.currentTarget);
116
+ void run(() => work(form));
117
+ };
118
+ const text = (form, key) => String(form.get(key) ?? '');
119
+ const who = (_jsxs("p", { style: s.note, children: [say(w, 'Signing in as {email}', { email }), " \u00B7", ' ', _jsx("button", { type: "button", style: s.link, onClick: () => { setStep(null); flow.current = null; }, children: say(w, 'Change') })] }));
120
+ let body;
121
+ const status = step?.status;
122
+ if (!step) {
123
+ body = (_jsxs("form", { onSubmit: submit((f) => { const typed = text(f, 'email'); setEmail(typed); return asSignUp ? setup.signUp(typed) : setup.start(typed); }), children: [field('email', say(w, 'Work email'), { type: 'email', autoComplete: 'username', defaultValue: email }), _jsx("button", { type: "submit", style: s.button, disabled: busy, children: say(w, 'Continue') }), settings.sign_up && (asSignUp
124
+ ? _jsx("p", { style: s.note, children: _jsx("button", { type: "button", style: s.link, onClick: () => setAsSignUp(false), children: say(w, 'Back to sign in') }) })
125
+ : _jsx("p", { style: s.note, children: sayAround(w, 'New here? {link}', 'link', _jsx("button", { type: "button", style: s.link, onClick: () => setAsSignUp(true), children: say(w, 'Create an account') })) }))] }));
126
+ }
127
+ else if (status === 'needs_first_factor') {
128
+ const ways = step.ways ?? [];
129
+ body = (_jsxs(_Fragment, { children: [who, ways.includes('password') && (_jsxs("form", { onSubmit: submit((f) => flow.current.password(text(f, 'password'))), children: [field('password', say(w, 'Password'), { type: 'password', autoComplete: 'current-password', autoFocus: true }), _jsx("p", { style: { ...s.note, textAlign: 'end' }, children: _jsx("button", { type: "button", style: s.link, onClick: () => void run(() => flow.current.sendResetCode()), children: say(w, 'Forgot password?') }) }), _jsx("button", { type: "submit", style: s.button, disabled: busy, children: say(w, 'Continue') })] })), ways.includes('email_code') && _jsx("button", { type: "button", style: s.quiet, disabled: busy, onClick: () => void run(() => flow.current.sendEmailCode()), children: say(w, 'Email me a code') }), ways.filter((x) => PROVIDERS[x]).map((x) => (_jsx("button", { type: "button", style: s.quiet, onClick: () => setup.withProvider(x, email), children: say(w, 'Continue with {name}', { name: PROVIDERS[x] ?? x }) }, x))), ways.includes('sso') && _jsx("button", { type: "button", style: s.quiet, onClick: () => setup.withProvider('sso', email), children: say(w, 'Single sign-on (SSO)') })] }));
130
+ }
131
+ else if (status === 'needs_email_code' || status === 'needs_reset_code') {
132
+ const signUp = asSignUp && status === 'needs_email_code';
133
+ body = (_jsxs("form", { onSubmit: submit((f) => {
134
+ const code = text(f, 'code');
135
+ if (status === 'needs_reset_code')
136
+ return flow.current.verifyResetCode(code);
137
+ return signUp ? flow.current.verifySignUpCode(code) : flow.current.verifyEmailCode(code);
138
+ }), children: [_jsx("p", { style: s.note, children: say(w, 'We sent a code to {email}. It ends in 10 minutes.', { email }) }), field('code', say(w, '8-digit code'), { inputMode: 'numeric', autoComplete: 'one-time-code', autoFocus: true }), _jsx("button", { type: "submit", style: s.button, disabled: busy, children: say(w, 'Continue') })] }));
139
+ }
140
+ else if (status === 'needs_second_factor') {
141
+ body = (_jsxs("form", { onSubmit: submit((f) => flow.current.secondFactor(text(f, 'code'))), children: [who, field('code', say(w, 'Code from your app, or a recovery code'), { autoComplete: 'one-time-code', autoFocus: true }), _jsx("button", { type: "submit", style: s.button, disabled: busy, children: say(w, 'Continue') })] }));
142
+ }
143
+ else if (status === 'needs_new_password') {
144
+ body = (_jsxs("form", { onSubmit: submit((f) => flow.current.setNewPassword(text(f, 'password'))), children: [field('password', say(w, 'New password'), { type: 'password', autoComplete: 'new-password', autoFocus: true }), _jsx("button", { type: "submit", style: s.button, disabled: busy, children: say(w, 'Continue') })] }));
145
+ }
146
+ else if (status === 'needs_details') {
147
+ body = (_jsxs("form", { onSubmit: submit((f) => flow.current.details({ firstName: text(f, 'first_name'), lastName: text(f, 'last_name'), password: text(f, 'password') })), children: [email && _jsx("p", { style: s.note, children: email }), field('first_name', say(w, 'First name'), { autoComplete: 'given-name', autoFocus: true }), _jsx("label", { htmlFor: "last_name", style: s.label, children: say(w, 'Last name') }), _jsx("input", { id: "last_name", name: "last_name", style: s.input, autoComplete: "family-name" }), field('password', say(w, 'Password'), { type: 'password', autoComplete: 'new-password' }), _jsx("button", { type: "submit", style: s.button, disabled: busy, children: say(w, 'Continue') })] }));
148
+ }
149
+ else if (status === 'needs_legal_acceptance') {
150
+ const links = [[step.termsUrl, 'Terms of Service'], [step.privacyUrl, 'Privacy Policy']].filter(([u]) => u);
151
+ body = (_jsxs("form", { onSubmit: submit(() => flow.current.acceptTerms()), children: [_jsxs("label", { style: { display: 'flex', gap: 8, alignItems: 'flex-start', fontSize: 14 }, children: [_jsx("input", { type: "checkbox", required: true }), _jsx("span", { children: sayAround(w, "I agree to {company}'s {links}", 'links', links.map(([u, t], i) => _jsxs("span", { children: [i ? ', ' : '', _jsx("a", { href: u, target: "_blank", rel: "noopener noreferrer", style: { color: c.link }, children: say(w, t) })] }, u)), { company: settings.name }) })] }), _jsx("button", { type: "submit", style: s.button, disabled: busy, children: say(w, 'Continue') })] }));
152
+ }
153
+ else if (status === 'waiting') {
154
+ body = _jsx("p", { style: s.note, children: say(w, "Request sent. If an admin approves it, you'll get an invitation by email.") });
155
+ }
156
+ else {
157
+ body = _jsx("button", { type: "button", style: s.button, onClick: () => { setStep(null); flow.current = null; }, children: say(w, 'Back to sign in') });
158
+ }
159
+ const heading = status === 'needs_details' && step?.reason === 'invited' ? say(w, 'Join {name}', { name: settings.name })
160
+ : status === 'needs_legal_acceptance' ? say(w, 'Before you continue')
161
+ : status === 'needs_new_password' ? say(w, 'Choose a new password')
162
+ : asSignUp ? say(w, 'Create your account for {name}', { name: settings.name })
163
+ : say(w, 'Sign in to {name}', { name: settings.name });
164
+ const fontUrl = settings.look.font?.url;
165
+ return (_jsxs("div", { className: className, style: s.card, lang: settings.lang, dir: settings.dir, children: [font && fontUrl && _jsx("style", { children: `@font-face{font-family:'${font.replace(/'/g, '')}';src:url('${fontUrl.replace(/'/g, '')}') format('woff2');font-display:swap}` }), logo && _jsx("img", { src: logo, alt: settings.name, style: { display: 'block', maxHeight: 40, margin: '0 auto 16px' } }), _jsx("h1", { style: s.title, children: heading }), body, problem && _jsx("p", { role: "alert", style: s.alert, children: problem }), settings.secured_by && _jsx("p", { style: s.foot, children: say(w, 'Secured by {name}', { name: 'Aiveth' }) })] }));
166
+ }
package/dist/client.d.ts CHANGED
@@ -1,3 +1,5 @@
1
+ import type { BoxSettings } from './box.js';
2
+ import { HereFlow } from './here.js';
1
3
  export interface AivethConfig {
2
4
  /** Your Aiveth address, e.g. https://accounts.aiveth.com */
3
5
  issuer: string;
@@ -144,9 +146,43 @@ export declare class AivethClient {
144
146
  * `screenHint: 'sign-up'` opens sign-up where your organization lets people join;
145
147
  * `invitation` (from your sign-in page's address) joins the organization first. */
146
148
  signIn({ returnTo, workspace, ...hints }?: SignInOptions): Promise<void>;
149
+ /** A sign-in about to start: its PKCE verifier, state and nonce kept until it comes back. */
150
+ private pending;
151
+ /** Sign-in on your own page (Aiveth's sign-in API; turn on "Sign-in on your page" for the app):
152
+ * each step answers the next (`Step`); the code is swapped here at the end (`signed_in`). */
153
+ readonly signInHere: {
154
+ start: ({ email, returnTo, workspace }: {
155
+ email: string;
156
+ returnTo?: string;
157
+ workspace?: string;
158
+ }) => Promise<{
159
+ flow: HereFlow;
160
+ step: import("./here.js").Step;
161
+ }>;
162
+ signUp: ({ email, returnTo }: {
163
+ email: string;
164
+ returnTo?: string;
165
+ }) => Promise<{
166
+ flow: HereFlow;
167
+ step: import("./here.js").Step;
168
+ }>;
169
+ /** The `invitation` your sign-in page got (`?invitation=`): its address, then `details`. */
170
+ invitation: (invitation: string, { returnTo }?: {
171
+ returnTo?: string;
172
+ }) => Promise<{
173
+ flow: HereFlow;
174
+ step: import("./here.js").Step;
175
+ }>;
176
+ /** What the ready-made `<SignIn />` shows: the look, the words in ``lang``, the badge. */
177
+ settings: (lang?: string) => Promise<BoxSettings>;
178
+ };
179
+ private hereFlow;
147
180
  /** On the return address: swap the code for tokens. Answers where the app wanted to go
148
181
  * (`returnTo`), or null when this page load isn't a return from Aiveth. */
149
182
  handleRedirect(url: string): Promise<Returned>;
183
+ /** The sign-in that started here comes back: its state checked, the code swapped for tokens —
184
+ * from the redirect (`handleRedirect`) or the sign-in API (`signInHere`) alike. */
185
+ private complete;
150
186
  private exchange;
151
187
  /** The signed-in workspace from your own pages (Aiveth's My workspace API): set `audience` to
152
188
  * `myWorkspaceAudience(issuer)` and sign in with `workspace`. Every member reads; only the
package/dist/client.js CHANGED
@@ -1,5 +1,6 @@
1
1
  /* Signing in from a single-page app, the way the IETF's browser-app best practice and RFC 8252 ask:
2
2
  * - on AIVETH's page (a redirect) — the password, passkeys, two-step and SSO never touch the app;
3
+ * or on your own page (`signInHere`, Aiveth's sign-in API) when the app turned that on;
3
4
  * - authorization code + PKCE (S256), with `state` and `nonce`;
4
5
  * - tokens kept IN MEMORY only, never localStorage; only the short-lived PKCE values sit in
5
6
  * sessionStorage, for the round trip, and are removed on return;
@@ -7,6 +8,7 @@
7
8
  * A reload forgets the tokens: `signIn()` again comes straight back while the person is still
8
9
  * signed in at Aiveth. The app must be a PUBLIC app (no secret) whose return address is
9
10
  * `redirectUri`; its origin may then call Aiveth's token endpoint (CORS). */
11
+ import { HereFlow, StepRefused } from './here.js';
10
12
  /** The audience of Aiveth's My workspace API for this issuer. */
11
13
  export function myWorkspaceAudience(issuer) {
12
14
  return `${issuer.replace(/\/+$/, '')}/my-workspace`;
@@ -124,39 +126,80 @@ export class AivethClient {
124
126
  * `invitation` (from your sign-in page's address) joins the organization first. */
125
127
  async signIn({ returnTo, workspace, ...hints } = {}) {
126
128
  const found = await this.discover();
129
+ const request = await this.pending(returnTo, workspace);
130
+ const query = new URLSearchParams({ client_id: this.config.clientId, response_type: 'code', ...request });
131
+ for (const [key, value] of Object.entries(authorizeHints(hints)))
132
+ query.set(key, value);
133
+ this.navigate(`${found.authorization_endpoint}?${query}`);
134
+ }
135
+ /** A sign-in about to start: its PKCE verifier, state and nonce kept until it comes back. */
136
+ async pending(returnTo, workspace) {
127
137
  const verifier = random(48);
128
138
  const pending = { state: random(), nonce: random(), verifier, returnTo: returnTo ?? null };
129
139
  this.storage.setItem(PENDING, JSON.stringify(pending));
130
- const query = new URLSearchParams({
131
- client_id: this.config.clientId, redirect_uri: this.config.redirectUri, response_type: 'code',
132
- scope: this.config.scope ?? DEFAULT_SCOPE, state: pending.state, nonce: pending.nonce,
133
- code_challenge: await challengeOf(verifier), code_challenge_method: 'S256',
140
+ return {
141
+ redirect_uri: this.config.redirectUri, scope: this.config.scope ?? DEFAULT_SCOPE,
142
+ state: pending.state, nonce: pending.nonce, code_challenge: await challengeOf(verifier),
143
+ code_challenge_method: 'S256',
144
+ ...(this.config.audience ? { resource: this.config.audience } : {}), // RFC 8707
145
+ ...(workspace ? { workspace } : {}), // signed in to that workspace (a member's only)
146
+ };
147
+ }
148
+ /** Sign-in on your own page (Aiveth's sign-in API; turn on "Sign-in on your page" for the app):
149
+ * each step answers the next (`Step`); the code is swapped here at the end (`signed_in`). */
150
+ signInHere = {
151
+ start: async ({ email, returnTo, workspace }) => {
152
+ const flow = this.hereFlow();
153
+ return { flow, step: await flow.begin(await this.pending(returnTo, workspace), email) };
154
+ },
155
+ signUp: async ({ email, returnTo }) => {
156
+ const flow = this.hereFlow();
157
+ return { flow, step: await flow.beginSignUp(await this.pending(returnTo), email) };
158
+ },
159
+ /** The `invitation` your sign-in page got (`?invitation=`): its address, then `details`. */
160
+ invitation: async (invitation, { returnTo } = {}) => {
161
+ const flow = this.hereFlow();
162
+ return { flow, step: await flow.beginInvitation(await this.pending(returnTo), invitation) };
163
+ },
164
+ /** What the ready-made `<SignIn />` shows: the look, the words in ``lang``, the badge. */
165
+ settings: async (lang = '') => {
166
+ const res = await this.fetcher(`${this.issuer}/v1/sign-in/${encodeURIComponent(this.config.clientId)}/box?${new URLSearchParams({ lang })}`);
167
+ if (!res.ok)
168
+ throw new StepRefused(res.status, 'Sign-in on this page is not turned on for the app.');
169
+ return (await res.json());
170
+ },
171
+ };
172
+ hereFlow() {
173
+ return new HereFlow({
174
+ baseUrl: this.issuer, clientId: this.config.clientId, fetch: this.fetcher, navigate: this.navigate,
175
+ finish: async (code, state) => {
176
+ const done = await this.complete(code, state, null, null);
177
+ return { status: 'signed_in', returnTo: done.returnTo };
178
+ },
134
179
  });
135
- if (this.config.audience)
136
- query.set('resource', this.config.audience); // RFC 8707
137
- if (workspace)
138
- query.set('workspace', workspace); // signed in to that workspace (a member's only)
139
- for (const [key, value] of Object.entries(authorizeHints(hints)))
140
- query.set(key, value);
141
- this.navigate(`${found.authorization_endpoint}?${query}`);
142
180
  }
143
181
  /** On the return address: swap the code for tokens. Answers where the app wanted to go
144
182
  * (`returnTo`), or null when this page load isn't a return from Aiveth. */
145
183
  async handleRedirect(url) {
146
184
  const params = new URL(url).searchParams;
147
- const raw = this.storage.getItem(PENDING);
148
- if (!raw || (!params.has('code') && !params.has('error')))
185
+ if (!this.storage.getItem(PENDING) || (!params.has('code') && !params.has('error')))
149
186
  return { handled: false, returnTo: null };
187
+ return this.complete(params.get('code') ?? '', params.get('state'), params.get('error'), params.get('error_description'));
188
+ }
189
+ /** The sign-in that started here comes back: its state checked, the code swapped for tokens —
190
+ * from the redirect (`handleRedirect`) or the sign-in API (`signInHere`) alike. */
191
+ async complete(code, state, error, description) {
192
+ const raw = this.storage.getItem(PENDING);
193
+ if (!raw)
194
+ throw new SignInError('That sign-in did not start here.');
150
195
  this.storage.removeItem(PENDING);
151
196
  const pending = JSON.parse(raw);
152
- if (params.get('state') !== pending.state)
197
+ if (state !== pending.state)
153
198
  throw new SignInError('That sign-in did not start here.');
154
- const refused = params.get('error');
155
- if (refused)
156
- throw new SignInError(params.get('error_description') ?? refused);
199
+ if (error)
200
+ throw new SignInError(description ?? error);
157
201
  await this.exchange({
158
- grant_type: 'authorization_code', code: params.get('code') ?? '', redirect_uri: this.config.redirectUri,
159
- code_verifier: pending.verifier,
202
+ grant_type: 'authorization_code', code, redirect_uri: this.config.redirectUri, code_verifier: pending.verifier,
160
203
  }, pending.nonce);
161
204
  return { handled: true, returnTo: pending.returnTo };
162
205
  }
package/dist/here.d.ts ADDED
@@ -0,0 +1,87 @@
1
+ /** What the next screen is. `signed_in`: done. `needs_aiveth`: send the browser to
2
+ * `continueUrl` (a step only Aiveth's page can do), or call `continueOnAiveth()`. */
3
+ export type StepStatus = 'needs_first_factor' | 'needs_second_factor' | 'needs_legal_acceptance' | 'needs_email_code' | 'needs_details' | 'needs_reset_code' | 'needs_new_password' | 'waiting' | 'needs_aiveth' | 'refused' | 'signed_in';
4
+ export interface Step {
5
+ status: StepStatus;
6
+ /** needs_first_factor: `password`, `email_code`, and `google` / `microsoft` / `github` / `sso`
7
+ * (for those, use `signIn({ connection })`). */
8
+ ways?: string[];
9
+ /** needs_second_factor: `authenticator`, `recovery_code`. */
10
+ factors?: string[];
11
+ /** needs_details: the fields to ask for. */
12
+ fields?: string[];
13
+ /** needs_details from an invitation: the address it was sent to. */
14
+ email?: string;
15
+ reason?: string;
16
+ termsUrl?: string;
17
+ privacyUrl?: string;
18
+ continueUrl?: string;
19
+ error?: string;
20
+ errorDescription?: string;
21
+ /** signed_in: where your app wanted to go. */
22
+ returnTo?: string | null;
23
+ }
24
+ /** A step Aiveth refused: `status` is the HTTP status (401 a wrong password or code, 422 a
25
+ * password the rules refuse, 429 too many tries, 404 the attempt ended). */
26
+ export declare class StepRefused extends Error {
27
+ readonly status: number;
28
+ constructor(status: number, message: string);
29
+ }
30
+ /** The authorize request the attempt stands for (PKCE, state, nonce). */
31
+ export interface AttemptRequest {
32
+ redirect_uri: string;
33
+ code_challenge: string;
34
+ code_challenge_method: 'S256';
35
+ scope: string;
36
+ state: string;
37
+ nonce: string;
38
+ workspace?: string;
39
+ resource?: string;
40
+ }
41
+ export interface HereSetup {
42
+ baseUrl: string;
43
+ clientId: string;
44
+ fetch: typeof fetch;
45
+ /** The code and its state: swap them for a session; answers the `signed_in` step. */
46
+ finish: (code: string, state: string | null) => Promise<Step>;
47
+ navigate: (url: string) => void;
48
+ }
49
+ /** One sign-in, sign-up, new password or invitation on your page. Each method sends one step
50
+ * and answers the next; a `complete` answer is finished at once (`signed_in`). */
51
+ export declare class HereFlow {
52
+ private readonly setup;
53
+ private attempt;
54
+ private continueUrl;
55
+ constructor(setup: HereSetup);
56
+ private base;
57
+ private send;
58
+ private at;
59
+ /** @internal Begin with the address (a sign-in) — through `signInHere.start`. */
60
+ begin(request: AttemptRequest, email: string): Promise<Step>;
61
+ /** @internal Begin a sign-up — through `signInHere.signUp`. */
62
+ beginSignUp(request: AttemptRequest, email: string): Promise<Step>;
63
+ /** @internal Begin from an invitation link's token — through `signInHere.invitation`. */
64
+ beginInvitation(request: AttemptRequest, invitation: string): Promise<Step>;
65
+ password(password: string): Promise<Step>;
66
+ sendEmailCode(): Promise<Step>;
67
+ verifyEmailCode(code: string): Promise<Step>;
68
+ /** The authenticator code, or one recovery code. */
69
+ secondFactor(code: string): Promise<Step>;
70
+ /** The person ticked your organization's terms (never tick it for them). */
71
+ acceptTerms(): Promise<Step>;
72
+ /** "Forgot password?": a code to the address — the same answer for any address. */
73
+ sendResetCode(): Promise<Step>;
74
+ verifyResetCode(code: string): Promise<Step>;
75
+ setNewPassword(password: string): Promise<Step>;
76
+ /** Sign-up: the code Aiveth emailed. */
77
+ verifySignUpCode(code: string): Promise<Step>;
78
+ resendSignUpCode(): Promise<Step>;
79
+ /** Sign-up or invitation: the name and a password. */
80
+ details(d: {
81
+ firstName: string;
82
+ lastName?: string;
83
+ password: string;
84
+ }): Promise<Step>;
85
+ /** After `needs_aiveth`: the rest on Aiveth's page, then back to your app. */
86
+ continueOnAiveth(): void;
87
+ }
package/dist/here.js ADDED
@@ -0,0 +1,92 @@
1
+ /* Sign-in on your own page (Aiveth's sign-in API, `/v1/sign-in/{client_id}/…`): the steps of a
2
+ * sign-in, a sign-up, a new password or an invitation, each answering a `Step`. The same file
3
+ * is in `@aiveth/react` and `@aiveth/nextjs` — keep them equal. Only `finish` differs: the code
4
+ * is swapped for tokens in the browser (React, PKCE) or by your server (Next.js `/auth/callback`). */
5
+ /** A step Aiveth refused: `status` is the HTTP status (401 a wrong password or code, 422 a
6
+ * password the rules refuse, 429 too many tries, 404 the attempt ended). */
7
+ export class StepRefused extends Error {
8
+ status;
9
+ constructor(status, message) {
10
+ super(message);
11
+ this.status = status;
12
+ this.name = 'StepRefused';
13
+ }
14
+ }
15
+ /** One sign-in, sign-up, new password or invitation on your page. Each method sends one step
16
+ * and answers the next; a `complete` answer is finished at once (`signed_in`). */
17
+ export class HereFlow {
18
+ setup;
19
+ attempt = '';
20
+ continueUrl = '';
21
+ constructor(setup) {
22
+ this.setup = setup;
23
+ }
24
+ base() {
25
+ return `${this.setup.baseUrl}/v1/sign-in/${encodeURIComponent(this.setup.clientId)}`;
26
+ }
27
+ async send(path, body) {
28
+ const res = await this.setup.fetch(`${this.base()}${path}`, {
29
+ method: 'POST', headers: { 'Content-Type': 'application/json' },
30
+ body: body === undefined ? undefined : JSON.stringify(body),
31
+ });
32
+ let said;
33
+ try {
34
+ said = (await res.json());
35
+ }
36
+ catch {
37
+ throw new StepRefused(res.status, `Aiveth answered ${res.status}.`);
38
+ }
39
+ if (!res.ok)
40
+ throw new StepRefused(res.status, typeof said.detail === 'string' ? said.detail : `Aiveth answered ${res.status}.`);
41
+ if (said.attempt)
42
+ this.attempt = said.attempt;
43
+ if (said.status === 'complete')
44
+ return this.setup.finish(said.code ?? '', said.state ?? null);
45
+ if (said.continue_url)
46
+ this.continueUrl = said.continue_url;
47
+ return {
48
+ status: said.status, ways: said.ways, factors: said.factors, fields: said.fields,
49
+ email: said.email, reason: said.reason, termsUrl: said.terms_url, privacyUrl: said.privacy_url,
50
+ continueUrl: said.continue_url, error: said.error, errorDescription: said.error_description,
51
+ };
52
+ }
53
+ at(kind, step) {
54
+ return `/${kind}/${encodeURIComponent(this.attempt)}/${step}`;
55
+ }
56
+ /** @internal Begin with the address (a sign-in) — through `signInHere.start`. */
57
+ begin(request, email) {
58
+ return this.send('/attempts', { ...request, email });
59
+ }
60
+ /** @internal Begin a sign-up — through `signInHere.signUp`. */
61
+ beginSignUp(request, email) {
62
+ return this.send('/sign-ups', { ...request, email });
63
+ }
64
+ /** @internal Begin from an invitation link's token — through `signInHere.invitation`. */
65
+ beginInvitation(request, invitation) {
66
+ return this.send('/invitations', { ...request, invitation });
67
+ }
68
+ password(password) { return this.send(this.at('attempts', 'password'), { password }); }
69
+ sendEmailCode() { return this.send(this.at('attempts', 'email-code')); }
70
+ verifyEmailCode(code) { return this.send(this.at('attempts', 'email-code/verify'), { code }); }
71
+ /** The authenticator code, or one recovery code. */
72
+ secondFactor(code) { return this.send(this.at('attempts', 'second-factor'), { code }); }
73
+ /** The person ticked your organization's terms (never tick it for them). */
74
+ acceptTerms() { return this.send(this.at('attempts', 'terms'), { accepted: true }); }
75
+ /** "Forgot password?": a code to the address — the same answer for any address. */
76
+ sendResetCode() { return this.send(this.at('attempts', 'reset-password')); }
77
+ verifyResetCode(code) { return this.send(this.at('attempts', 'reset-password/verify'), { code }); }
78
+ setNewPassword(password) { return this.send(this.at('attempts', 'reset-password/new'), { password }); }
79
+ /** Sign-up: the code Aiveth emailed. */
80
+ verifySignUpCode(code) { return this.send(this.at('sign-ups', 'verify'), { code }); }
81
+ resendSignUpCode() { return this.send(this.at('sign-ups', 'email-code')); }
82
+ /** Sign-up or invitation: the name and a password. */
83
+ details(d) {
84
+ return this.send(this.at('sign-ups', 'details'), { first_name: d.firstName, last_name: d.lastName ?? '', password: d.password });
85
+ }
86
+ /** After `needs_aiveth`: the rest on Aiveth's page, then back to your app. */
87
+ continueOnAiveth() {
88
+ if (!this.continueUrl)
89
+ throw new StepRefused(409, 'Nothing waits on Aiveth\'s page.');
90
+ this.setup.navigate(this.continueUrl);
91
+ }
92
+ }
package/dist/index.d.ts CHANGED
@@ -1,3 +1,5 @@
1
1
  export { AivethClient, RefusedError, SignInError, authorizeHints, claimsOf, type Connection, type SignInOptions, myWorkspaceAudience, type MyWorkspace, type WorkspaceMember, type WorkspaceInvitationView, type Actor, type AivethConfig, type Returned, type User } from './client.js';
2
- export { AivethProvider, useAiveth, SignedIn, SignedOut, SignInButton, AivethButton, SignOutButton, UserButton, ActingBanner, type AivethProviderProps, type UseAiveth } from './react.js';
2
+ export { AivethProvider, useAiveth, SignedIn, SignedOut, SignInButton, AivethButton, SignOutButton, UserButton, ActingBanner, SignIn, SignUp, type AivethProviderProps, type UseAiveth } from './react.js';
3
+ export { SignInBox, type BoxProps, type BoxSettings, type BoxSetup } from './box.js';
3
4
  export { BrandedButton, useBrandLook, type BrandLook, type BrandedButtonProps } from './brand.js';
5
+ export { HereFlow, StepRefused, type Step, type StepStatus } from './here.js';
package/dist/index.js CHANGED
@@ -1,3 +1,5 @@
1
1
  export { AivethClient, RefusedError, SignInError, authorizeHints, claimsOf, myWorkspaceAudience } from './client.js';
2
- export { AivethProvider, useAiveth, SignedIn, SignedOut, SignInButton, AivethButton, SignOutButton, UserButton, ActingBanner } from './react.js';
2
+ export { AivethProvider, useAiveth, SignedIn, SignedOut, SignInButton, AivethButton, SignOutButton, UserButton, ActingBanner, SignIn, SignUp } from './react.js';
3
+ export { SignInBox } from './box.js';
3
4
  export { BrandedButton, useBrandLook } from './brand.js';
5
+ export { HereFlow, StepRefused } from './here.js';
package/dist/react.d.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  import { type CSSProperties, type ReactNode } from 'react';
2
+ import { type BoxProps } from './box.js';
2
3
  import { AivethClient, type Actor, type AivethConfig, type SignInOptions, type User } from './client.js';
3
4
  export interface AivethProviderProps extends AivethConfig {
4
5
  children: ReactNode;
@@ -14,6 +15,8 @@ export interface UseAiveth {
14
15
  /** A sign-in that went wrong (Aiveth refused, or the round trip didn't start here). */
15
16
  error: Error | null;
16
17
  signIn: (options?: SignInOptions) => Promise<void>;
18
+ /** Sign-in on your own page (Aiveth's sign-in API): `start`, `signUp`, `invitation`. */
19
+ signInHere: AivethClient['signInHere'];
17
20
  signOut: () => Promise<void>;
18
21
  /** For your API calls: `Authorization: Bearer …`. Null when signed out. */
19
22
  getAccessToken: () => Promise<string | null>;
@@ -63,3 +66,16 @@ export declare function UserButton({ className }: {
63
66
  export declare function ActingBanner({ className }: {
64
67
  className?: string;
65
68
  }): import("react/jsx-runtime").JSX.Element | null;
69
+ /** The ready-made sign-in on your own page (turn on "Sign-in on your page" for the app in
70
+ * Aiveth): every step, in your organization's look and the person's language, "Secured by
71
+ * Aiveth" below on Free and Pro. `onSignedIn`: where to go next with your router (tokens are
72
+ * kept in memory — never reload the page to move on). */
73
+ export declare function SignIn(props: BoxProps & {
74
+ returnTo?: string;
75
+ onSignedIn?: (returnTo: string | null) => void;
76
+ }): import("react/jsx-runtime").JSX.Element;
77
+ /** `<SignIn />` opening on sign-up, where your organization lets people join from its apps. */
78
+ export declare function SignUp(props: BoxProps & {
79
+ returnTo?: string;
80
+ onSignedIn?: (returnTo: string | null) => void;
81
+ }): import("react/jsx-runtime").JSX.Element;
package/dist/react.js CHANGED
@@ -4,6 +4,7 @@ import { jsx as _jsx, Fragment as _Fragment, jsxs as _jsxs } from "react/jsx-run
4
4
  * itself happens on Aiveth's page (RFC 8252). */
5
5
  import { createContext, useCallback, useContext, useEffect, useMemo, useRef, useState, useSyncExternalStore } from 'react';
6
6
  import { BrandedButton, useBrandLook } from './brand.js';
7
+ import { SignInBox } from './box.js';
7
8
  import { AivethClient } from './client.js';
8
9
  const Context = createContext(null);
9
10
  /** Put it around your app. On the return address it finishes the sign-in by itself. */
@@ -45,7 +46,7 @@ export function useAiveth() {
45
46
  const user = useSyncExternalStore(useCallback((on) => client.subscribe(on), [client]), () => client.user);
46
47
  return {
47
48
  isLoaded: ctx.isLoaded, isSignedIn: user !== null, user, error: ctx.error,
48
- signIn: (o) => client.signIn(o), signOut: () => client.signOut(),
49
+ signIn: (o) => client.signIn(o), signInHere: client.signInHere, signOut: () => client.signOut(),
49
50
  getAccessToken: () => client.getAccessToken(), accountUrl: client.accountUrl(),
50
51
  actor: actorOf(user), actingUrl: client.actingUrl(),
51
52
  hasFlag: (key) => Array.isArray(user?.feature_flags) && user.feature_flags.includes(key),
@@ -114,3 +115,32 @@ export function ActingBanner({ className }) {
114
115
  const name = user.name ?? user.email ?? 'this person';
115
116
  return (_jsxs("div", { role: "status", style: BANNER.bar, className: className, children: [_jsxs("span", { children: [_jsxs("strong", { children: ["Acting as ", name] }), " \u00B7 by ", actor.email ?? 'support', actor.reason ? ` · ${actor.reason}` : ''] }), _jsx("a", { href: actingUrl, style: BANNER.end, children: "End" })] }));
116
117
  }
118
+ /** The ready-made sign-in on your own page (turn on "Sign-in on your page" for the app in
119
+ * Aiveth): every step, in your organization's look and the person's language, "Secured by
120
+ * Aiveth" below on Free and Pro. `onSignedIn`: where to go next with your router (tokens are
121
+ * kept in memory — never reload the page to move on). */
122
+ export function SignIn(props) {
123
+ return _jsx(SignInBox, { setup: useBoxSetup(props), mode: "sign-in", ...props });
124
+ }
125
+ /** `<SignIn />` opening on sign-up, where your organization lets people join from its apps. */
126
+ export function SignUp(props) {
127
+ return _jsx(SignInBox, { setup: useBoxSetup(props), mode: "sign-up", ...props });
128
+ }
129
+ function useBoxSetup({ returnTo, onSignedIn }) {
130
+ const ctx = useContext(Context);
131
+ if (!ctx)
132
+ throw new Error('<SignIn /> needs <AivethProvider> around your app.');
133
+ const { client } = ctx;
134
+ const after = useRef(onSignedIn);
135
+ after.current = onSignedIn;
136
+ return useMemo(() => ({
137
+ settings: (lang) => client.signInHere.settings(lang),
138
+ start: (email) => client.signInHere.start({ email, returnTo }),
139
+ signUp: (email) => client.signInHere.signUp({ email, returnTo }),
140
+ invitation: (token) => client.signInHere.invitation(token, { returnTo }),
141
+ withProvider: (connection, email) => {
142
+ void client.signIn({ connection: connection, loginHint: email || undefined, returnTo });
143
+ },
144
+ onSignedIn: (step) => after.current?.(step.returnTo ?? null),
145
+ }), [client, returnTo]);
146
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aiveth/react",
3
- "version": "0.11.0",
3
+ "version": "0.13.0",
4
4
  "description": "Official Aiveth SDK for React: sign in on Aiveth's page with PKCE, tokens kept in memory, and ready-made sign-in pieces.",
5
5
  "license": "Apache-2.0",
6
6
  "author": "Aiveth team",