@nexys/user-management-web 0.1.2 → 0.1.4

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nexys/user-management-web",
3
- "version": "0.1.2",
3
+ "version": "0.1.4",
4
4
  "description": "Modern, slick React + Tailwind + shadcn UI kit for the Nexys user-management service. Built on @nexys/user-management-client.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -33,7 +33,7 @@
33
33
  },
34
34
  "dependencies": {
35
35
  "@hookform/resolvers": "^3.10.0",
36
- "@nexys/user-management-client": "^0.1.2",
36
+ "@nexys/user-management-client": "^0.1.4",
37
37
  "@radix-ui/react-avatar": "^1.1.4",
38
38
  "@radix-ui/react-dialog": "^1.1.14",
39
39
  "@radix-ui/react-dropdown-menu": "^2.1.7",
@@ -0,0 +1,149 @@
1
+ import { type OAuthAppRow } from "@nexys/user-management-client";
2
+ import { AlertCircle, AppWindow, ShieldOff } from "lucide-react";
3
+ import { useState } from "react";
4
+
5
+ import { useUmClient } from "../../context/auth-context.js";
6
+ import { useCall } from "../../hooks/use-call.js";
7
+ import { errorMessage } from "../../lib/error-message.js";
8
+ import { formatRelative } from "../../lib/utils.js";
9
+ import { EmptyState } from "../primitives/empty-state.js";
10
+ import { Alert, AlertDescription } from "../ui/alert.js";
11
+ import { Button } from "../ui/button.js";
12
+ import {
13
+ Card,
14
+ CardContent,
15
+ CardDescription,
16
+ CardHeader,
17
+ CardTitle,
18
+ } from "../ui/card.js";
19
+ import {
20
+ Table,
21
+ TableBody,
22
+ TableCell,
23
+ TableHead,
24
+ TableHeader,
25
+ TableRow,
26
+ } from "../ui/table.js";
27
+
28
+ /** The resource as a reader knows it: host and path, without the scheme. */
29
+ const resourceLabel = (resource: string): string => {
30
+ try {
31
+ const url = new URL(resource);
32
+ return `${url.host}${url.pathname === "/" ? "" : url.pathname}`;
33
+ } catch {
34
+ return resource;
35
+ }
36
+ };
37
+
38
+ /**
39
+ * Connected apps: the OAuth clients (CLIs, mobile apps, MCP clients) the
40
+ * caller allowed into one of their tenants. Disconnecting one revokes its
41
+ * grant: its refresh token stops working at once, and its last access token
42
+ * within 15 minutes (access tokens are not checked against the grant).
43
+ */
44
+ export const ConnectedAppsCard = () => {
45
+ const client = useUmClient();
46
+ const { data, loading, error, refresh } = useCall("listOAuthApps");
47
+ const tenants = useCall("myTenants");
48
+ const [busy, setBusy] = useState<string | null>(null);
49
+ const [actionError, setActionError] = useState<string | null>(null);
50
+
51
+ const apps = data?.apps ?? [];
52
+ const tenantName = (organizationId: string): string =>
53
+ tenants.data?.memberships.find((m) => m.organizationId === organizationId)
54
+ ?.organizationName ?? organizationId;
55
+
56
+ const disconnect = async (app: OAuthAppRow) => {
57
+ setBusy(app.id);
58
+ setActionError(null);
59
+ const res = await client.revokeOAuthApp({ id: app.id });
60
+ setBusy(null);
61
+ if (res.ok) {
62
+ await refresh();
63
+ } else {
64
+ setActionError(errorMessage(res.error, "Couldn't disconnect the app."));
65
+ }
66
+ };
67
+
68
+ return (
69
+ <Card>
70
+ <CardHeader>
71
+ <CardTitle className="flex items-center gap-2">
72
+ <AppWindow className="size-4 text-muted-foreground" />
73
+ Connected apps
74
+ </CardTitle>
75
+ <CardDescription>
76
+ Apps you signed in to with OAuth, such as a CLI, a mobile app or an
77
+ MCP client. Each one acts as you in the tenant you chose. Disconnect
78
+ an app to sign it out: it stops working within 15 minutes.
79
+ </CardDescription>
80
+ </CardHeader>
81
+ <CardContent className="grid gap-4">
82
+ {error ? (
83
+ <Alert variant="destructive">
84
+ <AlertCircle />
85
+ <AlertDescription>{errorMessage(error)}</AlertDescription>
86
+ </Alert>
87
+ ) : null}
88
+ {actionError ? (
89
+ <Alert variant="destructive">
90
+ <AlertCircle />
91
+ <AlertDescription>{actionError}</AlertDescription>
92
+ </Alert>
93
+ ) : null}
94
+
95
+ {loading ? null : apps.length === 0 ? (
96
+ <EmptyState
97
+ icon={AppWindow}
98
+ title="No connected apps"
99
+ description="Apps you sign in to with OAuth show up here."
100
+ />
101
+ ) : (
102
+ <div className="overflow-hidden rounded-lg border">
103
+ <Table>
104
+ <TableHeader>
105
+ <TableRow>
106
+ <TableHead>App</TableHead>
107
+ <TableHead>Tenant</TableHead>
108
+ <TableHead>Access to</TableHead>
109
+ <TableHead>Connected</TableHead>
110
+ <TableHead>Last used</TableHead>
111
+ <TableHead className="text-right">Actions</TableHead>
112
+ </TableRow>
113
+ </TableHeader>
114
+ <TableBody>
115
+ {apps.map((app) => (
116
+ <TableRow key={app.id}>
117
+ <TableCell className="font-medium">{app.clientName}</TableCell>
118
+ <TableCell>{tenantName(app.organizationId)}</TableCell>
119
+ <TableCell className="font-mono text-xs text-muted-foreground">
120
+ {resourceLabel(app.resource)}
121
+ </TableCell>
122
+ <TableCell className="text-sm text-muted-foreground">
123
+ {formatRelative(app.grantedAt)}
124
+ </TableCell>
125
+ <TableCell className="text-sm text-muted-foreground">
126
+ {formatRelative(app.lastUsedAt)}
127
+ </TableCell>
128
+ <TableCell className="text-right">
129
+ <Button
130
+ variant="ghost"
131
+ size="sm"
132
+ onClick={() => disconnect(app)}
133
+ loading={busy === app.id}
134
+ aria-label={`Disconnect ${app.clientName}`}
135
+ >
136
+ <ShieldOff className="text-destructive" />
137
+ Disconnect
138
+ </Button>
139
+ </TableCell>
140
+ </TableRow>
141
+ ))}
142
+ </TableBody>
143
+ </Table>
144
+ </div>
145
+ )}
146
+ </CardContent>
147
+ </Card>
148
+ );
149
+ };
@@ -1,9 +1,12 @@
1
1
 
2
+ import { useAuth } from "../../context/auth-context.js";
2
3
  import { useCall } from "../../hooks/use-call.js";
3
4
  import { Tabs, TabsContent, TabsList, TabsTrigger } from "../ui/tabs.js";
4
5
  import { ProjectConsents } from "./project-consents.js";
5
6
  import { ProjectEmailTemplates } from "./project-email-templates.js";
6
7
  import { ProjectNotices } from "./project-notices.js";
8
+ import { ProjectOAuth } from "./project-oauth.js";
9
+ import { ProjectServiceAccounts } from "./project-service-accounts.js";
7
10
  import { ProjectSettings } from "./project-settings.js";
8
11
  import { ProjectTenants } from "./project-tenants.js";
9
12
 
@@ -24,6 +27,9 @@ export const ProjectDetailTabs = ({
24
27
  }: ProjectDetailTabsProps) => {
25
28
  // The email tab opens on the product's default locale.
26
29
  const { data } = useCall("getProject", { projectId });
30
+ // The OAuth settings API is superadmin only.
31
+ const { hasUserRole } = useAuth();
32
+ const showOAuth = canManage && hasUserRole("superadmin");
27
33
 
28
34
  return (
29
35
  <Tabs defaultValue="tenants">
@@ -32,6 +38,10 @@ export const ProjectDetailTabs = ({
32
38
  <TabsTrigger value="emails">Emails</TabsTrigger>
33
39
  <TabsTrigger value="consents">Consents</TabsTrigger>
34
40
  <TabsTrigger value="notices">Notices</TabsTrigger>
41
+ {canManage ? (
42
+ <TabsTrigger value="service-accounts">Service accounts</TabsTrigger>
43
+ ) : null}
44
+ {showOAuth ? <TabsTrigger value="oauth">OAuth</TabsTrigger> : null}
35
45
  <TabsTrigger value="settings">Settings</TabsTrigger>
36
46
  </TabsList>
37
47
  <TabsContent value="tenants" className="mt-4">
@@ -50,6 +60,16 @@ export const ProjectDetailTabs = ({
50
60
  <TabsContent value="notices" className="mt-4">
51
61
  <ProjectNotices projectId={projectId} canManage={canManage} />
52
62
  </TabsContent>
63
+ {canManage ? (
64
+ <TabsContent value="service-accounts" className="mt-4">
65
+ <ProjectServiceAccounts projectId={projectId} />
66
+ </TabsContent>
67
+ ) : null}
68
+ {showOAuth ? (
69
+ <TabsContent value="oauth" className="mt-4">
70
+ <ProjectOAuth projectId={projectId} />
71
+ </TabsContent>
72
+ ) : null}
53
73
  <TabsContent value="settings" className="mt-4">
54
74
  <ProjectSettings
55
75
  projectId={projectId}
@@ -0,0 +1,256 @@
1
+ import { AlertCircle, Check, Save, Trash2 } from "lucide-react";
2
+ import { useState, type FormEvent } from "react";
3
+
4
+ import { useUmClient } from "../../context/auth-context.js";
5
+ import { useCall } from "../../hooks/use-call.js";
6
+ import { errorMessage } from "../../lib/error-message.js";
7
+ import { Alert, AlertDescription } from "../ui/alert.js";
8
+ import { Badge } from "../ui/badge.js";
9
+ import { Button } from "../ui/button.js";
10
+ import {
11
+ Card,
12
+ CardContent,
13
+ CardDescription,
14
+ CardHeader,
15
+ CardTitle,
16
+ } from "../ui/card.js";
17
+ import {
18
+ Dialog,
19
+ DialogClose,
20
+ DialogContent,
21
+ DialogDescription,
22
+ DialogFooter,
23
+ DialogHeader,
24
+ DialogTitle,
25
+ DialogTrigger,
26
+ } from "../ui/dialog.js";
27
+ import { Field } from "../ui/field.js";
28
+ import { Input } from "../ui/input.js";
29
+ import { Skeleton } from "../ui/skeleton.js";
30
+ import { Textarea } from "../ui/textarea.js";
31
+
32
+ export interface ProjectOAuthProps {
33
+ projectId: string;
34
+ }
35
+
36
+ /**
37
+ * The product's OAuth settings: where this service sends the browser to
38
+ * approve a client (the product's consent page), and the resources it
39
+ * issues tokens for. Superadmin only, like the API behind it.
40
+ */
41
+ export const ProjectOAuth = ({ projectId }: ProjectOAuthProps) => {
42
+ const { data, loading, error, refresh } = useCall("getProjectOAuth", { projectId });
43
+
44
+ if (error) {
45
+ return (
46
+ <Alert variant="destructive">
47
+ <AlertCircle />
48
+ <AlertDescription>{errorMessage(error)}</AlertDescription>
49
+ </Alert>
50
+ );
51
+ }
52
+ if (loading && data === undefined) {
53
+ return <Skeleton className="h-64 w-full" />;
54
+ }
55
+
56
+ return (
57
+ <div className="grid gap-6">
58
+ <Card>
59
+ <CardHeader>
60
+ <CardTitle className="flex items-center gap-2">
61
+ OAuth sign-in
62
+ {data ? <Badge>On</Badge> : <Badge variant="outline">Off</Badge>}
63
+ </CardTitle>
64
+ <CardDescription>
65
+ Lets this product&apos;s apps and MCP clients sign in with OAuth
66
+ (authorization code with PKCE). A client registers with this
67
+ service, the user approves it on the product&apos;s consent page
68
+ and picks a tenant, and the client gets a short-lived access token
69
+ for one of the resources below and a refresh token.
70
+ </CardDescription>
71
+ </CardHeader>
72
+ <CardContent>
73
+ <OAuthForm
74
+ key={data?.updatedAt ?? "off"}
75
+ projectId={projectId}
76
+ consentUrl={data?.consentUrl ?? ""}
77
+ resources={data?.resources ?? []}
78
+ enabled={!!data}
79
+ onSaved={refresh}
80
+ />
81
+ </CardContent>
82
+ </Card>
83
+ {data ? (
84
+ <TurnOffCard projectId={projectId} onTurnedOff={refresh} />
85
+ ) : null}
86
+ </div>
87
+ );
88
+ };
89
+
90
+ const OAuthForm = ({
91
+ projectId,
92
+ consentUrl: initialConsentUrl,
93
+ resources: initialResources,
94
+ enabled,
95
+ onSaved,
96
+ }: {
97
+ projectId: string;
98
+ consentUrl: string;
99
+ resources: string[];
100
+ enabled: boolean;
101
+ onSaved: () => void;
102
+ }) => {
103
+ const client = useUmClient();
104
+ const [consentUrl, setConsentUrl] = useState(initialConsentUrl);
105
+ const [text, setText] = useState(initialResources.join("\n"));
106
+ const [saving, setSaving] = useState(false);
107
+ const [saved, setSaved] = useState(false);
108
+ const [error, setError] = useState<string | null>(null);
109
+
110
+ const resources = parseLines(text);
111
+ const dirty =
112
+ consentUrl.trim() !== initialConsentUrl ||
113
+ resources.join("\n") !== initialResources.join("\n");
114
+ const complete = consentUrl.trim() !== "" && resources.length > 0;
115
+
116
+ const submit = async (e: FormEvent) => {
117
+ e.preventDefault();
118
+ setSaving(true);
119
+ setError(null);
120
+ setSaved(false);
121
+ const res = await client.setProjectOAuth({
122
+ projectId,
123
+ consentUrl: consentUrl.trim(),
124
+ resources,
125
+ });
126
+ setSaving(false);
127
+ if (res.ok) {
128
+ setSaved(true);
129
+ setTimeout(() => setSaved(false), 2000);
130
+ onSaved();
131
+ } else {
132
+ setError(errorMessage(res.error, "Couldn't save the OAuth settings."));
133
+ }
134
+ };
135
+
136
+ return (
137
+ <form onSubmit={submit} className="grid gap-4">
138
+ {error ? (
139
+ <Alert variant="destructive">
140
+ <AlertCircle />
141
+ <AlertDescription>{error}</AlertDescription>
142
+ </Alert>
143
+ ) : null}
144
+ <Field
145
+ label="Consent page"
146
+ htmlFor="project-oauth-consent-url"
147
+ description="The product's own page that asks the user to approve a client. This service sends the browser there with ?request=<id>. https, or http on localhost."
148
+ >
149
+ <Input
150
+ id="project-oauth-consent-url"
151
+ value={consentUrl}
152
+ onChange={(e) => setConsentUrl(e.target.value)}
153
+ placeholder="https://app.example.com/oauth/consent"
154
+ className="font-mono"
155
+ />
156
+ </Field>
157
+ <Field
158
+ label="Resources"
159
+ htmlFor="project-oauth-resources"
160
+ description="One URL per line, 1 to 10 (RFC 8707). Each access token is issued for one of them, and the product's server accepts only tokens for its own. A resource belongs to one product."
161
+ >
162
+ <Textarea
163
+ id="project-oauth-resources"
164
+ value={text}
165
+ onChange={(e) => setText(e.target.value)}
166
+ rows={3}
167
+ placeholder={"https://app.example.com/api\nhttps://app.example.com/mcp"}
168
+ className="font-mono"
169
+ />
170
+ </Field>
171
+ <div className="flex items-center gap-3">
172
+ <Button type="submit" loading={saving} disabled={!dirty || !complete}>
173
+ {saved ? <Check /> : <Save />}
174
+ {saved ? "Saved" : enabled ? "Save changes" : "Turn on OAuth"}
175
+ </Button>
176
+ </div>
177
+ </form>
178
+ );
179
+ };
180
+
181
+ const TurnOffCard = ({
182
+ projectId,
183
+ onTurnedOff,
184
+ }: {
185
+ projectId: string;
186
+ onTurnedOff: () => void;
187
+ }) => {
188
+ const client = useUmClient();
189
+ const [busy, setBusy] = useState(false);
190
+ const [error, setError] = useState<string | null>(null);
191
+
192
+ const turnOff = async () => {
193
+ setBusy(true);
194
+ setError(null);
195
+ const res = await client.deleteProjectOAuth({ projectId });
196
+ setBusy(false);
197
+ if (res.ok) {
198
+ onTurnedOff();
199
+ } else {
200
+ setError(errorMessage(res.error, "Couldn't turn off OAuth."));
201
+ }
202
+ };
203
+
204
+ return (
205
+ <Card className="border-destructive/50">
206
+ <CardHeader>
207
+ <CardTitle className="text-destructive">Turn off OAuth</CardTitle>
208
+ <CardDescription>
209
+ New sign-ins are refused. Apps already signed in keep working
210
+ until their users sign out or revoke them.
211
+ </CardDescription>
212
+ </CardHeader>
213
+ <CardContent>
214
+ {error ? (
215
+ <Alert variant="destructive" className="mb-4">
216
+ <AlertCircle />
217
+ <AlertDescription>{error}</AlertDescription>
218
+ </Alert>
219
+ ) : null}
220
+ <Dialog>
221
+ <DialogTrigger asChild>
222
+ <Button variant="destructive">
223
+ <Trash2 /> Turn off OAuth
224
+ </Button>
225
+ </DialogTrigger>
226
+ <DialogContent>
227
+ <DialogHeader>
228
+ <DialogTitle>Turn off OAuth?</DialogTitle>
229
+ <DialogDescription>
230
+ The consent page and resources are removed, and apps (CLI,
231
+ mobile app, MCP clients) cannot start a new sign-in to this
232
+ product until you turn it back on. Apps already signed in keep
233
+ working until their users sign out or revoke them.
234
+ </DialogDescription>
235
+ </DialogHeader>
236
+ <DialogFooter>
237
+ <DialogClose asChild>
238
+ <Button variant="outline">Cancel</Button>
239
+ </DialogClose>
240
+ <Button variant="destructive" onClick={turnOff} loading={busy}>
241
+ Turn off
242
+ </Button>
243
+ </DialogFooter>
244
+ </DialogContent>
245
+ </Dialog>
246
+ </CardContent>
247
+ </Card>
248
+ );
249
+ };
250
+
251
+ /** One entry per line, trimmed, blanks dropped. */
252
+ const parseLines = (text: string): string[] =>
253
+ text
254
+ .split("\n")
255
+ .map((l) => l.trim())
256
+ .filter((l) => l.length > 0);
@@ -0,0 +1,116 @@
1
+ /// <reference lib="dom" />
2
+ import { afterEach, describe, expect, test } from "bun:test";
3
+
4
+ import { fireEvent, render, screen, waitFor } from "@testing-library/react";
5
+
6
+ import { mockRpc, reply } from "@nexys/user-management-client/testing";
7
+
8
+ import { AuthProvider } from "../../context/auth-context.js";
9
+ import { ProjectServiceAccounts } from "./project-service-accounts.js";
10
+
11
+ const ACCOUNT = {
12
+ id: "sa1",
13
+ projectId: "p1",
14
+ name: "eagle-backend",
15
+ description: "orchestrator",
16
+ role: "admin",
17
+ createdAt: "2026-11-01T00:00:00Z",
18
+ createdById: "u1",
19
+ token: {
20
+ id: "k1",
21
+ start: "um_abcde",
22
+ createdAt: "2026-11-01T00:00:00Z",
23
+ lastUsedAt: null,
24
+ },
25
+ };
26
+
27
+ afterEach(() => {
28
+ document.body.innerHTML = "";
29
+ });
30
+
31
+ const renderWith = (responder: Parameters<typeof mockRpc>[0]) => {
32
+ const rpc = mockRpc((p, input) => {
33
+ if (p === "me") return reply({ code: "unauth" }, 401);
34
+ return responder(p, input);
35
+ });
36
+ render(
37
+ <AuthProvider client={rpc.client} refreshIntervalMs={0}>
38
+ <ProjectServiceAccounts projectId="p1" />
39
+ </AuthProvider>
40
+ );
41
+ return rpc;
42
+ };
43
+
44
+ describe("<ProjectServiceAccounts />", () => {
45
+ test("lists accounts with their role and token prefix, never the token", async () => {
46
+ renderWith((p) =>
47
+ p === "listProjectServiceAccounts"
48
+ ? reply({ serviceAccounts: [ACCOUNT] })
49
+ : reply({ error: "not_found" }, 404)
50
+ );
51
+ await waitFor(() => expect(screen.getByText("eagle-backend")).toBeTruthy());
52
+ expect(screen.getByText("orchestrator")).toBeTruthy();
53
+ expect(screen.getByRole("cell", { name: "admin" })).toBeTruthy();
54
+ expect(screen.getByText("um_abcde…")).toBeTruthy();
55
+ expect(screen.getByText("Never")).toBeTruthy();
56
+ expect(screen.queryByTestId("service-account-token")).toBeNull();
57
+ });
58
+
59
+ test("creating an account shows its token once", async () => {
60
+ const rpc = renderWith((p) => {
61
+ if (p === "listProjectServiceAccounts") return reply({ serviceAccounts: [] });
62
+ if (p === "createProjectServiceAccount") {
63
+ return reply(
64
+ { serviceAccount: ACCOUNT, token: "um_secret_token", tokenId: "k1" },
65
+ 201
66
+ );
67
+ }
68
+ return reply({ error: "not_found" }, 404);
69
+ });
70
+ await waitFor(() => expect(screen.getByText("No service accounts")).toBeTruthy());
71
+
72
+ fireEvent.change(screen.getByLabelText(/name/i), {
73
+ target: { value: " eagle-backend " },
74
+ });
75
+ fireEvent.click(screen.getByRole("button", { name: /create/i }));
76
+
77
+ await waitFor(() =>
78
+ expect(screen.getByTestId("service-account-token").textContent).toBe(
79
+ "um_secret_token"
80
+ )
81
+ );
82
+ const create = rpc.calls.find((c) => c.procedure === "createProjectServiceAccount");
83
+ expect(create?.input).toEqual({
84
+ projectId: "p1",
85
+ name: "eagle-backend",
86
+ description: null,
87
+ role: "admin",
88
+ });
89
+
90
+ fireEvent.click(screen.getByRole("button", { name: /done/i }));
91
+ expect(screen.queryByTestId("service-account-token")).toBeNull();
92
+ });
93
+
94
+ test("replacing a token asks first, then shows the new one", async () => {
95
+ const rpc = renderWith((p) => {
96
+ if (p === "listProjectServiceAccounts") return reply({ serviceAccounts: [ACCOUNT] });
97
+ if (p === "rotateProjectServiceAccountToken") {
98
+ return reply({ token: "um_new_token", tokenId: "k2" });
99
+ }
100
+ return reply({ error: "not_found" }, 404);
101
+ });
102
+ await waitFor(() => expect(screen.getByText("eagle-backend")).toBeTruthy());
103
+
104
+ fireEvent.click(screen.getByRole("button", { name: /replace token of eagle-backend/i }));
105
+ expect(rpc.calls.some((c) => c.procedure === "rotateProjectServiceAccountToken")).toBe(
106
+ false
107
+ );
108
+ fireEvent.click(await screen.findByRole("button", { name: /^replace token$/i }));
109
+
110
+ await waitFor(() =>
111
+ expect(screen.getByTestId("service-account-token").textContent).toBe("um_new_token")
112
+ );
113
+ const rotate = rpc.calls.find((c) => c.procedure === "rotateProjectServiceAccountToken");
114
+ expect(rotate?.input).toEqual({ projectId: "p1", userId: "sa1" });
115
+ });
116
+ });
@@ -0,0 +1,366 @@
1
+ import { type ProjectServiceAccountRow } from "@nexys/user-management-client";
2
+ import {
3
+ AlertCircle,
4
+ Bot,
5
+ Check,
6
+ Copy,
7
+ Plus,
8
+ RefreshCw,
9
+ Trash2,
10
+ } from "lucide-react";
11
+ import { useState, type FormEvent, type ReactNode } from "react";
12
+
13
+ import { useUmClient } from "../../context/auth-context.js";
14
+ import { useCall } from "../../hooks/use-call.js";
15
+ import { errorMessage } from "../../lib/error-message.js";
16
+ import { formatRelative } from "../../lib/utils.js";
17
+ import { EmptyState } from "../primitives/empty-state.js";
18
+ import { Alert, AlertDescription } from "../ui/alert.js";
19
+ import { Badge } from "../ui/badge.js";
20
+ import { Button } from "../ui/button.js";
21
+ import {
22
+ Card,
23
+ CardContent,
24
+ CardDescription,
25
+ CardHeader,
26
+ CardTitle,
27
+ } from "../ui/card.js";
28
+ import {
29
+ Dialog,
30
+ DialogClose,
31
+ DialogContent,
32
+ DialogDescription,
33
+ DialogFooter,
34
+ DialogHeader,
35
+ DialogTitle,
36
+ DialogTrigger,
37
+ } from "../ui/dialog.js";
38
+ import { Field } from "../ui/field.js";
39
+ import { Input } from "../ui/input.js";
40
+ import {
41
+ Select,
42
+ SelectContent,
43
+ SelectItem,
44
+ SelectTrigger,
45
+ SelectValue,
46
+ } from "../ui/select.js";
47
+ import { Skeleton } from "../ui/skeleton.js";
48
+ import {
49
+ Table,
50
+ TableBody,
51
+ TableCell,
52
+ TableHead,
53
+ TableHeader,
54
+ TableRow,
55
+ } from "../ui/table.js";
56
+
57
+ export interface ProjectServiceAccountsProps {
58
+ projectId: string;
59
+ }
60
+
61
+ type Role = "admin" | "member";
62
+
63
+ /** A token just minted for `name` — shown once. */
64
+ interface RevealedToken {
65
+ name: string;
66
+ token: string;
67
+ }
68
+
69
+ /**
70
+ * A product's service accounts: API tokens for the product's backend.
71
+ * Each acts only inside this product — its tenants and its users — so a
72
+ * leaked token can't reach another product. Tokens are shown once, at
73
+ * creation or replacement.
74
+ */
75
+ export const ProjectServiceAccounts = ({ projectId }: ProjectServiceAccountsProps) => {
76
+ const client = useUmClient();
77
+ const { data, loading, error, refresh } = useCall("listProjectServiceAccounts", {
78
+ projectId,
79
+ });
80
+ const [name, setName] = useState("");
81
+ const [description, setDescription] = useState("");
82
+ const [role, setRole] = useState<Role>("admin");
83
+ const [creating, setCreating] = useState(false);
84
+ const [revealed, setRevealed] = useState<RevealedToken | null>(null);
85
+ const [actionError, setActionError] = useState<string | null>(null);
86
+
87
+ const accounts = data?.serviceAccounts ?? [];
88
+
89
+ const create = async (e: FormEvent) => {
90
+ e.preventDefault();
91
+ setCreating(true);
92
+ setActionError(null);
93
+ const res = await client.createProjectServiceAccount({
94
+ projectId,
95
+ name: name.trim(),
96
+ description: description.trim() || null,
97
+ role,
98
+ });
99
+ setCreating(false);
100
+ if (res.ok) {
101
+ setRevealed({ name: res.data.serviceAccount.name, token: res.data.token });
102
+ setName("");
103
+ setDescription("");
104
+ setRole("admin");
105
+ await refresh();
106
+ } else {
107
+ setActionError(errorMessage(res.error, "Couldn't create the service account."));
108
+ }
109
+ };
110
+
111
+ const rotate = async (sa: ProjectServiceAccountRow) => {
112
+ setActionError(null);
113
+ const res = await client.rotateProjectServiceAccountToken({
114
+ projectId,
115
+ userId: sa.id,
116
+ });
117
+ if (res.ok) {
118
+ setRevealed({ name: sa.name, token: res.data.token });
119
+ await refresh();
120
+ return true;
121
+ }
122
+ setActionError(errorMessage(res.error, "Couldn't replace the token."));
123
+ return false;
124
+ };
125
+
126
+ const remove = async (sa: ProjectServiceAccountRow) => {
127
+ setActionError(null);
128
+ const res = await client.deleteProjectServiceAccount({ projectId, userId: sa.id });
129
+ if (res.ok) {
130
+ await refresh();
131
+ return true;
132
+ }
133
+ setActionError(errorMessage(res.error, "Couldn't delete the service account."));
134
+ return false;
135
+ };
136
+
137
+ return (
138
+ <Card>
139
+ <CardHeader>
140
+ <CardTitle className="flex items-center gap-2">
141
+ <Bot className="size-4 text-muted-foreground" />
142
+ Service accounts
143
+ </CardTitle>
144
+ <CardDescription>
145
+ API tokens for this product's backend, sent as{" "}
146
+ <code className="font-mono text-xs">Authorization: Bearer um_…</code>.
147
+ A service account acts only inside this product: an{" "}
148
+ <strong>admin</strong> manages its tenants and reads its users; a{" "}
149
+ <strong>member</strong> only belongs to it.
150
+ </CardDescription>
151
+ </CardHeader>
152
+ <CardContent className="grid gap-4">
153
+ {error ? (
154
+ <Alert variant="destructive">
155
+ <AlertCircle />
156
+ <AlertDescription>{errorMessage(error)}</AlertDescription>
157
+ </Alert>
158
+ ) : null}
159
+ {actionError ? (
160
+ <Alert variant="destructive">
161
+ <AlertCircle />
162
+ <AlertDescription>{actionError}</AlertDescription>
163
+ </Alert>
164
+ ) : null}
165
+
166
+ {revealed ? (
167
+ <TokenReveal revealed={revealed} onDone={() => setRevealed(null)} />
168
+ ) : (
169
+ <form
170
+ onSubmit={create}
171
+ className="grid items-end gap-3 sm:grid-cols-[1fr_1fr_auto_auto]"
172
+ >
173
+ <Field label="Name" htmlFor="sa-name" required>
174
+ <Input
175
+ id="sa-name"
176
+ required
177
+ value={name}
178
+ onChange={(e) => setName(e.target.value)}
179
+ placeholder="e.g. eagle-backend"
180
+ />
181
+ </Field>
182
+ <Field label="Description" htmlFor="sa-description">
183
+ <Input
184
+ id="sa-description"
185
+ value={description}
186
+ onChange={(e) => setDescription(e.target.value)}
187
+ placeholder="Optional"
188
+ />
189
+ </Field>
190
+ <Field label="Role" htmlFor="sa-role">
191
+ <Select value={role} onValueChange={(v) => setRole(v as Role)}>
192
+ <SelectTrigger id="sa-role" className="w-[8rem]">
193
+ <SelectValue />
194
+ </SelectTrigger>
195
+ <SelectContent>
196
+ <SelectItem value="admin">Admin</SelectItem>
197
+ <SelectItem value="member">Member</SelectItem>
198
+ </SelectContent>
199
+ </Select>
200
+ </Field>
201
+ <Button type="submit" loading={creating} disabled={!name.trim()}>
202
+ <Plus />
203
+ Create
204
+ </Button>
205
+ </form>
206
+ )}
207
+
208
+ {loading ? (
209
+ <Skeleton className="h-16 w-full" />
210
+ ) : accounts.length === 0 ? (
211
+ <EmptyState
212
+ icon={Bot}
213
+ title="No service accounts"
214
+ description="Create one for each backend that calls this product's API."
215
+ />
216
+ ) : (
217
+ <div className="overflow-hidden rounded-lg border">
218
+ <Table>
219
+ <TableHeader>
220
+ <TableRow>
221
+ <TableHead>Name</TableHead>
222
+ <TableHead>Role</TableHead>
223
+ <TableHead>Token</TableHead>
224
+ <TableHead>Last used</TableHead>
225
+ <TableHead className="text-right">Actions</TableHead>
226
+ </TableRow>
227
+ </TableHeader>
228
+ <TableBody>
229
+ {accounts.map((sa) => (
230
+ <TableRow key={sa.id}>
231
+ <TableCell>
232
+ <div className="font-medium">{sa.name}</div>
233
+ {sa.description ? (
234
+ <div className="text-muted-foreground text-xs">{sa.description}</div>
235
+ ) : null}
236
+ </TableCell>
237
+ <TableCell>
238
+ <Badge variant="secondary">{sa.role}</Badge>
239
+ </TableCell>
240
+ <TableCell className="font-mono text-xs text-muted-foreground">
241
+ {sa.token?.start ? `${sa.token.start}…` : "none"}
242
+ </TableCell>
243
+ <TableCell className="text-sm text-muted-foreground">
244
+ {sa.token?.lastUsedAt ? formatRelative(sa.token.lastUsedAt) : "Never"}
245
+ </TableCell>
246
+ <TableCell className="text-right">
247
+ <ConfirmAction
248
+ icon={<RefreshCw />}
249
+ label={`Replace token of ${sa.name}`}
250
+ title={`Replace ${sa.name}'s token?`}
251
+ description="The current token stops working at once. Update the backend that uses it with the new one."
252
+ confirmLabel="Replace token"
253
+ onConfirm={() => rotate(sa)}
254
+ />
255
+ <ConfirmAction
256
+ icon={<Trash2 className="text-destructive" />}
257
+ label={`Delete ${sa.name}`}
258
+ title={`Delete ${sa.name}?`}
259
+ description="Its token stops working at once and it leaves every tenant it belongs to. Tenants it created stay."
260
+ confirmLabel="Delete"
261
+ destructive
262
+ onConfirm={() => remove(sa)}
263
+ />
264
+ </TableCell>
265
+ </TableRow>
266
+ ))}
267
+ </TableBody>
268
+ </Table>
269
+ </div>
270
+ )}
271
+ </CardContent>
272
+ </Card>
273
+ );
274
+ };
275
+
276
+ const TokenReveal = ({
277
+ revealed,
278
+ onDone,
279
+ }: {
280
+ revealed: RevealedToken;
281
+ onDone: () => void;
282
+ }) => {
283
+ const [copied, setCopied] = useState(false);
284
+ const copy = async () => {
285
+ await navigator.clipboard.writeText(revealed.token);
286
+ setCopied(true);
287
+ setTimeout(() => setCopied(false), 2000);
288
+ };
289
+ return (
290
+ <div className="grid gap-2 rounded-lg border border-dashed bg-muted/30 p-4">
291
+ <p className="text-sm font-medium">
292
+ Copy the token for {revealed.name} now — it won't be shown again.
293
+ </p>
294
+ <div className="flex items-center gap-2">
295
+ <code
296
+ data-testid="service-account-token"
297
+ className="flex-1 break-all rounded bg-muted px-2 py-1 font-mono text-xs"
298
+ >
299
+ {revealed.token}
300
+ </code>
301
+ <Button variant="outline" size="sm" onClick={copy}>
302
+ {copied ? <Check className="text-green-600" /> : <Copy />}
303
+ {copied ? "Copied" : "Copy"}
304
+ </Button>
305
+ <Button size="sm" onClick={onDone}>
306
+ Done
307
+ </Button>
308
+ </div>
309
+ </div>
310
+ );
311
+ };
312
+
313
+ /** An icon button that asks before running `onConfirm`. */
314
+ const ConfirmAction = ({
315
+ icon,
316
+ label,
317
+ title,
318
+ description,
319
+ confirmLabel,
320
+ destructive = false,
321
+ onConfirm,
322
+ }: {
323
+ icon: ReactNode;
324
+ label: string;
325
+ title: string;
326
+ description: string;
327
+ confirmLabel: string;
328
+ destructive?: boolean;
329
+ onConfirm: () => Promise<boolean>;
330
+ }) => {
331
+ const [open, setOpen] = useState(false);
332
+ const [busy, setBusy] = useState(false);
333
+ const confirm = async () => {
334
+ setBusy(true);
335
+ const done = await onConfirm();
336
+ setBusy(false);
337
+ if (done) setOpen(false);
338
+ };
339
+ return (
340
+ <Dialog open={open} onOpenChange={setOpen}>
341
+ <DialogTrigger asChild>
342
+ <Button variant="ghost" size="icon" aria-label={label}>
343
+ {icon}
344
+ </Button>
345
+ </DialogTrigger>
346
+ <DialogContent>
347
+ <DialogHeader>
348
+ <DialogTitle>{title}</DialogTitle>
349
+ <DialogDescription>{description}</DialogDescription>
350
+ </DialogHeader>
351
+ <DialogFooter>
352
+ <DialogClose asChild>
353
+ <Button variant="outline">Cancel</Button>
354
+ </DialogClose>
355
+ <Button
356
+ variant={destructive ? "destructive" : "default"}
357
+ onClick={() => void confirm()}
358
+ loading={busy}
359
+ >
360
+ {confirmLabel}
361
+ </Button>
362
+ </DialogFooter>
363
+ </DialogContent>
364
+ </Dialog>
365
+ );
366
+ };
package/src/index.ts CHANGED
@@ -111,6 +111,7 @@ export { SignUpForm, type SignUpFormProps } from "./components/auth/sign-up-form
111
111
 
112
112
  // profile
113
113
  export { ApiTokensCard } from "./components/profile/api-tokens-card.js";
114
+ export { ConnectedAppsCard } from "./components/profile/connected-apps-card.js";
114
115
  export { ChangePasswordForm } from "./components/profile/change-password-form.js";
115
116
  export { PasskeysCard } from "./components/profile/passkeys-card.js";
116
117
  export { ProfileCard } from "./components/profile/profile-card.js";
@@ -140,6 +141,8 @@ export { AuditLogTable } from "./components/audit/audit-log-table.js";
140
141
  // projects (products)
141
142
  export { ProjectCreateDialog, type ProjectCreateDialogProps } from "./components/projects/project-create-dialog.js";
142
143
  export { ProjectDetailTabs, type ProjectDetailTabsProps } from "./components/projects/project-detail-tabs.js";
144
+ export { ProjectOAuth, type ProjectOAuthProps } from "./components/projects/project-oauth.js";
145
+ export { ProjectServiceAccounts, type ProjectServiceAccountsProps } from "./components/projects/project-service-accounts.js";
143
146
  export { ProjectSettings, type ProjectSettingsProps } from "./components/projects/project-settings.js";
144
147
  export { ProjectTenants, type ProjectTenantsProps } from "./components/projects/project-tenants.js";
145
148
  export { ProjectsTable } from "./components/projects/projects-table.js";