@segmentstream-cloud/app 0.3.1 → 0.3.2

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/README.md CHANGED
@@ -56,11 +56,12 @@ export const { GET, POST, PUT, DELETE, PATCH } = segmentstream.authHandlers();
56
56
  The route completes emailed sign-in links (`/api/auth/magic-link/verify`) itself: it
57
57
  verifies the token through Neon Auth without a callback, sets the session cookies on
58
58
  the app's domain and redirects to the link's `callbackURL` path. An expired, used or
59
- unknown link redirects to `/sign-in?error=sign_in_link_invalid`, where `<SignIn />`
60
- offers a new code.
59
+ unknown link redirects to `/sign-in?error=sign_in_link_invalid`, where `<SignIn />` (or
60
+ `useSignIn().linkInvalid`) offers a new code.
61
61
 
62
62
  **`src/app/sign-in/page.tsx`** renders the sign-in form, and the root layout imports
63
- its stylesheet once:
63
+ its stylesheet once. Apps with their own design system render their own form on
64
+ [`useSignIn()`](#your-own-sign-in-form) instead and skip the stylesheet:
64
65
 
65
66
  ```tsx
66
67
  import { SignIn } from "@segmentstream-cloud/app/ui";
@@ -127,6 +128,7 @@ user in Server Functions and Route Handlers too; do not rely on the proxy alone.
127
128
  | Export | Does |
128
129
  | -------------------------------------- | ---------------------------------------------------------------------------------- |
129
130
  | `<SignIn />` | Email, then the six-digit code; resend after 30 seconds, errors and loading states |
131
+ | `useSignIn()` | The same sign-in without markup, for the app's own form |
130
132
  | `<SignedIn>`, `<SignedOut>` | Render children by session state |
131
133
  | `<Can permission="lead:changeStatus">` | Renders children when the user holds the permission; `fallback` otherwise |
132
134
  | `<UserMenu />` | Name, email, roles and sign-out |
@@ -143,6 +145,85 @@ Server Component may wrap server-rendered children in `<Can>`:
143
145
  </Can>
144
146
  ```
145
147
 
148
+ ### Your own sign-in form
149
+
150
+ `useSignIn({ returnTo, error })` holds everything `<SignIn />` does, without markup: the
151
+ steps, the 30-second resend hold, the six-digit check, error sentences, the return to
152
+ `returnTo` after sign-in and the `not_invited` and `sign_in_link_invalid` states. Both
153
+ options default to the page's query parameters. The workspace starter renders it with
154
+ Tailwind CSS and shadcn/ui in `src/components/sign-in-form.tsx`; `<SignIn />` stays for
155
+ apps without Tailwind.
156
+
157
+ ```tsx
158
+ "use client";
159
+
160
+ import { useSignIn } from "@segmentstream-cloud/app/ui";
161
+
162
+ export function SignInForm() {
163
+ const signIn = useSignIn();
164
+
165
+ if (signIn.step === "email") {
166
+ return (
167
+ <form
168
+ noValidate
169
+ onSubmit={(event) => {
170
+ event.preventDefault();
171
+ void signIn.submitEmail();
172
+ }}
173
+ >
174
+ <input
175
+ type="email"
176
+ value={signIn.email}
177
+ onChange={(event) => signIn.setEmail(event.target.value)}
178
+ />
179
+ {signIn.error !== null && <p role="alert">{signIn.error}</p>}
180
+ <button disabled={signIn.pending !== null}>Send code</button>
181
+ </form>
182
+ );
183
+ }
184
+
185
+ return (
186
+ <form
187
+ noValidate
188
+ onSubmit={(event) => {
189
+ event.preventDefault();
190
+ void signIn.submitCode();
191
+ }}
192
+ >
193
+ <input
194
+ inputMode="numeric"
195
+ autoComplete="one-time-code"
196
+ value={signIn.code}
197
+ onChange={(event) => signIn.setCode(event.target.value)}
198
+ />
199
+ {signIn.error !== null && <p role="alert">{signIn.error}</p>}
200
+ <button disabled={signIn.pending !== null}>Sign in</button>
201
+ <button type="button" onClick={() => void signIn.resend()} disabled={signIn.resendIn > 0}>
202
+ Resend code
203
+ </button>
204
+ </form>
205
+ );
206
+ }
207
+ ```
208
+
209
+ | Field | Means |
210
+ | -------------------------------------- | -------------------------------------------------------------------------------------- |
211
+ | `step` | `email`, then `code` once a code is sent |
212
+ | `email`, `setEmail`, `code`, `setCode` | The field values; `submitEmail()` trims the address |
213
+ | `pending` | `send`, `verify`, `resend` or `sign-out` while a call runs; disable the form |
214
+ | `error`, `notice` | A sentence for the person, and a confirmation such as a resent code |
215
+ | `resendIn` | Seconds until `resend()` may be offered; 0 when it may |
216
+ | `submitEmail()`, `submitCode(value?)` | Send the code; verify `value` or `code`. A wrong code clears `code`; refocus the field |
217
+ | `resend()`, `changeEmail()` | Another code to the same address; back to the email step |
218
+ | `signedIn`, `destination` | A session already exists: offer a link to `destination` |
219
+ | `notInvited`, `sessionEmail` | The person is signed in as `sessionEmail` without an invitation |
220
+ | `switchAccount()` | Signs out and returns to the email step |
221
+ | `linkInvalid` | An emailed sign-in link was expired or used: say so on the email step |
222
+
223
+ The calls take values, not form events: call `submitEmail()` and `submitCode()` from the
224
+ form's submit handler after `event.preventDefault()`. A second `submitCode()` while one
225
+ runs is ignored, so the last digit and the Enter key may both submit.
226
+
146
227
  ## The ontology
147
228
 
148
229
  `segmentstream.ontology.<entity>` calls the app's ontology service at `/api/ontology`
@@ -2,8 +2,10 @@ export { Can, SignedIn, SignedOut, UserMenu, signOut } from "./components.js";
2
2
  export type { CanProps, ChildrenProps, UserMenuProps } from "./components.js";
3
3
  export { usePermissions, useSession, useUser } from "./hooks.js";
4
4
  export type { Permissions } from "./hooks.js";
5
- export { SignIn, signInErrorMessage } from "./sign-in.js";
5
+ export { SignIn } from "./sign-in.js";
6
6
  export type { SignInProps } from "./sign-in.js";
7
+ export { signInErrorMessage, useSignIn } from "./use-sign-in.js";
8
+ export type { SignInController, SignInOptions } from "./use-sign-in.js";
7
9
  export type { SessionState, SessionUser, UserState } from "./store.js";
8
10
  export { isAllowed } from "../permissions.js";
9
11
  export type { CurrentUser } from "../me.js";
package/dist/ui/index.js CHANGED
@@ -1,8 +1,10 @@
1
1
  "use client";
2
2
  // Client components for apps that sign in with Neon Auth. Import the stylesheet once, in the root
3
- // layout: `import "@segmentstream-cloud/app/ui/styles.css";`.
3
+ // layout, when rendering the components: `import "@segmentstream-cloud/app/ui/styles.css";`. The
4
+ // hooks, `useSignIn()` among them, need no stylesheet.
4
5
  export { Can, SignedIn, SignedOut, UserMenu, signOut } from "./components.js";
5
6
  export { usePermissions, useSession, useUser } from "./hooks.js";
6
- export { SignIn, signInErrorMessage } from "./sign-in.js";
7
+ export { SignIn } from "./sign-in.js";
8
+ export { signInErrorMessage, useSignIn } from "./use-sign-in.js";
7
9
  export { isAllowed } from "../permissions.js";
8
10
  export { SegmentStreamApiError, NOT_INVITED, SIGN_IN_LINK_INVALID } from "../errors.js";
@@ -1,20 +1,10 @@
1
- export interface SignInProps {
2
- /** Where to go once signed in. Defaults to the page's `returnTo` parameter, then `/`. */
3
- readonly returnTo?: string;
4
- /**
5
- * Why the page was opened: `not_invited` when `requireUser()` found no invitation,
6
- * `sign_in_link_invalid` when an emailed sign-in link was expired, used or unknown. Defaults to
7
- * the page's `error` parameter.
8
- */
9
- readonly error?: string;
1
+ import type { SignInOptions } from "./use-sign-in.js";
2
+ export interface SignInProps extends SignInOptions {
10
3
  /** The heading. Defaults to "Sign in". */
11
4
  readonly title?: string;
12
5
  }
13
6
  /**
14
- * Email code sign-in with Neon Auth: the email address, then the six-digit code sent to it. New
15
- * addresses get an account on first sign-in; whether they may use the app is the ontology's
16
- * decision, which `requireUser()` reports as `not_invited`.
7
+ * Email code sign-in with Neon Auth in the SDK's neutral styles: `useSignIn()` with markup. Apps
8
+ * with their own design system render `useSignIn()` themselves.
17
9
  */
18
- export declare function SignIn({ returnTo, error: reason, title }: SignInProps): import("react").JSX.Element;
19
- /** A sentence for a Neon Auth (Better Auth) failure. */
20
- export declare function signInErrorMessage(error: unknown): string;
10
+ export declare function SignIn({ title, ...options }: SignInProps): import("react").JSX.Element;
@@ -1,158 +1,42 @@
1
1
  "use client";
2
2
  import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
3
- import { useEffect, useId, useRef, useState, useSyncExternalStore } from "react";
4
- import { SIGN_IN_LINK_INVALID } from "../errors.js";
5
- import { safeReturnTo } from "../return-to.js";
6
- import { useSession } from "./hooks.js";
7
- import { navigate } from "./navigation.js";
8
- import { NOT_INVITED, authClient, clearSession, refreshSession } from "./store.js";
9
- /** Seconds before another code may be requested. */
10
- const RESEND_AFTER_SECONDS = 30;
11
- const CODE_LENGTH = 6;
12
- const noSubscription = () => () => { };
13
- /** The page's own query string; empty during server rendering. */
14
- function useSearchParameter(name) {
15
- const search = useSyncExternalStore(noSubscription, () => window.location.search, () => "");
16
- return new URLSearchParams(search).get(name);
17
- }
3
+ import { useEffect, useId, useRef } from "react";
4
+ import { useSignIn } from "./use-sign-in.js";
18
5
  /**
19
- * Email code sign-in with Neon Auth: the email address, then the six-digit code sent to it. New
20
- * addresses get an account on first sign-in; whether they may use the app is the ontology's
21
- * decision, which `requireUser()` reports as `not_invited`.
6
+ * Email code sign-in with Neon Auth in the SDK's neutral styles: `useSignIn()` with markup. Apps
7
+ * with their own design system render `useSignIn()` themselves.
22
8
  */
23
- export function SignIn({ returnTo, error: reason, title = "Sign in" }) {
9
+ export function SignIn({ title = "Sign in", ...options }) {
24
10
  const ids = useId();
25
- const session = useSession();
26
- const pageReturnTo = useSearchParameter("returnTo");
27
- const pageError = useSearchParameter("error");
28
- const [step, setStep] = useState("email");
29
- const [email, setEmail] = useState("");
30
- const [code, setCode] = useState("");
31
- const [pending, setPending] = useState(null);
32
- const [error, setError] = useState(null);
33
- const [notice, setNotice] = useState(null);
34
- /** Seconds until another code may be requested. */
35
- const [resendIn, setResendIn] = useState(0);
36
- const [switchingAccount, setSwitchingAccount] = useState(false);
11
+ const { step, email, setEmail, code, setCode, pending, error, notice, resendIn, codeLength, destination, signedIn, notInvited, linkInvalid, sessionEmail, submitEmail, submitCode, resend, changeEmail, switchAccount, } = useSignIn(options);
37
12
  const codeInput = useRef(null);
38
- const verifying = useRef(false);
39
- const resendTimer = useRef(undefined);
40
- const destination = safeReturnTo(returnTo ?? pageReturnTo);
41
- const notInvited = (reason ?? pageError) === NOT_INVITED && !switchingAccount;
42
- const linkInvalid = (reason ?? pageError) === SIGN_IN_LINK_INVALID;
43
- useEffect(() => () => clearInterval(resendTimer.current), []);
13
+ // The code field takes focus when it appears and again after a wrong code.
44
14
  useEffect(() => {
45
- if (step === "code") {
15
+ if (step === "code" && pending === null) {
46
16
  codeInput.current?.focus();
47
17
  }
48
- }, [step]);
49
- function holdResend() {
50
- const deadline = Date.now() + RESEND_AFTER_SECONDS * 1000;
51
- clearInterval(resendTimer.current);
52
- setResendIn(RESEND_AFTER_SECONDS);
53
- resendTimer.current = setInterval(() => {
54
- const remaining = Math.max(0, Math.ceil((deadline - Date.now()) / 1000));
55
- setResendIn(remaining);
56
- if (remaining === 0) {
57
- clearInterval(resendTimer.current);
58
- }
59
- }, 1000);
60
- }
61
- async function sendCode(address) {
62
- const result = await attempt(() => authClient().emailOtp.sendVerificationOtp({ email: address, type: "sign-in" }));
63
- if (result !== null) {
64
- setError(signInErrorMessage(result));
65
- return false;
66
- }
67
- holdResend();
68
- return true;
69
- }
70
- async function submitEmail(event) {
71
- event.preventDefault();
72
- const address = email.trim();
73
- if (address === "") {
74
- setError("Enter your email address.");
75
- return;
76
- }
77
- setPending("send");
78
- setError(null);
79
- setNotice(null);
80
- if (await sendCode(address)) {
81
- setEmail(address);
82
- setCode("");
83
- setStep("code");
84
- }
85
- setPending(null);
86
- }
87
- async function verify(value) {
88
- // The sixth digit and the Enter key may both submit the same code.
89
- if (verifying.current) {
90
- return;
91
- }
92
- if (!new RegExp(`^[0-9]{${CODE_LENGTH}}$`).test(value)) {
93
- setError(`Enter the ${CODE_LENGTH}-digit code from the email.`);
94
- return;
95
- }
96
- verifying.current = true;
97
- setPending("verify");
98
- setError(null);
99
- setNotice(null);
100
- const result = await attempt(() => authClient().signIn.emailOtp({ email, otp: value }));
101
- if (result !== null) {
102
- verifying.current = false;
103
- setError(signInErrorMessage(result));
104
- setCode("");
105
- setPending(null);
106
- codeInput.current?.focus();
107
- return;
108
- }
109
- navigate(destination);
110
- }
111
- async function resend() {
112
- setPending("resend");
113
- setError(null);
114
- setNotice(null);
115
- if (await sendCode(email)) {
116
- setCode("");
117
- setNotice(`We sent a new code to ${email}.`);
118
- }
119
- setPending(null);
120
- }
121
- function changeEmail() {
122
- setStep("email");
123
- setCode("");
124
- setError(null);
125
- setNotice(null);
126
- }
127
- async function switchAccount() {
128
- setPending("sign-out");
129
- setError(null);
130
- await attempt(() => authClient().signOut());
131
- clearSession();
132
- await refreshSession();
133
- setSwitchingAccount(true);
134
- setStep("email");
135
- setPending(null);
136
- }
18
+ }, [step, pending]);
137
19
  const errorId = `${ids}-error`;
138
- const sessionEmail = session.status === "signed-in" ? (session.user.email ?? session.user.name) : null;
139
20
  if (notInvited) {
140
21
  return (_jsxs("section", { className: "ss-card ss-sign-in", "aria-labelledby": `${ids}-title`, children: [_jsx("h1", { id: `${ids}-title`, className: "ss-title", children: "Ask for an invitation" }), _jsxs("p", { className: "ss-text", children: [sessionEmail === null ? "You are signed in" : `You are signed in as ${sessionEmail}`, ", but this app has not invited you. Ask your administrator for an invitation, or sign in with another email address."] }), error !== null && (_jsx("p", { id: errorId, className: "ss-error", role: "alert", children: error })), _jsx("button", { type: "button", className: "ss-button", onClick: () => void switchAccount(), disabled: pending !== null, "aria-busy": pending === "sign-out", children: pending === "sign-out" ? "Signing out…" : "Use another email" })] }));
141
22
  }
142
- if (session.status === "signed-in" && step === "email" && pending === null && !switchingAccount) {
23
+ if (signedIn && step === "email" && pending === null) {
143
24
  return (_jsxs("section", { className: "ss-card ss-sign-in", "aria-labelledby": `${ids}-title`, children: [_jsx("h1", { id: `${ids}-title`, className: "ss-title", children: "You are signed in" }), _jsx("p", { className: "ss-text", children: sessionEmail === null ? "You already have a session." : `Signed in as ${sessionEmail}.` }), _jsxs("div", { className: "ss-actions", children: [_jsx("a", { className: "ss-button", href: destination, children: "Continue" }), _jsx("button", { type: "button", className: "ss-button ss-button--secondary", onClick: () => void switchAccount(), children: "Use another email" })] })] }));
144
25
  }
145
26
  if (step === "email") {
146
- return (_jsxs("section", { className: "ss-card ss-sign-in", "aria-labelledby": `${ids}-title`, children: [_jsx("h1", { id: `${ids}-title`, className: "ss-title", children: title }), _jsxs("p", { className: "ss-text", children: ["We will email you a ", CODE_LENGTH, "-digit code to sign in."] }), _jsxs("form", { className: "ss-form", onSubmit: (event) => void submitEmail(event), noValidate: true, children: [linkInvalid && (_jsx("p", { className: "ss-notice", role: "status", children: "This sign-in link is not valid anymore. Enter your email to get a new code." })), _jsxs("div", { className: "ss-field", children: [_jsx("label", { className: "ss-label", htmlFor: `${ids}-email`, children: "Email" }), _jsx("input", { id: `${ids}-email`, className: "ss-input", type: "email", name: "email", autoComplete: "email", inputMode: "email", required: true, value: email, onChange: (event) => setEmail(event.target.value), disabled: pending !== null, "aria-invalid": error !== null, "aria-describedby": error === null ? undefined : errorId })] }), error !== null && (_jsx("p", { id: errorId, className: "ss-error", role: "alert", children: error })), _jsx("button", { type: "submit", className: "ss-button", disabled: pending !== null, "aria-busy": pending === "send", children: pending === "send" ? "Sending code…" : "Send code" })] })] }));
27
+ return (_jsxs("section", { className: "ss-card ss-sign-in", "aria-labelledby": `${ids}-title`, children: [_jsx("h1", { id: `${ids}-title`, className: "ss-title", children: title }), _jsxs("p", { className: "ss-text", children: ["We will email you a ", codeLength, "-digit code to sign in."] }), _jsxs("form", { className: "ss-form", onSubmit: (event) => {
28
+ event.preventDefault();
29
+ void submitEmail();
30
+ }, noValidate: true, children: [linkInvalid && (_jsx("p", { className: "ss-notice", role: "status", children: "This sign-in link is not valid anymore. Enter your email to get a new code." })), _jsxs("div", { className: "ss-field", children: [_jsx("label", { className: "ss-label", htmlFor: `${ids}-email`, children: "Email" }), _jsx("input", { id: `${ids}-email`, className: "ss-input", type: "email", name: "email", autoComplete: "email", inputMode: "email", required: true, value: email, onChange: (event) => setEmail(event.target.value), disabled: pending !== null, "aria-invalid": error !== null, "aria-describedby": error === null ? undefined : errorId })] }), error !== null && (_jsx("p", { id: errorId, className: "ss-error", role: "alert", children: error })), _jsx("button", { type: "submit", className: "ss-button", disabled: pending !== null, "aria-busy": pending === "send", children: pending === "send" ? "Sending code…" : "Send code" })] })] }));
147
31
  }
148
- return (_jsxs("section", { className: "ss-card ss-sign-in", "aria-labelledby": `${ids}-title`, children: [_jsx("h1", { id: `${ids}-title`, className: "ss-title", children: "Check your email" }), _jsxs("p", { className: "ss-text", children: ["Enter the ", CODE_LENGTH, "-digit code we sent to ", _jsx("strong", { children: email }), "."] }), _jsxs("form", { className: "ss-form", onSubmit: (event) => {
32
+ return (_jsxs("section", { className: "ss-card ss-sign-in", "aria-labelledby": `${ids}-title`, children: [_jsx("h1", { id: `${ids}-title`, className: "ss-title", children: "Check your email" }), _jsxs("p", { className: "ss-text", children: ["Enter the ", codeLength, "-digit code we sent to ", _jsx("strong", { children: email }), "."] }), _jsxs("form", { className: "ss-form", onSubmit: (event) => {
149
33
  event.preventDefault();
150
- void verify(code);
151
- }, noValidate: true, children: [_jsxs("div", { className: "ss-field", children: [_jsx("label", { className: "ss-label", htmlFor: `${ids}-code`, children: "Code" }), _jsx("input", { ref: codeInput, id: `${ids}-code`, className: "ss-input ss-input--code", type: "text", name: "code", inputMode: "numeric", autoComplete: "one-time-code", pattern: "[0-9]*", maxLength: CODE_LENGTH, required: true, value: code, onChange: (event) => {
152
- const digits = event.target.value.replace(/\D/g, "").slice(0, CODE_LENGTH);
34
+ void submitCode();
35
+ }, noValidate: true, children: [_jsxs("div", { className: "ss-field", children: [_jsx("label", { className: "ss-label", htmlFor: `${ids}-code`, children: "Code" }), _jsx("input", { ref: codeInput, id: `${ids}-code`, className: "ss-input ss-input--code", type: "text", name: "code", inputMode: "numeric", autoComplete: "one-time-code", pattern: "[0-9]*", maxLength: codeLength, required: true, value: code, onChange: (event) => {
36
+ const digits = event.target.value.replace(/\D/g, "").slice(0, codeLength);
153
37
  setCode(digits);
154
- if (digits.length === CODE_LENGTH) {
155
- void verify(digits);
38
+ if (digits.length === codeLength) {
39
+ void submitCode(digits);
156
40
  }
157
41
  }, disabled: pending === "verify", "aria-invalid": error !== null, "aria-describedby": error === null ? undefined : errorId })] }), error !== null && (_jsx("p", { id: errorId, className: "ss-error", role: "alert", children: error })), notice !== null && (_jsx("p", { className: "ss-notice", role: "status", children: notice })), _jsx("button", { type: "submit", className: "ss-button", disabled: pending !== null, "aria-busy": pending === "verify", children: pending === "verify" ? "Signing in…" : "Sign in" })] }), _jsxs("div", { className: "ss-actions", children: [_jsx("button", { type: "button", className: "ss-link", onClick: () => void resend(), disabled: pending !== null || resendIn > 0, "aria-busy": pending === "resend", children: pending === "resend"
158
42
  ? "Sending…"
@@ -160,41 +44,3 @@ export function SignIn({ returnTo, error: reason, title = "Sign in" }) {
160
44
  ? `Resend code in ${resendIn} s`
161
45
  : "Resend code" }), _jsx("button", { type: "button", className: "ss-link", onClick: changeEmail, disabled: pending !== null, children: "Use another email" })] })] }));
162
46
  }
163
- /** Runs a Neon Auth client call; its failure, returned or thrown, or `null` on success. */
164
- async function attempt(call) {
165
- try {
166
- const result = await call();
167
- return result.error ?? null;
168
- }
169
- catch (error) {
170
- return error ?? new Error("Sign-in failed.");
171
- }
172
- }
173
- /** A sentence for a Neon Auth (Better Auth) failure. */
174
- export function signInErrorMessage(error) {
175
- const details = typeof error === "object" && error !== null ? error : {};
176
- const status = typeof details.status === "number" ? details.status : undefined;
177
- const text = [details.code, details.message]
178
- .filter((part) => typeof part === "string")
179
- .join(" ")
180
- .toLowerCase();
181
- if (status === 429 || text.includes("rate limit") || text.includes("too many requests")) {
182
- return "Too many requests. Wait a minute, then try again.";
183
- }
184
- if (text.includes("too many attempts") || text.includes("too_many_attempts")) {
185
- return "Too many wrong codes. Send a new code.";
186
- }
187
- if (text.includes("expired")) {
188
- return "That code has expired. Send a new one.";
189
- }
190
- if (text.includes("otp") || text.includes("code")) {
191
- return "That code is not right. Check the email and try again.";
192
- }
193
- if (text.includes("email")) {
194
- return "Enter a valid email address.";
195
- }
196
- if (status === undefined || status >= 500 || text.includes("network")) {
197
- return "Sign-in is unavailable right now. Try again in a moment.";
198
- }
199
- return "Sign-in failed. Try again.";
200
- }
@@ -0,0 +1,63 @@
1
+ export interface SignInOptions {
2
+ /** Where to go once signed in. Defaults to the page's `returnTo` parameter, then `/`. */
3
+ readonly returnTo?: string;
4
+ /**
5
+ * Why the page was opened: `not_invited` when `requireUser()` found no invitation,
6
+ * `sign_in_link_invalid` when an emailed sign-in link was expired, used or unknown. Defaults to
7
+ * the page's `error` parameter.
8
+ */
9
+ readonly error?: string;
10
+ }
11
+ /** Email code sign-in for a form the app renders itself. The calls take values, not form events. */
12
+ export interface SignInController {
13
+ readonly step: "email" | "code";
14
+ readonly email: string;
15
+ readonly setEmail: (value: string) => void;
16
+ readonly code: string;
17
+ readonly setCode: (value: string) => void;
18
+ /** The call in flight; disable the form while it is not `null`. */
19
+ readonly pending: "send" | "verify" | "resend" | "sign-out" | null;
20
+ /** A sentence for the person, from the last failed call. */
21
+ readonly error: string | null;
22
+ /** A confirmation, such as a new code having been sent. */
23
+ readonly notice: string | null;
24
+ /** Seconds until another code may be requested; 0 when it may. */
25
+ readonly resendIn: number;
26
+ /** Digits in a code: 6. */
27
+ readonly codeLength: number;
28
+ /** The same-origin path the person returns to after signing in. */
29
+ readonly destination: string;
30
+ /**
31
+ * A session exists in this browser and the person has not chosen another account: offer to
32
+ * continue to `destination` instead of the email step.
33
+ */
34
+ readonly signedIn: boolean;
35
+ /** The page was opened for a signed-in person the app has not invited. */
36
+ readonly notInvited: boolean;
37
+ /** The emailed sign-in link was expired, used or unknown: say so on the email step. */
38
+ readonly linkInvalid: boolean;
39
+ /** The signed-in address or name, for the not-invited state; null when signed out. */
40
+ readonly sessionEmail: string | null;
41
+ /** Sends a code to `email` and moves to the code step. Call it from the form's submit handler. */
42
+ readonly submitEmail: () => Promise<void>;
43
+ /**
44
+ * Verifies `value`, or the current `code`, and opens `destination`. A wrong code clears `code`;
45
+ * a second call while one is verifying is ignored, so the last digit and Enter may both submit.
46
+ */
47
+ readonly submitCode: (value?: string) => Promise<void>;
48
+ /** Sends another code to the same address. */
49
+ readonly resend: () => Promise<void>;
50
+ /** Returns to the email step. */
51
+ readonly changeEmail: () => void;
52
+ /** Signs the current session out and returns to the email step. */
53
+ readonly switchAccount: () => Promise<void>;
54
+ }
55
+ /**
56
+ * Email code sign-in with Neon Auth, without markup: the email address, then the six-digit code
57
+ * sent to it. New addresses get an account on first sign-in; whether they may use the app is the
58
+ * ontology's decision, which `requireUser()` reports as `not_invited`. `<SignIn />` renders it with
59
+ * the SDK's own styles; apps with their own design system render the controller themselves.
60
+ */
61
+ export declare function useSignIn({ returnTo, error: reason }?: SignInOptions): SignInController;
62
+ /** A sentence for a Neon Auth (Better Auth) failure. */
63
+ export declare function signInErrorMessage(error: unknown): string;
@@ -0,0 +1,186 @@
1
+ "use client";
2
+ import { useEffect, useRef, useState, useSyncExternalStore } from "react";
3
+ import { NOT_INVITED, SIGN_IN_LINK_INVALID } from "../errors.js";
4
+ import { safeReturnTo } from "../return-to.js";
5
+ import { useSession } from "./hooks.js";
6
+ import { navigate } from "./navigation.js";
7
+ import { authClient, clearSession, refreshSession } from "./store.js";
8
+ /** Seconds before another code may be requested. */
9
+ const RESEND_AFTER_SECONDS = 30;
10
+ const CODE_LENGTH = 6;
11
+ const noSubscription = () => () => { };
12
+ /** The page's own query string; empty during server rendering. */
13
+ function useSearchParameter(name) {
14
+ const search = useSyncExternalStore(noSubscription, () => window.location.search, () => "");
15
+ return new URLSearchParams(search).get(name);
16
+ }
17
+ /**
18
+ * Email code sign-in with Neon Auth, without markup: the email address, then the six-digit code
19
+ * sent to it. New addresses get an account on first sign-in; whether they may use the app is the
20
+ * ontology's decision, which `requireUser()` reports as `not_invited`. `<SignIn />` renders it with
21
+ * the SDK's own styles; apps with their own design system render the controller themselves.
22
+ */
23
+ export function useSignIn({ returnTo, error: reason } = {}) {
24
+ const session = useSession();
25
+ const pageReturnTo = useSearchParameter("returnTo");
26
+ const pageError = useSearchParameter("error");
27
+ const [step, setStep] = useState("email");
28
+ const [email, setEmail] = useState("");
29
+ const [code, setCode] = useState("");
30
+ const [pending, setPending] = useState(null);
31
+ const [error, setError] = useState(null);
32
+ const [notice, setNotice] = useState(null);
33
+ const [resendIn, setResendIn] = useState(0);
34
+ const [switchingAccount, setSwitchingAccount] = useState(false);
35
+ const verifying = useRef(false);
36
+ const resendTimer = useRef(undefined);
37
+ const destination = safeReturnTo(returnTo ?? pageReturnTo);
38
+ const why = reason ?? pageError;
39
+ useEffect(() => () => clearInterval(resendTimer.current), []);
40
+ function holdResend() {
41
+ const deadline = Date.now() + RESEND_AFTER_SECONDS * 1000;
42
+ clearInterval(resendTimer.current);
43
+ setResendIn(RESEND_AFTER_SECONDS);
44
+ resendTimer.current = setInterval(() => {
45
+ const remaining = Math.max(0, Math.ceil((deadline - Date.now()) / 1000));
46
+ setResendIn(remaining);
47
+ if (remaining === 0) {
48
+ clearInterval(resendTimer.current);
49
+ }
50
+ }, 1000);
51
+ }
52
+ async function sendCode(address) {
53
+ const result = await attempt(() => authClient().emailOtp.sendVerificationOtp({ email: address, type: "sign-in" }));
54
+ if (result !== null) {
55
+ setError(signInErrorMessage(result));
56
+ return false;
57
+ }
58
+ holdResend();
59
+ return true;
60
+ }
61
+ async function submitEmail() {
62
+ const address = email.trim();
63
+ if (address === "") {
64
+ setError("Enter your email address.");
65
+ return;
66
+ }
67
+ setPending("send");
68
+ setError(null);
69
+ setNotice(null);
70
+ if (await sendCode(address)) {
71
+ setEmail(address);
72
+ setCode("");
73
+ setStep("code");
74
+ }
75
+ setPending(null);
76
+ }
77
+ async function submitCode(value = code) {
78
+ // The last digit and the Enter key may both submit the same code.
79
+ if (verifying.current) {
80
+ return;
81
+ }
82
+ if (!new RegExp(`^[0-9]{${CODE_LENGTH}}$`).test(value)) {
83
+ setError(`Enter the ${CODE_LENGTH}-digit code from the email.`);
84
+ return;
85
+ }
86
+ verifying.current = true;
87
+ setPending("verify");
88
+ setError(null);
89
+ setNotice(null);
90
+ const result = await attempt(() => authClient().signIn.emailOtp({ email, otp: value }));
91
+ if (result !== null) {
92
+ verifying.current = false;
93
+ setError(signInErrorMessage(result));
94
+ setCode("");
95
+ setPending(null);
96
+ return;
97
+ }
98
+ navigate(destination);
99
+ }
100
+ async function resend() {
101
+ setPending("resend");
102
+ setError(null);
103
+ setNotice(null);
104
+ if (await sendCode(email)) {
105
+ setCode("");
106
+ setNotice(`We sent a new code to ${email}.`);
107
+ }
108
+ setPending(null);
109
+ }
110
+ function changeEmail() {
111
+ setStep("email");
112
+ setCode("");
113
+ setError(null);
114
+ setNotice(null);
115
+ }
116
+ async function switchAccount() {
117
+ setPending("sign-out");
118
+ setError(null);
119
+ await attempt(() => authClient().signOut());
120
+ clearSession();
121
+ await refreshSession();
122
+ setSwitchingAccount(true);
123
+ setStep("email");
124
+ setPending(null);
125
+ }
126
+ return {
127
+ step,
128
+ email,
129
+ setEmail,
130
+ code,
131
+ setCode,
132
+ pending,
133
+ error,
134
+ notice,
135
+ resendIn,
136
+ codeLength: CODE_LENGTH,
137
+ destination,
138
+ signedIn: session.status === "signed-in" && !switchingAccount,
139
+ notInvited: why === NOT_INVITED && !switchingAccount,
140
+ linkInvalid: why === SIGN_IN_LINK_INVALID,
141
+ sessionEmail: session.status === "signed-in" ? (session.user.email ?? session.user.name) : null,
142
+ submitEmail,
143
+ submitCode,
144
+ resend,
145
+ changeEmail,
146
+ switchAccount,
147
+ };
148
+ }
149
+ /** Runs a Neon Auth client call; its failure, returned or thrown, or `null` on success. */
150
+ async function attempt(call) {
151
+ try {
152
+ const result = await call();
153
+ return result.error ?? null;
154
+ }
155
+ catch (error) {
156
+ return error ?? new Error("Sign-in failed.");
157
+ }
158
+ }
159
+ /** A sentence for a Neon Auth (Better Auth) failure. */
160
+ export function signInErrorMessage(error) {
161
+ const details = typeof error === "object" && error !== null ? error : {};
162
+ const status = typeof details.status === "number" ? details.status : undefined;
163
+ const text = [details.code, details.message]
164
+ .filter((part) => typeof part === "string")
165
+ .join(" ")
166
+ .toLowerCase();
167
+ if (status === 429 || text.includes("rate limit") || text.includes("too many requests")) {
168
+ return "Too many requests. Wait a minute, then try again.";
169
+ }
170
+ if (text.includes("too many attempts") || text.includes("too_many_attempts")) {
171
+ return "Too many wrong codes. Send a new code.";
172
+ }
173
+ if (text.includes("expired")) {
174
+ return "That code has expired. Send a new one.";
175
+ }
176
+ if (text.includes("otp") || text.includes("code")) {
177
+ return "That code is not right. Check the email and try again.";
178
+ }
179
+ if (text.includes("email")) {
180
+ return "Enter a valid email address.";
181
+ }
182
+ if (status === undefined || status >= 500 || text.includes("network")) {
183
+ return "Sign-in is unavailable right now. Try again in a moment.";
184
+ }
185
+ return "Sign-in failed. Try again.";
186
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@segmentstream-cloud/app",
3
- "version": "0.3.1",
3
+ "version": "0.3.2",
4
4
  "description": "Sign-in, users, permissions, the ontology client and warehouse data access for SegmentStream workspace apps built with Next.js.",
5
5
  "license": "Apache-2.0",
6
6
  "author": "SegmentStream",