@aiveth/react 0.0.0-stage → 0.1.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 ADDED
@@ -0,0 +1,7 @@
1
+ # Changelog
2
+
3
+ ## 0.1.0 — first release
4
+
5
+ - Sign in on Aiveth's own page (PKCE), tokens kept in memory, ready-made pieces (`<SignedIn>`,
6
+ `<SignInButton>`, `<UserButton>`, `<ActingBanner>`).
7
+ - Feature flags (`useAiveth().hasFlag`), the person's photo (`user.picture`).
package/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/README.md CHANGED
@@ -1,3 +1,51 @@
1
- # Temporary Holding Version
1
+ # @aiveth/react
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Aiveth by Gooclaim for React 18 single-page apps. Register a **public** app in the console whose
4
+ return address is your callback page; its origin may then call Aiveth's token endpoint.
5
+
6
+ ```tsx
7
+ import { AivethProvider, SignedIn, SignedOut, SignInButton, UserButton, useAiveth } from '@aiveth/react';
8
+
9
+ <AivethProvider issuer="https://aiveth.example.com" clientId="your-app-client-id"
10
+ redirectUri="https://app.example.com/callback" postLogoutRedirectUri="https://app.example.com/">
11
+ <SignedOut><SignInButton /></SignedOut>
12
+ <SignedIn><UserButton /></SignedIn>
13
+ </AivethProvider>
14
+
15
+ // Anywhere inside:
16
+ const { user, getAccessToken } = useAiveth();
17
+ const token = await getAccessToken(); // Authorization: Bearer … for your API
18
+ ```
19
+
20
+ - Sign-in happens on Aiveth's page (code + PKCE); tokens are kept in memory, never in
21
+ localStorage. After a reload, `signIn()` comes straight back while the person is signed in at
22
+ Aiveth.
23
+ - Refresh tokens (`offline_access`, asked by default) are swapped at every use.
24
+ - One app belongs to one organization in Aiveth, so there is no organization switcher.
25
+
26
+ ## Acting for others (support signed in as a person)
27
+
28
+ When a support person acts as someone (Aiveth → Security → Acting for others), the ID token
29
+ carries `act` (who, and why). Show it, and block what support shouldn't do:
30
+
31
+ ```tsx
32
+ import { ActingBanner, useAiveth } from '@aiveth/react';
33
+
34
+ <ActingBanner /> {/* "Acting as Asha · by ravi@acme.com · Invoice page is blank [End]" */}
35
+
36
+ const { actor } = useAiveth();
37
+ if (actor) { /* hide "Pay now", "Delete account"… */ }
38
+ ```
39
+
40
+ ## Feature flags and the person's photo
41
+
42
+ ```tsx
43
+ const { user, hasFlag } = useAiveth();
44
+ {hasFlag('new-billing') && <NewBilling />}
45
+ <img src={user?.picture} alt="" />
46
+ ```
47
+
48
+ ## Development and production
49
+
50
+ Use your Development environment's app (`okc_test_…`, `http://localhost` allowed) while you build,
51
+ and the production app (`okc_live_…`, https only) when you ship.
@@ -0,0 +1,92 @@
1
+ export interface AivethConfig {
2
+ /** Your Aiveth address, e.g. https://aiveth.dev.gooclaim.com */
3
+ issuer: string;
4
+ clientId: string;
5
+ /** Exactly one of the app's registered return addresses. */
6
+ redirectUri: string;
7
+ scope?: string;
8
+ /** Where Aiveth sends the person after signing out (registered under the app's sign-out). */
9
+ postLogoutRedirectUri?: string;
10
+ /** For tests. */
11
+ fetch?: typeof fetch;
12
+ storage?: Pick<Storage, 'getItem' | 'setItem' | 'removeItem'>;
13
+ navigate?: (url: string) => void;
14
+ }
15
+ /** Someone acting as the person (Aiveth's "Acting for others"; RFC 8693's `act` claim). */
16
+ export interface Actor {
17
+ /** The support person's Aiveth id. */
18
+ sub: string;
19
+ email?: string;
20
+ reason?: string;
21
+ }
22
+ export interface User {
23
+ sub: string;
24
+ org_id: string;
25
+ email?: string;
26
+ email_verified?: boolean;
27
+ name?: string | null;
28
+ given_name?: string | null;
29
+ family_name?: string | null;
30
+ role?: string;
31
+ permissions?: string[];
32
+ /** Present only while someone acts as this person: who, and why. */
33
+ act?: Actor;
34
+ /** The person's photo on Aiveth (with the `profile` scope). */
35
+ picture?: string;
36
+ /** The organization's feature flags that are on for this person — present once it has one. */
37
+ feature_flags?: string[];
38
+ [claim: string]: unknown;
39
+ }
40
+ /** What `handleRedirect` did: `handled` — this load was a return from Aiveth (clean the address
41
+ * bar either way); `returnTo` — where the app wanted to go. */
42
+ export interface Returned {
43
+ handled: boolean;
44
+ returnTo: string | null;
45
+ }
46
+ export declare class SignInError extends Error {
47
+ constructor(message: string);
48
+ }
49
+ /** The ID token's claims. It came straight from Aiveth's token endpoint over TLS, to this app
50
+ * (OIDC Core §3.1.3.7); the claims that bind it — issuer, audience, nonce, expiry — are checked. */
51
+ export declare function claimsOf(idToken: string): Record<string, unknown>;
52
+ /** Aiveth said no (its OAuth `error` code is kept: `invalid_grant` means the token has ended). */
53
+ export declare class RefusedError extends SignInError {
54
+ readonly code: string;
55
+ constructor(code: string, message: string);
56
+ }
57
+ export declare class AivethClient {
58
+ private readonly config;
59
+ private readonly issuer;
60
+ private readonly fetcher;
61
+ private readonly storage;
62
+ private readonly navigate;
63
+ private discovery;
64
+ private tokens;
65
+ private refreshing;
66
+ /** Bumped at sign-out: an answer that set out before it never signs anyone back in. */
67
+ private generation;
68
+ private readonly listeners;
69
+ user: User | null;
70
+ constructor(config: AivethConfig);
71
+ subscribe(listener: () => void): () => void;
72
+ private changed;
73
+ private discover;
74
+ /** To Aiveth's sign-in page; back at `redirectUri`, `handleRedirect` finishes. */
75
+ signIn({ returnTo }?: {
76
+ returnTo?: string;
77
+ }): Promise<void>;
78
+ /** On the return address: swap the code for tokens. Answers where the app wanted to go
79
+ * (`returnTo`), or null when this page load isn't a return from Aiveth. */
80
+ handleRedirect(url: string): Promise<Returned>;
81
+ private exchange;
82
+ /** A live access token for calling your API — renewed with the refresh token when it is near
83
+ * its end; null when signed out (or the refresh token has ended: sign in again). */
84
+ getAccessToken(): Promise<string | null>;
85
+ private forget;
86
+ /** Signs out here AND at Aiveth: the refresh token is revoked, then Aiveth's sign-out page. */
87
+ signOut(): Promise<void>;
88
+ /** The person's account page at Aiveth (password, two-step, passkeys, connected accounts). */
89
+ accountUrl(): string;
90
+ /** Aiveth's page that ends acting as someone (its End button). */
91
+ actingUrl(): string;
92
+ }
package/dist/client.js ADDED
@@ -0,0 +1,227 @@
1
+ /* Signing in from a single-page app, the way the IETF's browser-app best practice and RFC 8252 ask:
2
+ * - on AIVETH's page (a redirect) — the password, passkeys, two-step and SSO never touch the app;
3
+ * - authorization code + PKCE (S256), with `state` and `nonce`;
4
+ * - tokens kept IN MEMORY only, never localStorage; only the short-lived PKCE values sit in
5
+ * sessionStorage, for the round trip, and are removed on return;
6
+ * - refresh tokens (ask for `offline_access`) swapped at every use (Aiveth rotates them).
7
+ * A reload forgets the tokens: `signIn()` again comes straight back while the person is still
8
+ * signed in at Aiveth. The app must be a PUBLIC app (no secret) whose return address is
9
+ * `redirectUri`; its origin may then call Aiveth's token endpoint (CORS). */
10
+ const PENDING = 'aiveth:pending';
11
+ const DEFAULT_SCOPE = 'openid email profile offline_access';
12
+ /** An access token this close to its end is renewed first. */
13
+ const EARLY_MS = 30_000;
14
+ const LOCAL = new Set(['localhost', '127.0.0.1', '[::1]']);
15
+ /** https only (http just for this machine): over plain http anyone could answer for Aiveth. */
16
+ function trusted(url, what) {
17
+ const parsed = new URL(url);
18
+ if (parsed.protocol === 'https:' || (parsed.protocol === 'http:' && LOCAL.has(parsed.hostname)))
19
+ return url.replace(/\/+$/, '');
20
+ throw new SignInError(`${what} must be an https:// address (http only for localhost).`);
21
+ }
22
+ export class SignInError extends Error {
23
+ constructor(message) {
24
+ super(message);
25
+ this.name = 'SignInError';
26
+ }
27
+ }
28
+ function b64url(bytes) {
29
+ let text = '';
30
+ bytes.forEach((b) => { text += String.fromCharCode(b); });
31
+ return btoa(text).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
32
+ }
33
+ function random(size = 32) {
34
+ return b64url(crypto.getRandomValues(new Uint8Array(size)));
35
+ }
36
+ async function challengeOf(verifier) {
37
+ return b64url(new Uint8Array(await crypto.subtle.digest('SHA-256', new TextEncoder().encode(verifier))));
38
+ }
39
+ /** The ID token's claims. It came straight from Aiveth's token endpoint over TLS, to this app
40
+ * (OIDC Core §3.1.3.7); the claims that bind it — issuer, audience, nonce, expiry — are checked. */
41
+ export function claimsOf(idToken) {
42
+ const part = idToken.split('.')[1];
43
+ if (!part)
44
+ throw new SignInError('Not an ID token.');
45
+ const json = atob(part.replace(/-/g, '+').replace(/_/g, '/'));
46
+ return JSON.parse(decodeURIComponent(Array.from(json, (c) => `%${c.charCodeAt(0).toString(16).padStart(2, '0')}`).join('')));
47
+ }
48
+ /** Aiveth said no (its OAuth `error` code is kept: `invalid_grant` means the token has ended). */
49
+ export class RefusedError extends SignInError {
50
+ code;
51
+ constructor(code, message) {
52
+ super(message);
53
+ this.code = code;
54
+ this.name = 'RefusedError';
55
+ }
56
+ }
57
+ export class AivethClient {
58
+ config;
59
+ issuer;
60
+ fetcher;
61
+ storage;
62
+ navigate;
63
+ discovery = null;
64
+ tokens = null;
65
+ refreshing = null;
66
+ /** Bumped at sign-out: an answer that set out before it never signs anyone back in. */
67
+ generation = 0;
68
+ listeners = new Set();
69
+ user = null;
70
+ constructor(config) {
71
+ this.config = config;
72
+ this.issuer = trusted(config.issuer, 'issuer');
73
+ this.fetcher = config.fetch ?? globalThis.fetch.bind(globalThis);
74
+ this.storage = config.storage ?? globalThis.sessionStorage;
75
+ this.navigate = config.navigate ?? ((url) => { globalThis.location.assign(url); });
76
+ }
77
+ subscribe(listener) {
78
+ this.listeners.add(listener);
79
+ return () => { this.listeners.delete(listener); };
80
+ }
81
+ changed() {
82
+ this.listeners.forEach((l) => l());
83
+ }
84
+ discover() {
85
+ this.discovery ??= this.fetcher(`${this.issuer}/.well-known/openid-configuration`).then(async (res) => {
86
+ if (!res.ok)
87
+ throw new SignInError(`Aiveth's discovery document answered ${res.status}.`);
88
+ const found = (await res.json());
89
+ // OIDC Discovery §4.3: the issuer is the address you gave; every endpoint https.
90
+ if (String(found.issuer ?? '').replace(/\/+$/, '') !== this.issuer)
91
+ throw new SignInError("Aiveth's discovery names another issuer.");
92
+ trusted(found.token_endpoint, 'token_endpoint');
93
+ trusted(found.authorization_endpoint, 'authorization_endpoint');
94
+ return found;
95
+ }).catch((e) => {
96
+ this.discovery = null; // try again next time, never stuck until a reload
97
+ throw e;
98
+ });
99
+ return this.discovery;
100
+ }
101
+ /** To Aiveth's sign-in page; back at `redirectUri`, `handleRedirect` finishes. */
102
+ async signIn({ returnTo } = {}) {
103
+ const found = await this.discover();
104
+ const verifier = random(48);
105
+ const pending = { state: random(), nonce: random(), verifier, returnTo: returnTo ?? null };
106
+ this.storage.setItem(PENDING, JSON.stringify(pending));
107
+ const query = new URLSearchParams({
108
+ client_id: this.config.clientId, redirect_uri: this.config.redirectUri, response_type: 'code',
109
+ scope: this.config.scope ?? DEFAULT_SCOPE, state: pending.state, nonce: pending.nonce,
110
+ code_challenge: await challengeOf(verifier), code_challenge_method: 'S256',
111
+ });
112
+ this.navigate(`${found.authorization_endpoint}?${query}`);
113
+ }
114
+ /** On the return address: swap the code for tokens. Answers where the app wanted to go
115
+ * (`returnTo`), or null when this page load isn't a return from Aiveth. */
116
+ async handleRedirect(url) {
117
+ const params = new URL(url).searchParams;
118
+ const raw = this.storage.getItem(PENDING);
119
+ if (!raw || (!params.has('code') && !params.has('error')))
120
+ return { handled: false, returnTo: null };
121
+ this.storage.removeItem(PENDING);
122
+ const pending = JSON.parse(raw);
123
+ if (params.get('state') !== pending.state)
124
+ throw new SignInError('That sign-in did not start here.');
125
+ const refused = params.get('error');
126
+ if (refused)
127
+ throw new SignInError(params.get('error_description') ?? refused);
128
+ await this.exchange({
129
+ grant_type: 'authorization_code', code: params.get('code') ?? '', redirect_uri: this.config.redirectUri,
130
+ code_verifier: pending.verifier,
131
+ }, pending.nonce);
132
+ return { handled: true, returnTo: pending.returnTo };
133
+ }
134
+ async exchange(form, nonce) {
135
+ const found = await this.discover();
136
+ const started = this.generation;
137
+ const res = await this.fetcher(found.token_endpoint, {
138
+ method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
139
+ body: new URLSearchParams({ ...form, client_id: this.config.clientId }),
140
+ });
141
+ let body;
142
+ try {
143
+ body = (await res.json());
144
+ }
145
+ catch {
146
+ throw new SignInError(`Aiveth answered ${res.status}.`); // an error page that isn't JSON
147
+ }
148
+ if (!res.ok)
149
+ throw new RefusedError(String(body.error ?? ''), String(body.error_description ?? body.error ?? `Aiveth answered ${res.status}.`));
150
+ const idToken = String(body.id_token ?? '');
151
+ const claims = claimsOf(idToken);
152
+ const audience = Array.isArray(claims.aud) ? claims.aud : [claims.aud];
153
+ if (claims.iss !== found.issuer || !audience.includes(this.config.clientId))
154
+ throw new SignInError('That ID token is not for this app.');
155
+ if (nonce !== null && claims.nonce !== nonce)
156
+ throw new SignInError('That ID token does not answer this sign-in.');
157
+ if (typeof claims.exp !== 'number' || claims.exp * 1000 < Date.now())
158
+ throw new SignInError('That ID token has ended.');
159
+ if (this.user && claims.sub !== this.user.sub)
160
+ throw new SignInError('A renewed ID token named someone else.'); // OIDC §12.2
161
+ if (this.generation !== started)
162
+ throw new SignInError('Signed out meanwhile.');
163
+ this.tokens = {
164
+ accessToken: String(body.access_token), idToken,
165
+ refreshToken: typeof body.refresh_token === 'string' ? body.refresh_token : this.tokens?.refreshToken ?? null,
166
+ expiresAt: Date.now() + Number(body.expires_in ?? 0) * 1000,
167
+ };
168
+ this.user = claims;
169
+ this.changed();
170
+ return this.tokens;
171
+ }
172
+ /** A live access token for calling your API — renewed with the refresh token when it is near
173
+ * its end; null when signed out (or the refresh token has ended: sign in again). */
174
+ async getAccessToken() {
175
+ if (!this.tokens)
176
+ return null;
177
+ if (this.tokens.expiresAt - EARLY_MS > Date.now())
178
+ return this.tokens.accessToken;
179
+ const held = this.tokens.refreshToken;
180
+ if (!held)
181
+ return null;
182
+ this.refreshing ??= this.exchange({ grant_type: 'refresh_token', refresh_token: held }, null)
183
+ .catch((e) => {
184
+ // Aiveth refused the refresh token (ended, reused, signed out): signed out here too. A
185
+ // network blip is no sign-out — the next call tries again.
186
+ if (e instanceof RefusedError && e.code === 'invalid_grant')
187
+ this.forget();
188
+ return null;
189
+ })
190
+ .finally(() => { this.refreshing = null; });
191
+ return (await this.refreshing)?.accessToken ?? null;
192
+ }
193
+ forget() {
194
+ this.generation += 1;
195
+ this.tokens = null;
196
+ this.user = null;
197
+ this.changed();
198
+ }
199
+ /** Signs out here AND at Aiveth: the refresh token is revoked, then Aiveth's sign-out page. */
200
+ async signOut() {
201
+ const held = this.tokens;
202
+ this.forget(); // signed out here first, whatever happens next
203
+ const found = await this.discover();
204
+ if (held?.refreshToken && found.revocation_endpoint) {
205
+ await this.fetcher(found.revocation_endpoint, {
206
+ method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
207
+ body: new URLSearchParams({ token: held.refreshToken, token_type_hint: 'refresh_token', client_id: this.config.clientId }),
208
+ }).catch(() => undefined);
209
+ }
210
+ if (found.end_session_endpoint) {
211
+ const query = new URLSearchParams({ client_id: this.config.clientId });
212
+ if (held)
213
+ query.set('id_token_hint', held.idToken);
214
+ if (this.config.postLogoutRedirectUri)
215
+ query.set('post_logout_redirect_uri', this.config.postLogoutRedirectUri);
216
+ this.navigate(`${found.end_session_endpoint}?${query}`);
217
+ }
218
+ }
219
+ /** The person's account page at Aiveth (password, two-step, passkeys, connected accounts). */
220
+ accountUrl() {
221
+ return `${this.issuer}/console/account`;
222
+ }
223
+ /** Aiveth's page that ends acting as someone (its End button). */
224
+ actingUrl() {
225
+ return `${this.issuer}/act`;
226
+ }
227
+ }
@@ -0,0 +1,2 @@
1
+ export { AivethClient, RefusedError, SignInError, claimsOf, type Actor, type AivethConfig, type Returned, type User } from './client.js';
2
+ export { AivethProvider, useAiveth, SignedIn, SignedOut, SignInButton, SignOutButton, UserButton, ActingBanner, type AivethProviderProps, type UseAiveth } from './react.js';
package/dist/index.js ADDED
@@ -0,0 +1,2 @@
1
+ export { AivethClient, RefusedError, SignInError, claimsOf } from './client.js';
2
+ export { AivethProvider, useAiveth, SignedIn, SignedOut, SignInButton, SignOutButton, UserButton, ActingBanner } from './react.js';
@@ -0,0 +1,56 @@
1
+ import { type ReactNode } from 'react';
2
+ import { type Actor, type AivethConfig, type User } from './client.js';
3
+ export interface AivethProviderProps extends AivethConfig {
4
+ children: ReactNode;
5
+ /** After a return from Aiveth: where to go (your router's navigate), given `returnTo`. */
6
+ onSignedIn?: (returnTo: string | null) => void;
7
+ }
8
+ /** Put it around your app. On the return address it finishes the sign-in by itself. */
9
+ export declare function AivethProvider({ children, onSignedIn, ...config }: AivethProviderProps): import("react/jsx-runtime").JSX.Element;
10
+ export interface UseAiveth {
11
+ isLoaded: boolean;
12
+ isSignedIn: boolean;
13
+ user: User | null;
14
+ /** A sign-in that went wrong (Aiveth refused, or the round trip didn't start here). */
15
+ error: Error | null;
16
+ signIn: (options?: {
17
+ returnTo?: string;
18
+ }) => Promise<void>;
19
+ signOut: () => Promise<void>;
20
+ /** For your API calls: `Authorization: Bearer …`. Null when signed out. */
21
+ getAccessToken: () => Promise<string | null>;
22
+ accountUrl: string;
23
+ /** Someone acting as this person (support) — who and why; null otherwise. Block what a
24
+ * support person shouldn't do (payments, deleting data) while it is set. */
25
+ actor: Actor | null;
26
+ /** Is this feature flag on for the person? (Aiveth's feature flags, from the sign-in token.) */
27
+ hasFlag: (key: string) => boolean;
28
+ /** Aiveth's page that ends acting as someone. */
29
+ actingUrl: string;
30
+ }
31
+ export declare function useAiveth(): UseAiveth;
32
+ export declare function SignedIn({ children }: {
33
+ children: ReactNode;
34
+ }): import("react/jsx-runtime").JSX.Element | null;
35
+ export declare function SignedOut({ children }: {
36
+ children: ReactNode;
37
+ }): import("react/jsx-runtime").JSX.Element | null;
38
+ export declare function SignInButton({ children, returnTo, className }: {
39
+ children?: ReactNode;
40
+ returnTo?: string;
41
+ className?: string;
42
+ }): import("react/jsx-runtime").JSX.Element;
43
+ export declare function SignOutButton({ children, className }: {
44
+ children?: ReactNode;
45
+ className?: string;
46
+ }): import("react/jsx-runtime").JSX.Element;
47
+ /** The signed-in person's initials; opens their name and email, "Manage account" (at Aiveth)
48
+ * and "Sign out". Nothing when signed out. */
49
+ export declare function UserButton({ className }: {
50
+ className?: string;
51
+ }): import("react/jsx-runtime").JSX.Element | null;
52
+ /** A line across the top while a support person acts as this person ("Acting for others"):
53
+ * who, by whom, why — and End (Aiveth's page). Nothing otherwise. Put it at the top of your app. */
54
+ export declare function ActingBanner({ className }: {
55
+ className?: string;
56
+ }): import("react/jsx-runtime").JSX.Element | null;
package/dist/react.js ADDED
@@ -0,0 +1,102 @@
1
+ import { jsx as _jsx, Fragment as _Fragment, jsxs as _jsxs } from "react/jsx-runtime";
2
+ /* React on top of `AivethClient`: a provider, one hook, and the ready-made pieces Clerk, Auth0 and
3
+ * WorkOS give — <SignedIn>, <SignedOut>, <SignInButton>, <SignOutButton>, <UserButton>. Sign-in
4
+ * itself happens on Aiveth's page (RFC 8252). */
5
+ import { createContext, useCallback, useContext, useEffect, useMemo, useRef, useState, useSyncExternalStore } from 'react';
6
+ import { AivethClient } from './client.js';
7
+ const Context = createContext(null);
8
+ /** Put it around your app. On the return address it finishes the sign-in by itself. */
9
+ export function AivethProvider({ children, onSignedIn, ...config }) {
10
+ const client = useMemo(() => new AivethClient(config), [config.issuer, config.clientId, config.redirectUri]); // eslint-disable-line react-hooks/exhaustive-deps
11
+ const [isLoaded, setLoaded] = useState(false);
12
+ const [error, setError] = useState(null);
13
+ const done = useRef(false);
14
+ useEffect(() => {
15
+ if (done.current)
16
+ return; // React's strict mode runs effects twice: one code, one swap
17
+ done.current = true;
18
+ const clean = () => globalThis.history.replaceState(null, '', globalThis.location.pathname); // the code leaves the address bar
19
+ client.handleRedirect(globalThis.location.href)
20
+ .then(({ handled, returnTo }) => {
21
+ if (!handled)
22
+ return; // a ?code= of the app's own (an invite link) is left alone
23
+ globalThis.history.replaceState(null, '', returnTo ?? globalThis.location.pathname);
24
+ onSignedIn?.(returnTo);
25
+ })
26
+ .catch((e) => {
27
+ clean(); // a refused or forged return: its error and code leave the address bar too
28
+ setError(e instanceof Error ? e : new Error(String(e)));
29
+ })
30
+ .finally(() => setLoaded(true));
31
+ }, [client, onSignedIn]);
32
+ return _jsx(Context.Provider, { value: { client, isLoaded, error }, children: children });
33
+ }
34
+ function actorOf(user) {
35
+ const act = user?.act;
36
+ return act && typeof act === 'object' && typeof act.sub === 'string' ? act : null;
37
+ }
38
+ export function useAiveth() {
39
+ const ctx = useContext(Context);
40
+ if (!ctx)
41
+ throw new Error('useAiveth needs <AivethProvider> around your app.');
42
+ const { client } = ctx;
43
+ const user = useSyncExternalStore(useCallback((on) => client.subscribe(on), [client]), () => client.user);
44
+ return {
45
+ isLoaded: ctx.isLoaded, isSignedIn: user !== null, user, error: ctx.error,
46
+ signIn: (o) => client.signIn(o), signOut: () => client.signOut(),
47
+ getAccessToken: () => client.getAccessToken(), accountUrl: client.accountUrl(),
48
+ actor: actorOf(user), actingUrl: client.actingUrl(),
49
+ hasFlag: (key) => Array.isArray(user?.feature_flags) && user.feature_flags.includes(key),
50
+ };
51
+ }
52
+ export function SignedIn({ children }) {
53
+ const { isLoaded, isSignedIn } = useAiveth();
54
+ return isLoaded && isSignedIn ? _jsx(_Fragment, { children: children }) : null;
55
+ }
56
+ export function SignedOut({ children }) {
57
+ const { isLoaded, isSignedIn } = useAiveth();
58
+ return isLoaded && !isSignedIn ? _jsx(_Fragment, { children: children }) : null;
59
+ }
60
+ export function SignInButton({ children = 'Sign in', returnTo, className }) {
61
+ const { signIn } = useAiveth();
62
+ return _jsx("button", { type: "button", className: className, onClick: () => { void signIn({ returnTo }); }, children: children });
63
+ }
64
+ export function SignOutButton({ children = 'Sign out', className }) {
65
+ const { signOut } = useAiveth();
66
+ return _jsx("button", { type: "button", className: className, onClick: () => { void signOut(); }, children: children });
67
+ }
68
+ function initials(user) {
69
+ const name = (user.name ?? [user.given_name, user.family_name].filter(Boolean).join(' ')) || user.email || '?';
70
+ return name.split(/[\s@.]+/).filter(Boolean).slice(0, 2).map((w) => w[0]?.toUpperCase() ?? '').join('') || '?';
71
+ }
72
+ const S = {
73
+ wrap: { position: 'relative', display: 'inline-block', fontFamily: 'inherit' },
74
+ avatar: { width: 32, height: 32, borderRadius: '50%', border: '1px solid rgba(0,0,0,.15)', background: '#111', color: '#fff', fontSize: 13, fontWeight: 600, cursor: 'pointer' },
75
+ menu: { position: 'absolute', right: 0, top: 40, minWidth: 220, padding: 8, borderRadius: 10, background: '#fff', color: '#111', boxShadow: '0 8px 24px rgba(0,0,0,.15)', zIndex: 1000 },
76
+ who: { padding: '6px 8px 10px', borderBottom: '1px solid rgba(0,0,0,.08)', marginBottom: 6, fontSize: 13 },
77
+ item: { display: 'block', width: '100%', padding: '8px', border: 0, background: 'none', textAlign: 'left', color: 'inherit', textDecoration: 'none', fontSize: 14, borderRadius: 6, cursor: 'pointer' },
78
+ };
79
+ /** The signed-in person's initials; opens their name and email, "Manage account" (at Aiveth)
80
+ * and "Sign out". Nothing when signed out. */
81
+ export function UserButton({ className }) {
82
+ const { user, signOut, accountUrl } = useAiveth();
83
+ const [open, setOpen] = useState(false);
84
+ if (!user)
85
+ return null;
86
+ const name = user.name ?? [user.given_name, user.family_name].filter(Boolean).join(' ');
87
+ return (_jsxs("div", { style: S.wrap, className: className, children: [_jsx("button", { type: "button", style: S.avatar, "aria-haspopup": "menu", "aria-expanded": open, "aria-label": `Account menu for ${name || user.email || 'you'}`, onClick: () => setOpen((o) => !o), children: initials(user) }), open && (_jsxs("div", { role: "menu", style: S.menu, onKeyDown: (e) => { if (e.key === 'Escape')
88
+ setOpen(false); }, children: [_jsxs("div", { style: S.who, children: [name && _jsx("div", { style: { fontWeight: 600 }, children: name }), user.email && _jsx("div", { style: { opacity: 0.7 }, children: user.email })] }), _jsx("a", { role: "menuitem", style: S.item, href: accountUrl, target: "_blank", rel: "noreferrer", children: "Manage account" }), _jsx("button", { role: "menuitem", type: "button", style: S.item, onClick: () => { void signOut(); }, children: "Sign out" })] }))] }));
89
+ }
90
+ const BANNER = {
91
+ bar: { display: 'flex', alignItems: 'center', gap: 12, padding: '8px 16px', background: '#FEF3C7', color: '#78350F', fontSize: 14, borderBottom: '1px solid #FCD34D' },
92
+ end: { marginLeft: 'auto', padding: '4px 12px', borderRadius: 6, border: '1px solid #B45309', color: '#78350F', textDecoration: 'none', fontWeight: 500 },
93
+ };
94
+ /** A line across the top while a support person acts as this person ("Acting for others"):
95
+ * who, by whom, why — and End (Aiveth's page). Nothing otherwise. Put it at the top of your app. */
96
+ export function ActingBanner({ className }) {
97
+ const { user, actor, actingUrl } = useAiveth();
98
+ if (!user || !actor)
99
+ return null;
100
+ const name = user.name ?? user.email ?? 'this person';
101
+ 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" })] }));
102
+ }
package/package.json CHANGED
@@ -1,6 +1,55 @@
1
1
  {
2
2
  "name": "@aiveth/react",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "Aiveth by Gooclaim for React: sign in on Aiveth's page (PKCE), tokens in memory, ready-made pieces.",
5
+ "license": "Apache-2.0",
6
+ "author": "Gooclaim",
7
+ "keywords": [
8
+ "aiveth",
9
+ "gooclaim",
10
+ "react",
11
+ "auth",
12
+ "authentication",
13
+ "oidc",
14
+ "pkce",
15
+ "sso"
16
+ ],
17
+ "type": "module",
18
+ "main": "./dist/index.js",
19
+ "types": "./dist/index.d.ts",
20
+ "exports": {
21
+ ".": {
22
+ "types": "./dist/index.d.ts",
23
+ "import": "./dist/index.js"
24
+ }
25
+ },
26
+ "files": [
27
+ "dist",
28
+ "LICENSE",
29
+ "README.md",
30
+ "CHANGELOG.md"
31
+ ],
32
+ "sideEffects": false,
33
+ "publishConfig": {
34
+ "access": "public"
35
+ },
36
+ "scripts": {
37
+ "build": "tsc -p tsconfig.build.json",
38
+ "typecheck": "tsc -p tsconfig.json --noEmit",
39
+ "test": "vitest run",
40
+ "prepublishOnly": "npm run typecheck && npm test && npm run build"
41
+ },
42
+ "peerDependencies": {
43
+ "react": ">=18"
44
+ },
45
+ "devDependencies": {
46
+ "@testing-library/react": "16.1.0",
47
+ "@types/react": "18.3.12",
48
+ "@types/react-dom": "18.3.1",
49
+ "jsdom": "25.0.1",
50
+ "react": "18.3.1",
51
+ "react-dom": "18.3.1",
52
+ "typescript": "5.6.3",
53
+ "vitest": "2.1.8"
54
+ }
55
+ }