@aiveth/react 0.11.0 → 0.12.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,9 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.12.0 — unreleased
4
+
5
+ - `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.
6
+
3
7
  ## 0.11.0 — unreleased
4
8
 
5
9
  - `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,25 @@ 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
+
47
66
  ## Sign in in your organization's own look
48
67
 
49
68
  `<AivethButton>` draws "Sign in" with what you set in Aiveth → Branding — colours (light and
package/dist/client.d.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import { HereFlow } from './here.js';
1
2
  export interface AivethConfig {
2
3
  /** Your Aiveth address, e.g. https://accounts.aiveth.com */
3
4
  issuer: string;
@@ -144,9 +145,41 @@ export declare class AivethClient {
144
145
  * `screenHint: 'sign-up'` opens sign-up where your organization lets people join;
145
146
  * `invitation` (from your sign-in page's address) joins the organization first. */
146
147
  signIn({ returnTo, workspace, ...hints }?: SignInOptions): Promise<void>;
148
+ /** A sign-in about to start: its PKCE verifier, state and nonce kept until it comes back. */
149
+ private pending;
150
+ /** Sign-in on your own page (Aiveth's sign-in API; turn on "Sign-in on your page" for the app):
151
+ * each step answers the next (`Step`); the code is swapped here at the end (`signed_in`). */
152
+ readonly signInHere: {
153
+ start: ({ email, returnTo, workspace }: {
154
+ email: string;
155
+ returnTo?: string;
156
+ workspace?: string;
157
+ }) => Promise<{
158
+ flow: HereFlow;
159
+ step: import("./here.js").Step;
160
+ }>;
161
+ signUp: ({ email, returnTo }: {
162
+ email: string;
163
+ returnTo?: string;
164
+ }) => Promise<{
165
+ flow: HereFlow;
166
+ step: import("./here.js").Step;
167
+ }>;
168
+ /** The `invitation` your sign-in page got (`?invitation=`): its address, then `details`. */
169
+ invitation: (invitation: string, { returnTo }?: {
170
+ returnTo?: string;
171
+ }) => Promise<{
172
+ flow: HereFlow;
173
+ step: import("./here.js").Step;
174
+ }>;
175
+ };
176
+ private hereFlow;
147
177
  /** On the return address: swap the code for tokens. Answers where the app wanted to go
148
178
  * (`returnTo`), or null when this page load isn't a return from Aiveth. */
149
179
  handleRedirect(url: string): Promise<Returned>;
180
+ /** The sign-in that started here comes back: its state checked, the code swapped for tokens —
181
+ * from the redirect (`handleRedirect`) or the sign-in API (`signInHere`) alike. */
182
+ private complete;
150
183
  private exchange;
151
184
  /** The signed-in workspace from your own pages (Aiveth's My workspace API): set `audience` to
152
185
  * `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 } 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,73 @@ 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
+ };
165
+ hereFlow() {
166
+ return new HereFlow({
167
+ baseUrl: this.issuer, clientId: this.config.clientId, fetch: this.fetcher, navigate: this.navigate,
168
+ finish: async (code, state) => {
169
+ const done = await this.complete(code, state, null, null);
170
+ return { status: 'signed_in', returnTo: done.returnTo };
171
+ },
134
172
  });
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
173
  }
143
174
  /** On the return address: swap the code for tokens. Answers where the app wanted to go
144
175
  * (`returnTo`), or null when this page load isn't a return from Aiveth. */
145
176
  async handleRedirect(url) {
146
177
  const params = new URL(url).searchParams;
147
- const raw = this.storage.getItem(PENDING);
148
- if (!raw || (!params.has('code') && !params.has('error')))
178
+ if (!this.storage.getItem(PENDING) || (!params.has('code') && !params.has('error')))
149
179
  return { handled: false, returnTo: null };
180
+ return this.complete(params.get('code') ?? '', params.get('state'), params.get('error'), params.get('error_description'));
181
+ }
182
+ /** The sign-in that started here comes back: its state checked, the code swapped for tokens —
183
+ * from the redirect (`handleRedirect`) or the sign-in API (`signInHere`) alike. */
184
+ async complete(code, state, error, description) {
185
+ const raw = this.storage.getItem(PENDING);
186
+ if (!raw)
187
+ throw new SignInError('That sign-in did not start here.');
150
188
  this.storage.removeItem(PENDING);
151
189
  const pending = JSON.parse(raw);
152
- if (params.get('state') !== pending.state)
190
+ if (state !== pending.state)
153
191
  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);
192
+ if (error)
193
+ throw new SignInError(description ?? error);
157
194
  await this.exchange({
158
- grant_type: 'authorization_code', code: params.get('code') ?? '', redirect_uri: this.config.redirectUri,
159
- code_verifier: pending.verifier,
195
+ grant_type: 'authorization_code', code, redirect_uri: this.config.redirectUri, code_verifier: pending.verifier,
160
196
  }, pending.nonce);
161
197
  return { handled: true, returnTo: pending.returnTo };
162
198
  }
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,4 @@
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
2
  export { AivethProvider, useAiveth, SignedIn, SignedOut, SignInButton, AivethButton, SignOutButton, UserButton, ActingBanner, type AivethProviderProps, type UseAiveth } from './react.js';
3
3
  export { BrandedButton, useBrandLook, type BrandLook, type BrandedButtonProps } from './brand.js';
4
+ export { HereFlow, StepRefused, type Step, type StepStatus } from './here.js';
package/dist/index.js CHANGED
@@ -1,3 +1,4 @@
1
1
  export { AivethClient, RefusedError, SignInError, authorizeHints, claimsOf, myWorkspaceAudience } from './client.js';
2
2
  export { AivethProvider, useAiveth, SignedIn, SignedOut, SignInButton, AivethButton, SignOutButton, UserButton, ActingBanner } from './react.js';
3
3
  export { BrandedButton, useBrandLook } from './brand.js';
4
+ export { HereFlow, StepRefused } from './here.js';
package/dist/react.d.ts CHANGED
@@ -14,6 +14,8 @@ export interface UseAiveth {
14
14
  /** A sign-in that went wrong (Aiveth refused, or the round trip didn't start here). */
15
15
  error: Error | null;
16
16
  signIn: (options?: SignInOptions) => Promise<void>;
17
+ /** Sign-in on your own page (Aiveth's sign-in API): `start`, `signUp`, `invitation`. */
18
+ signInHere: AivethClient['signInHere'];
17
19
  signOut: () => Promise<void>;
18
20
  /** For your API calls: `Authorization: Bearer …`. Null when signed out. */
19
21
  getAccessToken: () => Promise<string | null>;
package/dist/react.js CHANGED
@@ -45,7 +45,7 @@ export function useAiveth() {
45
45
  const user = useSyncExternalStore(useCallback((on) => client.subscribe(on), [client]), () => client.user);
46
46
  return {
47
47
  isLoaded: ctx.isLoaded, isSignedIn: user !== null, user, error: ctx.error,
48
- signIn: (o) => client.signIn(o), signOut: () => client.signOut(),
48
+ signIn: (o) => client.signIn(o), signInHere: client.signInHere, signOut: () => client.signOut(),
49
49
  getAccessToken: () => client.getAccessToken(), accountUrl: client.accountUrl(),
50
50
  actor: actorOf(user), actingUrl: client.actingUrl(),
51
51
  hasFlag: (key) => Array.isArray(user?.feature_flags) && user.feature_flags.includes(key),
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aiveth/react",
3
- "version": "0.11.0",
3
+ "version": "0.12.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",