bwh-auth 0.3.3 → 0.4.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/README.md CHANGED
@@ -22,6 +22,7 @@ The companion Laravel API package is
22
22
  - `TwoFactorForm`
23
23
  - `PasskeyLoginButton`
24
24
  - `PasskeySection`
25
+ - `ApiCredentialsSection`
25
26
 
26
27
  ## Relying-party helpers
27
28
 
@@ -206,6 +207,31 @@ The explicit passkey button and conditional autofill both default to the Laravel
206
207
  />
207
208
  ```
208
209
 
210
+ ## API credentials
211
+
212
+ `ApiCredentialsSection` lets a signed-in person create credentials for apps that use the API:
213
+ - **API tokens**, for connectors that ask for a key;
214
+ - **OAuth apps**, for connectors that run the authorization-code flow.
215
+
216
+ It talks to the auth package's credential service (`oauth_server.credentials`) through its JSON index URL. The server sends every action URL, so the component assembles none.
217
+
218
+ ```tsx
219
+ <ApiCredentialsSection
220
+ indexUrl="/account/api-credentials"
221
+ components={components}
222
+ links={[
223
+ { label: 'OpenAPI document', url: openApiUrl },
224
+ { label: 'OAuth authorize URL', url: authorizeUrl },
225
+ { label: 'OAuth token URL', url: tokenUrl },
226
+ ]}
227
+ />
228
+ ```
229
+
230
+ - **Each new secret is shown once.** It comes from the creation response and is kept only in component memory. Afterwards only the lists are reloaded, so it never enters page props or history.
231
+ - **Requests** send the session cookie and `X-CSRF-TOKEN`. A 401 or 419 response becomes "sign in again".
232
+ - **While the server reports issuing unavailable** (OAuth switched off), the create forms are hidden, and revoke and delete still work.
233
+ - **Token lifetimes** are ISO-8601 durations from the server, displayed as text (`PT4H` shows as "4 hours").
234
+
209
235
  ## Endpoint Defaults
210
236
 
211
237
  Auth forms default to the Laravel package API routes where the Laravel package owns the endpoint:
package/dist/index.cjs CHANGED
@@ -30,6 +30,7 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
30
30
  // src/index.ts
31
31
  var index_exports = {};
32
32
  __export(index_exports, {
33
+ ApiCredentialsSection: () => ApiCredentialsSection,
33
34
  ChangePasswordForm: () => ChangePasswordForm,
34
35
  LoginForm: () => LoginForm,
35
36
  PasskeyLoginButton: () => PasskeyLoginButton,
@@ -41,6 +42,7 @@ __export(index_exports, {
41
42
  arrayBufferToBase64url: () => arrayBufferToBase64url,
42
43
  authenticateWithPasskey: () => authenticateWithPasskey,
43
44
  base64urlToArrayBuffer: () => base64urlToArrayBuffer,
45
+ describeDuration: () => describeDuration,
44
46
  getCsrfToken: () => getCsrfToken,
45
47
  getDefaultPasskeyName: () => getDefaultPasskeyName,
46
48
  isAbortError: () => isAbortError,
@@ -995,8 +997,398 @@ function relyingApplicationsFrom(value) {
995
997
  return href === null ? [] : [{ key, name: name.trim(), url: href }];
996
998
  });
997
999
  }
1000
+
1001
+ // src/api-credentials-section.tsx
1002
+ var React5 = __toESM(require("react"), 1);
1003
+ var import_jsx_runtime4 = require("react/jsx-runtime");
1004
+ function ApiCredentialsSection({ indexUrl, components, links = [], csrfToken, onSuccess, onError }) {
1005
+ const { Card, CardContent, CardDescription, CardHeader, CardTitle } = resolveAuthComponents(components);
1006
+ const [index, setIndex] = React5.useState(null);
1007
+ const [issued, setIssued] = React5.useState([]);
1008
+ const issuedKey = React5.useRef(0);
1009
+ const addIssued = React5.useCallback((credential) => {
1010
+ issuedKey.current += 1;
1011
+ const key = issuedKey.current;
1012
+ setIssued((current) => [...current, { key, credential }]);
1013
+ }, []);
1014
+ const [loadError, setLoadError] = React5.useState(null);
1015
+ const onErrorRef = React5.useRef(onError);
1016
+ onErrorRef.current = onError;
1017
+ const generation = React5.useRef(0);
1018
+ const context = React5.useRef({ indexUrl, csrfToken });
1019
+ context.current = { indexUrl, csrfToken };
1020
+ const reload = React5.useCallback(async () => {
1021
+ generation.current += 1;
1022
+ const mine = generation.current;
1023
+ const { indexUrl: url, csrfToken: token } = context.current;
1024
+ const result = await credentialRequest("GET", url, void 0, token);
1025
+ if (mine !== generation.current) {
1026
+ return;
1027
+ }
1028
+ if (result.ok) {
1029
+ setIndex(result.data);
1030
+ setLoadError(null);
1031
+ } else {
1032
+ setLoadError(result.message);
1033
+ onErrorRef.current?.("api-credentials", result.message);
1034
+ }
1035
+ }, []);
1036
+ React5.useEffect(() => {
1037
+ setIndex(null);
1038
+ void reload();
1039
+ }, [indexUrl, csrfToken, reload]);
1040
+ const removeLocally = React5.useCallback((list, id) => {
1041
+ setIndex(
1042
+ (current) => current === null ? current : list === "tokens" ? { ...current, tokens: current.tokens.filter((token) => token.id !== id) } : { ...current, apps: current.apps.filter((app) => app.id !== id) }
1043
+ );
1044
+ }, []);
1045
+ const shared = { components, csrfToken, onError, onSuccess, removeLocally };
1046
+ return /* @__PURE__ */ (0, import_jsx_runtime4.jsxs)(Card, { children: [
1047
+ /* @__PURE__ */ (0, import_jsx_runtime4.jsxs)(CardHeader, { children: [
1048
+ /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(CardTitle, { children: "API access" }),
1049
+ /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(CardDescription, { children: "Connect apps that use the API. Register an OAuth app for apps that sign you in, or create an API token for apps that ask for a key. Each carries only the permissions you choose, and never more than your own access." })
1050
+ ] }),
1051
+ /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(CardContent, { children: /* @__PURE__ */ (0, import_jsx_runtime4.jsxs)("div", { style: { display: "grid", gap: "1.5rem", minWidth: 0 }, children: [
1052
+ links.length > 0 && /* @__PURE__ */ (0, import_jsx_runtime4.jsx)("dl", { style: { display: "grid", gap: "0.5rem", minWidth: 0 }, children: links.map((link) => /* @__PURE__ */ (0, import_jsx_runtime4.jsxs)("div", { style: { minWidth: 0 }, children: [
1053
+ /* @__PURE__ */ (0, import_jsx_runtime4.jsx)("dt", { children: link.label }),
1054
+ /* @__PURE__ */ (0, import_jsx_runtime4.jsxs)("dd", { style: { margin: 0, overflowWrap: "anywhere" }, children: [
1055
+ /* @__PURE__ */ (0, import_jsx_runtime4.jsx)("code", { children: link.url }),
1056
+ " ",
1057
+ /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(CopyButton, { text: link.url, label: link.label, components })
1058
+ ] })
1059
+ ] }, link.label)) }),
1060
+ issued.map(({ key, credential }) => /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(
1061
+ IssuedNotice,
1062
+ {
1063
+ issued: credential,
1064
+ components,
1065
+ onDismiss: () => setIssued((current) => current.filter((entry) => entry.key !== key))
1066
+ },
1067
+ key
1068
+ )),
1069
+ loadError !== null && /* @__PURE__ */ (0, import_jsx_runtime4.jsx)("p", { role: "alert", children: loadError }),
1070
+ index !== null && /* @__PURE__ */ (0, import_jsx_runtime4.jsxs)(import_jsx_runtime4.Fragment, { children: [
1071
+ (index.issue_token_href === null || index.register_app_href === null) && /* @__PURE__ */ (0, import_jsx_runtime4.jsx)("p", { role: "status", children: "Creating new credentials is unavailable right now. You can still revoke existing ones." }),
1072
+ /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(TokenSection, { index, ...shared, onIssued: addIssued, reload }),
1073
+ /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(AppSection, { index, ...shared, onIssued: addIssued, reload })
1074
+ ] })
1075
+ ] }) })
1076
+ ] });
1077
+ }
1078
+ function TokenSection({ index, components, csrfToken, onIssued, reload, onSuccess, onError, removeLocally }) {
1079
+ const { Button, Input, Label } = resolveAuthComponents(components);
1080
+ const [name, setName] = React5.useState("");
1081
+ const [scopes, setScopes] = React5.useState([]);
1082
+ const [lifetime, setLifetime] = React5.useState(index.token_lifetimes[0] ?? "");
1083
+ const [busy, setBusy] = React5.useState(false);
1084
+ const [error, setError] = React5.useState(null);
1085
+ async function create(event) {
1086
+ event.preventDefault();
1087
+ if (index.issue_token_href === null) {
1088
+ return;
1089
+ }
1090
+ setBusy(true);
1091
+ const result = await credentialRequest("POST", index.issue_token_href, { name, scopes, lifetime }, csrfToken);
1092
+ setBusy(false);
1093
+ if (!result.ok) {
1094
+ setError(result.message);
1095
+ onError?.("api-tokens", result.message);
1096
+ return;
1097
+ }
1098
+ setError(null);
1099
+ setName("");
1100
+ setScopes([]);
1101
+ onIssued(result.data);
1102
+ onSuccess?.("API token created.");
1103
+ await reload();
1104
+ }
1105
+ const [pending, setPending] = React5.useState([]);
1106
+ async function revoke(token) {
1107
+ if (pending.includes(token.id)) {
1108
+ return;
1109
+ }
1110
+ setPending((current) => [...current, token.id]);
1111
+ const result = await credentialRequest("DELETE", token.revoke_href, void 0, csrfToken);
1112
+ if (!result.ok) {
1113
+ setPending((current) => current.filter((id) => id !== token.id));
1114
+ setError(result.message);
1115
+ onError?.("api-tokens", result.message);
1116
+ return;
1117
+ }
1118
+ setError(null);
1119
+ removeLocally("tokens", token.id);
1120
+ onSuccess?.("API token revoked.");
1121
+ await reload();
1122
+ setPending((current) => current.filter((id) => id !== token.id));
1123
+ }
1124
+ return /* @__PURE__ */ (0, import_jsx_runtime4.jsxs)("section", { style: { display: "grid", gap: "0.75rem", minWidth: 0 }, children: [
1125
+ /* @__PURE__ */ (0, import_jsx_runtime4.jsx)("h3", { children: "API tokens" }),
1126
+ index.issue_token_href !== null && /* @__PURE__ */ (0, import_jsx_runtime4.jsxs)("form", { onSubmit: create, style: { display: "grid", gap: "0.75rem" }, children: [
1127
+ /* @__PURE__ */ (0, import_jsx_runtime4.jsxs)("div", { style: { display: "grid", gap: "0.25rem" }, children: [
1128
+ /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(Label, { htmlFor: "api-token-name", children: "Token name" }),
1129
+ /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(Input, { id: "api-token-name", value: name, maxLength: 120, onChange: (event) => setName(event.target.value) })
1130
+ ] }),
1131
+ /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(ScopePicker, { idPrefix: "api-token-scope", scopes: index.scopes, selected: scopes, onChange: setScopes }),
1132
+ /* @__PURE__ */ (0, import_jsx_runtime4.jsxs)("fieldset", { style: { display: "grid", gap: "0.25rem", border: 0, padding: 0 }, children: [
1133
+ /* @__PURE__ */ (0, import_jsx_runtime4.jsx)("legend", { children: "Expires after" }),
1134
+ index.token_lifetimes.map((spec) => /* @__PURE__ */ (0, import_jsx_runtime4.jsxs)("label", { children: [
1135
+ /* @__PURE__ */ (0, import_jsx_runtime4.jsx)("input", { type: "radio", name: "api-token-lifetime", checked: lifetime === spec, onChange: () => setLifetime(spec) }),
1136
+ " ",
1137
+ describeDuration(spec)
1138
+ ] }, spec))
1139
+ ] }),
1140
+ /* @__PURE__ */ (0, import_jsx_runtime4.jsx)("div", { children: /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(Button, { type: "submit", disabled: busy || name.trim() === "" || scopes.length === 0 || lifetime === "", children: "Create API token" }) })
1141
+ ] }),
1142
+ error !== null && /* @__PURE__ */ (0, import_jsx_runtime4.jsx)("p", { role: "alert", children: error }),
1143
+ /* @__PURE__ */ (0, import_jsx_runtime4.jsx)("ul", { style: { display: "grid", gap: "0.5rem", listStyle: "none", padding: 0, margin: 0, minWidth: 0 }, children: index.tokens.map((token) => /* @__PURE__ */ (0, import_jsx_runtime4.jsxs)("li", { style: { minWidth: 0, overflowWrap: "anywhere" }, children: [
1144
+ /* @__PURE__ */ (0, import_jsx_runtime4.jsx)("strong", { children: token.name }),
1145
+ " \xB7 ",
1146
+ token.scopes.join(", "),
1147
+ token.expires_at !== null && /* @__PURE__ */ (0, import_jsx_runtime4.jsxs)(import_jsx_runtime4.Fragment, { children: [
1148
+ " \xB7 expires ",
1149
+ new Date(token.expires_at).toLocaleString()
1150
+ ] }),
1151
+ " ",
1152
+ /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(Button, { type: "button", disabled: pending.includes(token.id), onClick: () => void revoke(token), children: "Revoke" })
1153
+ ] }, token.id)) })
1154
+ ] });
1155
+ }
1156
+ function AppSection({ index, components, csrfToken, onIssued, reload, onSuccess, onError, removeLocally }) {
1157
+ const { Button, Input, Label } = resolveAuthComponents(components);
1158
+ const [name, setName] = React5.useState("");
1159
+ const [redirects, setRedirects] = React5.useState("");
1160
+ const [confidential, setConfidential] = React5.useState(true);
1161
+ const [scopes, setScopes] = React5.useState([]);
1162
+ const [busy, setBusy] = React5.useState(false);
1163
+ const [error, setError] = React5.useState(null);
1164
+ const redirectUris = redirects.split("\n").map((line) => line.trim()).filter((line) => line !== "");
1165
+ async function register(event) {
1166
+ event.preventDefault();
1167
+ if (index.register_app_href === null) {
1168
+ return;
1169
+ }
1170
+ setBusy(true);
1171
+ const result = await credentialRequest(
1172
+ "POST",
1173
+ index.register_app_href,
1174
+ { name, redirect_uris: redirectUris, confidential, scopes },
1175
+ csrfToken
1176
+ );
1177
+ setBusy(false);
1178
+ if (!result.ok) {
1179
+ setError(result.message);
1180
+ onError?.("oauth-apps", result.message);
1181
+ return;
1182
+ }
1183
+ setError(null);
1184
+ setName("");
1185
+ setRedirects("");
1186
+ setScopes([]);
1187
+ onIssued(result.data);
1188
+ onSuccess?.("OAuth app registered.");
1189
+ await reload();
1190
+ }
1191
+ const [pending, setPending] = React5.useState([]);
1192
+ async function remove(app) {
1193
+ if (pending.includes(app.id)) {
1194
+ return;
1195
+ }
1196
+ setPending((current) => [...current, app.id]);
1197
+ const result = await credentialRequest("DELETE", app.delete_href, void 0, csrfToken);
1198
+ if (!result.ok) {
1199
+ setPending((current) => current.filter((id) => id !== app.id));
1200
+ setError(result.message);
1201
+ onError?.("oauth-apps", result.message);
1202
+ return;
1203
+ }
1204
+ setError(null);
1205
+ removeLocally("apps", app.id);
1206
+ onSuccess?.("OAuth app deleted and its tokens revoked.");
1207
+ await reload();
1208
+ setPending((current) => current.filter((id) => id !== app.id));
1209
+ }
1210
+ return /* @__PURE__ */ (0, import_jsx_runtime4.jsxs)("section", { style: { display: "grid", gap: "0.75rem", minWidth: 0 }, children: [
1211
+ /* @__PURE__ */ (0, import_jsx_runtime4.jsx)("h3", { children: "OAuth apps" }),
1212
+ index.register_app_href !== null && /* @__PURE__ */ (0, import_jsx_runtime4.jsxs)("form", { onSubmit: register, style: { display: "grid", gap: "0.75rem" }, children: [
1213
+ /* @__PURE__ */ (0, import_jsx_runtime4.jsxs)("div", { style: { display: "grid", gap: "0.25rem" }, children: [
1214
+ /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(Label, { htmlFor: "oauth-app-name", children: "App name" }),
1215
+ /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(Input, { id: "oauth-app-name", value: name, maxLength: 120, onChange: (event) => setName(event.target.value) })
1216
+ ] }),
1217
+ /* @__PURE__ */ (0, import_jsx_runtime4.jsxs)("div", { style: { display: "grid", gap: "0.25rem" }, children: [
1218
+ /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(Label, { htmlFor: "oauth-app-redirects", children: "Redirect URIs (one per line)" }),
1219
+ /* @__PURE__ */ (0, import_jsx_runtime4.jsx)("textarea", { id: "oauth-app-redirects", rows: 3, value: redirects, onChange: (event) => setRedirects(event.target.value) })
1220
+ ] }),
1221
+ /* @__PURE__ */ (0, import_jsx_runtime4.jsxs)("fieldset", { style: { display: "grid", gap: "0.25rem", border: 0, padding: 0 }, children: [
1222
+ /* @__PURE__ */ (0, import_jsx_runtime4.jsx)("legend", { children: "Client type" }),
1223
+ /* @__PURE__ */ (0, import_jsx_runtime4.jsxs)("label", { children: [
1224
+ /* @__PURE__ */ (0, import_jsx_runtime4.jsx)("input", { type: "radio", name: "oauth-app-type", checked: confidential, onChange: () => setConfidential(true) }),
1225
+ " Confidential: the app keeps a client secret on its server"
1226
+ ] }),
1227
+ /* @__PURE__ */ (0, import_jsx_runtime4.jsxs)("label", { children: [
1228
+ /* @__PURE__ */ (0, import_jsx_runtime4.jsx)("input", { type: "radio", name: "oauth-app-type", checked: !confidential, onChange: () => setConfidential(false) }),
1229
+ " Public: no secret, PKCE only"
1230
+ ] })
1231
+ ] }),
1232
+ /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(ScopePicker, { idPrefix: "oauth-app-scope", scopes: index.scopes, selected: scopes, onChange: setScopes }),
1233
+ /* @__PURE__ */ (0, import_jsx_runtime4.jsx)("div", { children: /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(Button, { type: "submit", disabled: busy || name.trim() === "" || redirectUris.length === 0 || scopes.length === 0, children: "Register OAuth app" }) })
1234
+ ] }),
1235
+ error !== null && /* @__PURE__ */ (0, import_jsx_runtime4.jsx)("p", { role: "alert", children: error }),
1236
+ /* @__PURE__ */ (0, import_jsx_runtime4.jsx)("ul", { style: { display: "grid", gap: "0.5rem", listStyle: "none", padding: 0, margin: 0, minWidth: 0 }, children: index.apps.map((app) => /* @__PURE__ */ (0, import_jsx_runtime4.jsxs)("li", { style: { minWidth: 0, overflowWrap: "anywhere" }, children: [
1237
+ /* @__PURE__ */ (0, import_jsx_runtime4.jsx)("strong", { children: app.name }),
1238
+ " \xB7 client ID ",
1239
+ /* @__PURE__ */ (0, import_jsx_runtime4.jsx)("code", { children: app.id }),
1240
+ " \xB7 ",
1241
+ app.confidential ? "confidential" : "public",
1242
+ /* @__PURE__ */ (0, import_jsx_runtime4.jsx)("br", {}),
1243
+ app.redirect_uris.join(", "),
1244
+ /* @__PURE__ */ (0, import_jsx_runtime4.jsx)("br", {}),
1245
+ "May request: ",
1246
+ app.scopes.join(", "),
1247
+ " ",
1248
+ /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(Button, { type: "button", disabled: pending.includes(app.id), onClick: () => void remove(app), children: "Delete" })
1249
+ ] }, app.id)) })
1250
+ ] });
1251
+ }
1252
+ function ScopePicker({
1253
+ idPrefix,
1254
+ scopes,
1255
+ selected,
1256
+ onChange
1257
+ }) {
1258
+ return /* @__PURE__ */ (0, import_jsx_runtime4.jsxs)("fieldset", { style: { display: "grid", gap: "0.25rem", border: 0, padding: 0, minWidth: 0 }, children: [
1259
+ /* @__PURE__ */ (0, import_jsx_runtime4.jsx)("legend", { children: "Permissions" }),
1260
+ scopes.map((scope) => {
1261
+ const id = `${idPrefix}-${scope.id}`;
1262
+ return /* @__PURE__ */ (0, import_jsx_runtime4.jsxs)("label", { htmlFor: id, style: { overflowWrap: "anywhere" }, children: [
1263
+ /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(
1264
+ "input",
1265
+ {
1266
+ id,
1267
+ type: "checkbox",
1268
+ checked: selected.includes(scope.id),
1269
+ onChange: (event) => onChange(event.target.checked ? [...selected, scope.id] : selected.filter((value) => value !== scope.id))
1270
+ }
1271
+ ),
1272
+ " ",
1273
+ /* @__PURE__ */ (0, import_jsx_runtime4.jsx)("code", { children: scope.id }),
1274
+ " ",
1275
+ scope.description
1276
+ ] }, scope.id);
1277
+ })
1278
+ ] });
1279
+ }
1280
+ function IssuedNotice({
1281
+ issued,
1282
+ components,
1283
+ onDismiss
1284
+ }) {
1285
+ const { Button } = resolveAuthComponents(components);
1286
+ const values = issued.kind === "token" ? [{ label: "API token", url: issued.token }] : [
1287
+ { label: "Client ID", url: issued.client_id },
1288
+ ...issued.client_secret !== null ? [{ label: "Client secret", url: issued.client_secret }] : []
1289
+ ];
1290
+ return /* @__PURE__ */ (0, import_jsx_runtime4.jsxs)("div", { role: "status", style: { display: "grid", gap: "0.5rem", minWidth: 0 }, children: [
1291
+ /* @__PURE__ */ (0, import_jsx_runtime4.jsxs)("p", { style: { overflowWrap: "anywhere" }, children: [
1292
+ issued.kind === "token" ? `API token \u201C${issued.name}\u201D created.` : `OAuth app \u201C${issued.name}\u201D registered.`,
1293
+ " Copy it now: it will not be shown again."
1294
+ ] }),
1295
+ values.map((value) => /* @__PURE__ */ (0, import_jsx_runtime4.jsxs)("div", { style: { minWidth: 0, overflowWrap: "anywhere" }, children: [
1296
+ value.label,
1297
+ ": ",
1298
+ /* @__PURE__ */ (0, import_jsx_runtime4.jsx)("code", { children: value.url }),
1299
+ " ",
1300
+ /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(CopyButton, { text: value.url, label: value.label, components })
1301
+ ] }, value.label)),
1302
+ /* @__PURE__ */ (0, import_jsx_runtime4.jsx)("div", { children: /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(Button, { type: "button", onClick: onDismiss, children: "Done" }) })
1303
+ ] });
1304
+ }
1305
+ function CopyButton({ text, label, components }) {
1306
+ const { Button } = resolveAuthComponents(components);
1307
+ const [state, setState] = React5.useState("idle");
1308
+ return /* @__PURE__ */ (0, import_jsx_runtime4.jsxs)(import_jsx_runtime4.Fragment, { children: [
1309
+ /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(
1310
+ Button,
1311
+ {
1312
+ type: "button",
1313
+ "aria-label": `Copy ${label}`,
1314
+ onClick: async () => {
1315
+ if (typeof navigator === "undefined" || typeof navigator.clipboard?.writeText !== "function") {
1316
+ setState("failed");
1317
+ return;
1318
+ }
1319
+ try {
1320
+ await navigator.clipboard.writeText(text);
1321
+ setState("copied");
1322
+ } catch {
1323
+ setState("failed");
1324
+ }
1325
+ },
1326
+ children: state === "copied" ? "Copied" : "Copy"
1327
+ }
1328
+ ),
1329
+ state === "failed" && /* @__PURE__ */ (0, import_jsx_runtime4.jsx)("span", { role: "status", children: " Copying is unavailable here; select the text and copy it manually." })
1330
+ ] });
1331
+ }
1332
+ function describeDuration(spec) {
1333
+ const match = /^P(?:(\d+)Y)?(?:(\d+)M)?(?:(\d+)W)?(?:(\d+)D)?(?:T(?:(\d+)H)?(?:(\d+)M)?)?$/.exec(spec);
1334
+ if (!match) {
1335
+ return spec;
1336
+ }
1337
+ const units = ["year", "month", "week", "day", "hour", "minute"];
1338
+ const parts = match.slice(1).map((value, position) => value ? `${Number(value)} ${units[position]}${Number(value) === 1 ? "" : "s"}` : null).filter((part) => part !== null);
1339
+ return parts.length > 0 ? parts.join(" ") : spec;
1340
+ }
1341
+ async function credentialRequest(method, url, body, csrfToken) {
1342
+ let response;
1343
+ try {
1344
+ response = await fetch(url, {
1345
+ method,
1346
+ credentials: "same-origin",
1347
+ headers: {
1348
+ Accept: "application/json",
1349
+ ...body !== void 0 ? { "Content-Type": "application/json" } : {},
1350
+ ...method !== "GET" ? { "X-CSRF-TOKEN": getCsrfToken(csrfToken) } : {}
1351
+ },
1352
+ body: body !== void 0 ? JSON.stringify(body) : void 0
1353
+ });
1354
+ } catch {
1355
+ return { ok: false, status: 0, message: "The server could not be reached. Check the connection and try again." };
1356
+ }
1357
+ const payload = await response.json().catch(() => null);
1358
+ if (response.ok) {
1359
+ const data = typeof payload === "object" && payload !== null && "data" in payload ? payload.data : payload;
1360
+ return { ok: true, status: response.status, data };
1361
+ }
1362
+ return { ok: false, status: response.status, message: refusalMessage(response.status, payload) };
1363
+ }
1364
+ function refusalMessage(status, payload) {
1365
+ if (status === 401 || status === 419) {
1366
+ return "Your session has expired. Reload the page and sign in again.";
1367
+ }
1368
+ if (typeof payload === "object" && payload !== null) {
1369
+ const errors = payload.errors;
1370
+ if (errors && typeof errors === "object") {
1371
+ const first = Object.values(errors)[0];
1372
+ if (Array.isArray(first) && typeof first[0] === "string") {
1373
+ return first[0];
1374
+ }
1375
+ }
1376
+ const message = payload.message;
1377
+ if (typeof message === "string" && message !== "") {
1378
+ return message;
1379
+ }
1380
+ }
1381
+ if (status === 403) {
1382
+ return "You do not have permission to do that.";
1383
+ }
1384
+ if (status === 404) {
1385
+ return "That credential no longer exists, or creating credentials is unavailable right now.";
1386
+ }
1387
+ return "That action could not be completed.";
1388
+ }
998
1389
  // Annotate the CommonJS export names for ESM import in node:
999
1390
  0 && (module.exports = {
1391
+ ApiCredentialsSection,
1000
1392
  ChangePasswordForm,
1001
1393
  LoginForm,
1002
1394
  PasskeyLoginButton,
@@ -1008,6 +1400,7 @@ function relyingApplicationsFrom(value) {
1008
1400
  arrayBufferToBase64url,
1009
1401
  authenticateWithPasskey,
1010
1402
  base64urlToArrayBuffer,
1403
+ describeDuration,
1011
1404
  getCsrfToken,
1012
1405
  getDefaultPasskeyName,
1013
1406
  isAbortError,
package/dist/index.d.cts CHANGED
@@ -214,4 +214,73 @@ declare function isConditionalMediationAvailable(): Promise<boolean>;
214
214
  declare function authenticateWithPasskey({ endpoints, mediation, signal }?: AuthenticateWithPasskeyOptions): Promise<PasskeyAuthenticationResult>;
215
215
  declare function registerPasskey({ endpoints, name, signal }?: RegisterPasskeyOptions): Promise<PasskeyRegistrationResult>;
216
216
 
217
- export { type AuthButtonComponent, type AuthButtonComponentInput, type AuthButtonComponentProps, type AuthButtonSize, type AuthButtonVariant, type AuthComponentInput, type AuthComponentOverrides, type AuthComponentSet, type AuthComponentSuperset, type AuthComponents, type AuthContainerComponentProps, type AuthEndpointConfig, type AuthInputComponentProps, type AuthJsonResponse, type AuthLabelComponentProps, type AuthSignupField, type AuthSignupValues, type AuthValidationErrors, ChangePasswordForm, LoginForm, type LoginFormProps, type LoginRememberMeCheckboxProps, type Passkey, PasskeyLoginButton, PasskeySection, PasswordResetRequestForm, type RelyingApplication, ResetPasswordForm, SignupForm, TwoFactorForm, arrayBufferToBase64url, authenticateWithPasskey, base64urlToArrayBuffer, getCsrfToken, getDefaultPasskeyName, isAbortError, isConditionalMediationAvailable, registerPasskey, relyingApplicationsFrom, safeApplicationHref };
217
+ interface ApiCredentialScope {
218
+ id: string;
219
+ description: string;
220
+ }
221
+ interface ApiCredentialToken {
222
+ id: string;
223
+ name: string;
224
+ scopes: string[];
225
+ created_at: string | null;
226
+ expires_at: string | null;
227
+ revoke_href: string;
228
+ }
229
+ interface ApiCredentialApp {
230
+ id: string;
231
+ name: string;
232
+ confidential: boolean;
233
+ redirect_uris: string[];
234
+ scopes: string[];
235
+ created_at: string | null;
236
+ delete_href: string;
237
+ }
238
+ /** The server's index response (`data`): every URL is finished; this component assembles none. */
239
+ interface ApiCredentialIndex {
240
+ scopes: ApiCredentialScope[];
241
+ token_lifetimes: string[];
242
+ /** Null while issuing is unavailable (the OAuth server is switched off). Revocation stays available. */
243
+ issue_token_href: string | null;
244
+ register_app_href: string | null;
245
+ tokens: ApiCredentialToken[];
246
+ apps: ApiCredentialApp[];
247
+ }
248
+ type IssuedApiCredential = {
249
+ kind: 'token';
250
+ name: string;
251
+ token: string;
252
+ expires_at?: string;
253
+ } | {
254
+ kind: 'app';
255
+ name: string;
256
+ client_id: string;
257
+ client_secret: string | null;
258
+ };
259
+ interface ApiCredentialEndpointLink {
260
+ label: string;
261
+ url: string;
262
+ }
263
+ interface ApiCredentialsSectionProps {
264
+ /** The credential service's index URL (GET). */
265
+ indexUrl: string;
266
+ components: AuthComponentInput;
267
+ /** Values a connector needs: the OpenAPI document, API base, OAuth authorize/token URLs, MCP URL. */
268
+ links?: ApiCredentialEndpointLink[];
269
+ csrfToken?: string;
270
+ onSuccess?: (message: string) => void;
271
+ onError?: (field: string, message: string) => void;
272
+ }
273
+ /**
274
+ * A person's credentials for apps that use the API: personal API tokens (for
275
+ * connectors that ask for a key) and OAuth apps (for connectors that run the
276
+ * authorization-code flow).
277
+ *
278
+ * Each secret arrives once, in the response that created it, and lives only
279
+ * in this component's memory; afterwards only the lists are reloaded, so it is
280
+ * never part of page props or browser history.
281
+ */
282
+ declare function ApiCredentialsSection({ indexUrl, components, links, csrfToken, onSuccess, onError }: ApiCredentialsSectionProps): React.JSX.Element;
283
+ /** PT4H → "4 hours", P30D → "30 days", P1Y → "1 year". Unknown shapes are shown as given. */
284
+ declare function describeDuration(spec: string): string;
285
+
286
+ export { type ApiCredentialApp, type ApiCredentialEndpointLink, type ApiCredentialIndex, type ApiCredentialScope, type ApiCredentialToken, ApiCredentialsSection, type ApiCredentialsSectionProps, type AuthButtonComponent, type AuthButtonComponentInput, type AuthButtonComponentProps, type AuthButtonSize, type AuthButtonVariant, type AuthComponentInput, type AuthComponentOverrides, type AuthComponentSet, type AuthComponentSuperset, type AuthComponents, type AuthContainerComponentProps, type AuthEndpointConfig, type AuthInputComponentProps, type AuthJsonResponse, type AuthLabelComponentProps, type AuthSignupField, type AuthSignupValues, type AuthValidationErrors, ChangePasswordForm, type IssuedApiCredential, LoginForm, type LoginFormProps, type LoginRememberMeCheckboxProps, type Passkey, PasskeyLoginButton, PasskeySection, PasswordResetRequestForm, type RelyingApplication, ResetPasswordForm, SignupForm, TwoFactorForm, arrayBufferToBase64url, authenticateWithPasskey, base64urlToArrayBuffer, describeDuration, getCsrfToken, getDefaultPasskeyName, isAbortError, isConditionalMediationAvailable, registerPasskey, relyingApplicationsFrom, safeApplicationHref };
package/dist/index.d.ts CHANGED
@@ -214,4 +214,73 @@ declare function isConditionalMediationAvailable(): Promise<boolean>;
214
214
  declare function authenticateWithPasskey({ endpoints, mediation, signal }?: AuthenticateWithPasskeyOptions): Promise<PasskeyAuthenticationResult>;
215
215
  declare function registerPasskey({ endpoints, name, signal }?: RegisterPasskeyOptions): Promise<PasskeyRegistrationResult>;
216
216
 
217
- export { type AuthButtonComponent, type AuthButtonComponentInput, type AuthButtonComponentProps, type AuthButtonSize, type AuthButtonVariant, type AuthComponentInput, type AuthComponentOverrides, type AuthComponentSet, type AuthComponentSuperset, type AuthComponents, type AuthContainerComponentProps, type AuthEndpointConfig, type AuthInputComponentProps, type AuthJsonResponse, type AuthLabelComponentProps, type AuthSignupField, type AuthSignupValues, type AuthValidationErrors, ChangePasswordForm, LoginForm, type LoginFormProps, type LoginRememberMeCheckboxProps, type Passkey, PasskeyLoginButton, PasskeySection, PasswordResetRequestForm, type RelyingApplication, ResetPasswordForm, SignupForm, TwoFactorForm, arrayBufferToBase64url, authenticateWithPasskey, base64urlToArrayBuffer, getCsrfToken, getDefaultPasskeyName, isAbortError, isConditionalMediationAvailable, registerPasskey, relyingApplicationsFrom, safeApplicationHref };
217
+ interface ApiCredentialScope {
218
+ id: string;
219
+ description: string;
220
+ }
221
+ interface ApiCredentialToken {
222
+ id: string;
223
+ name: string;
224
+ scopes: string[];
225
+ created_at: string | null;
226
+ expires_at: string | null;
227
+ revoke_href: string;
228
+ }
229
+ interface ApiCredentialApp {
230
+ id: string;
231
+ name: string;
232
+ confidential: boolean;
233
+ redirect_uris: string[];
234
+ scopes: string[];
235
+ created_at: string | null;
236
+ delete_href: string;
237
+ }
238
+ /** The server's index response (`data`): every URL is finished; this component assembles none. */
239
+ interface ApiCredentialIndex {
240
+ scopes: ApiCredentialScope[];
241
+ token_lifetimes: string[];
242
+ /** Null while issuing is unavailable (the OAuth server is switched off). Revocation stays available. */
243
+ issue_token_href: string | null;
244
+ register_app_href: string | null;
245
+ tokens: ApiCredentialToken[];
246
+ apps: ApiCredentialApp[];
247
+ }
248
+ type IssuedApiCredential = {
249
+ kind: 'token';
250
+ name: string;
251
+ token: string;
252
+ expires_at?: string;
253
+ } | {
254
+ kind: 'app';
255
+ name: string;
256
+ client_id: string;
257
+ client_secret: string | null;
258
+ };
259
+ interface ApiCredentialEndpointLink {
260
+ label: string;
261
+ url: string;
262
+ }
263
+ interface ApiCredentialsSectionProps {
264
+ /** The credential service's index URL (GET). */
265
+ indexUrl: string;
266
+ components: AuthComponentInput;
267
+ /** Values a connector needs: the OpenAPI document, API base, OAuth authorize/token URLs, MCP URL. */
268
+ links?: ApiCredentialEndpointLink[];
269
+ csrfToken?: string;
270
+ onSuccess?: (message: string) => void;
271
+ onError?: (field: string, message: string) => void;
272
+ }
273
+ /**
274
+ * A person's credentials for apps that use the API: personal API tokens (for
275
+ * connectors that ask for a key) and OAuth apps (for connectors that run the
276
+ * authorization-code flow).
277
+ *
278
+ * Each secret arrives once, in the response that created it, and lives only
279
+ * in this component's memory; afterwards only the lists are reloaded, so it is
280
+ * never part of page props or browser history.
281
+ */
282
+ declare function ApiCredentialsSection({ indexUrl, components, links, csrfToken, onSuccess, onError }: ApiCredentialsSectionProps): React.JSX.Element;
283
+ /** PT4H → "4 hours", P30D → "30 days", P1Y → "1 year". Unknown shapes are shown as given. */
284
+ declare function describeDuration(spec: string): string;
285
+
286
+ export { type ApiCredentialApp, type ApiCredentialEndpointLink, type ApiCredentialIndex, type ApiCredentialScope, type ApiCredentialToken, ApiCredentialsSection, type ApiCredentialsSectionProps, type AuthButtonComponent, type AuthButtonComponentInput, type AuthButtonComponentProps, type AuthButtonSize, type AuthButtonVariant, type AuthComponentInput, type AuthComponentOverrides, type AuthComponentSet, type AuthComponentSuperset, type AuthComponents, type AuthContainerComponentProps, type AuthEndpointConfig, type AuthInputComponentProps, type AuthJsonResponse, type AuthLabelComponentProps, type AuthSignupField, type AuthSignupValues, type AuthValidationErrors, ChangePasswordForm, type IssuedApiCredential, LoginForm, type LoginFormProps, type LoginRememberMeCheckboxProps, type Passkey, PasskeyLoginButton, PasskeySection, PasswordResetRequestForm, type RelyingApplication, ResetPasswordForm, SignupForm, TwoFactorForm, arrayBufferToBase64url, authenticateWithPasskey, base64urlToArrayBuffer, describeDuration, getCsrfToken, getDefaultPasskeyName, isAbortError, isConditionalMediationAvailable, registerPasskey, relyingApplicationsFrom, safeApplicationHref };
package/dist/index.js CHANGED
@@ -942,7 +942,397 @@ function relyingApplicationsFrom(value) {
942
942
  return href === null ? [] : [{ key, name: name.trim(), url: href }];
943
943
  });
944
944
  }
945
+
946
+ // src/api-credentials-section.tsx
947
+ import * as React5 from "react";
948
+ import { Fragment, jsx as jsx4, jsxs as jsxs4 } from "react/jsx-runtime";
949
+ function ApiCredentialsSection({ indexUrl, components, links = [], csrfToken, onSuccess, onError }) {
950
+ const { Card, CardContent, CardDescription, CardHeader, CardTitle } = resolveAuthComponents(components);
951
+ const [index, setIndex] = React5.useState(null);
952
+ const [issued, setIssued] = React5.useState([]);
953
+ const issuedKey = React5.useRef(0);
954
+ const addIssued = React5.useCallback((credential) => {
955
+ issuedKey.current += 1;
956
+ const key = issuedKey.current;
957
+ setIssued((current) => [...current, { key, credential }]);
958
+ }, []);
959
+ const [loadError, setLoadError] = React5.useState(null);
960
+ const onErrorRef = React5.useRef(onError);
961
+ onErrorRef.current = onError;
962
+ const generation = React5.useRef(0);
963
+ const context = React5.useRef({ indexUrl, csrfToken });
964
+ context.current = { indexUrl, csrfToken };
965
+ const reload = React5.useCallback(async () => {
966
+ generation.current += 1;
967
+ const mine = generation.current;
968
+ const { indexUrl: url, csrfToken: token } = context.current;
969
+ const result = await credentialRequest("GET", url, void 0, token);
970
+ if (mine !== generation.current) {
971
+ return;
972
+ }
973
+ if (result.ok) {
974
+ setIndex(result.data);
975
+ setLoadError(null);
976
+ } else {
977
+ setLoadError(result.message);
978
+ onErrorRef.current?.("api-credentials", result.message);
979
+ }
980
+ }, []);
981
+ React5.useEffect(() => {
982
+ setIndex(null);
983
+ void reload();
984
+ }, [indexUrl, csrfToken, reload]);
985
+ const removeLocally = React5.useCallback((list, id) => {
986
+ setIndex(
987
+ (current) => current === null ? current : list === "tokens" ? { ...current, tokens: current.tokens.filter((token) => token.id !== id) } : { ...current, apps: current.apps.filter((app) => app.id !== id) }
988
+ );
989
+ }, []);
990
+ const shared = { components, csrfToken, onError, onSuccess, removeLocally };
991
+ return /* @__PURE__ */ jsxs4(Card, { children: [
992
+ /* @__PURE__ */ jsxs4(CardHeader, { children: [
993
+ /* @__PURE__ */ jsx4(CardTitle, { children: "API access" }),
994
+ /* @__PURE__ */ jsx4(CardDescription, { children: "Connect apps that use the API. Register an OAuth app for apps that sign you in, or create an API token for apps that ask for a key. Each carries only the permissions you choose, and never more than your own access." })
995
+ ] }),
996
+ /* @__PURE__ */ jsx4(CardContent, { children: /* @__PURE__ */ jsxs4("div", { style: { display: "grid", gap: "1.5rem", minWidth: 0 }, children: [
997
+ links.length > 0 && /* @__PURE__ */ jsx4("dl", { style: { display: "grid", gap: "0.5rem", minWidth: 0 }, children: links.map((link) => /* @__PURE__ */ jsxs4("div", { style: { minWidth: 0 }, children: [
998
+ /* @__PURE__ */ jsx4("dt", { children: link.label }),
999
+ /* @__PURE__ */ jsxs4("dd", { style: { margin: 0, overflowWrap: "anywhere" }, children: [
1000
+ /* @__PURE__ */ jsx4("code", { children: link.url }),
1001
+ " ",
1002
+ /* @__PURE__ */ jsx4(CopyButton, { text: link.url, label: link.label, components })
1003
+ ] })
1004
+ ] }, link.label)) }),
1005
+ issued.map(({ key, credential }) => /* @__PURE__ */ jsx4(
1006
+ IssuedNotice,
1007
+ {
1008
+ issued: credential,
1009
+ components,
1010
+ onDismiss: () => setIssued((current) => current.filter((entry) => entry.key !== key))
1011
+ },
1012
+ key
1013
+ )),
1014
+ loadError !== null && /* @__PURE__ */ jsx4("p", { role: "alert", children: loadError }),
1015
+ index !== null && /* @__PURE__ */ jsxs4(Fragment, { children: [
1016
+ (index.issue_token_href === null || index.register_app_href === null) && /* @__PURE__ */ jsx4("p", { role: "status", children: "Creating new credentials is unavailable right now. You can still revoke existing ones." }),
1017
+ /* @__PURE__ */ jsx4(TokenSection, { index, ...shared, onIssued: addIssued, reload }),
1018
+ /* @__PURE__ */ jsx4(AppSection, { index, ...shared, onIssued: addIssued, reload })
1019
+ ] })
1020
+ ] }) })
1021
+ ] });
1022
+ }
1023
+ function TokenSection({ index, components, csrfToken, onIssued, reload, onSuccess, onError, removeLocally }) {
1024
+ const { Button, Input, Label } = resolveAuthComponents(components);
1025
+ const [name, setName] = React5.useState("");
1026
+ const [scopes, setScopes] = React5.useState([]);
1027
+ const [lifetime, setLifetime] = React5.useState(index.token_lifetimes[0] ?? "");
1028
+ const [busy, setBusy] = React5.useState(false);
1029
+ const [error, setError] = React5.useState(null);
1030
+ async function create(event) {
1031
+ event.preventDefault();
1032
+ if (index.issue_token_href === null) {
1033
+ return;
1034
+ }
1035
+ setBusy(true);
1036
+ const result = await credentialRequest("POST", index.issue_token_href, { name, scopes, lifetime }, csrfToken);
1037
+ setBusy(false);
1038
+ if (!result.ok) {
1039
+ setError(result.message);
1040
+ onError?.("api-tokens", result.message);
1041
+ return;
1042
+ }
1043
+ setError(null);
1044
+ setName("");
1045
+ setScopes([]);
1046
+ onIssued(result.data);
1047
+ onSuccess?.("API token created.");
1048
+ await reload();
1049
+ }
1050
+ const [pending, setPending] = React5.useState([]);
1051
+ async function revoke(token) {
1052
+ if (pending.includes(token.id)) {
1053
+ return;
1054
+ }
1055
+ setPending((current) => [...current, token.id]);
1056
+ const result = await credentialRequest("DELETE", token.revoke_href, void 0, csrfToken);
1057
+ if (!result.ok) {
1058
+ setPending((current) => current.filter((id) => id !== token.id));
1059
+ setError(result.message);
1060
+ onError?.("api-tokens", result.message);
1061
+ return;
1062
+ }
1063
+ setError(null);
1064
+ removeLocally("tokens", token.id);
1065
+ onSuccess?.("API token revoked.");
1066
+ await reload();
1067
+ setPending((current) => current.filter((id) => id !== token.id));
1068
+ }
1069
+ return /* @__PURE__ */ jsxs4("section", { style: { display: "grid", gap: "0.75rem", minWidth: 0 }, children: [
1070
+ /* @__PURE__ */ jsx4("h3", { children: "API tokens" }),
1071
+ index.issue_token_href !== null && /* @__PURE__ */ jsxs4("form", { onSubmit: create, style: { display: "grid", gap: "0.75rem" }, children: [
1072
+ /* @__PURE__ */ jsxs4("div", { style: { display: "grid", gap: "0.25rem" }, children: [
1073
+ /* @__PURE__ */ jsx4(Label, { htmlFor: "api-token-name", children: "Token name" }),
1074
+ /* @__PURE__ */ jsx4(Input, { id: "api-token-name", value: name, maxLength: 120, onChange: (event) => setName(event.target.value) })
1075
+ ] }),
1076
+ /* @__PURE__ */ jsx4(ScopePicker, { idPrefix: "api-token-scope", scopes: index.scopes, selected: scopes, onChange: setScopes }),
1077
+ /* @__PURE__ */ jsxs4("fieldset", { style: { display: "grid", gap: "0.25rem", border: 0, padding: 0 }, children: [
1078
+ /* @__PURE__ */ jsx4("legend", { children: "Expires after" }),
1079
+ index.token_lifetimes.map((spec) => /* @__PURE__ */ jsxs4("label", { children: [
1080
+ /* @__PURE__ */ jsx4("input", { type: "radio", name: "api-token-lifetime", checked: lifetime === spec, onChange: () => setLifetime(spec) }),
1081
+ " ",
1082
+ describeDuration(spec)
1083
+ ] }, spec))
1084
+ ] }),
1085
+ /* @__PURE__ */ jsx4("div", { children: /* @__PURE__ */ jsx4(Button, { type: "submit", disabled: busy || name.trim() === "" || scopes.length === 0 || lifetime === "", children: "Create API token" }) })
1086
+ ] }),
1087
+ error !== null && /* @__PURE__ */ jsx4("p", { role: "alert", children: error }),
1088
+ /* @__PURE__ */ jsx4("ul", { style: { display: "grid", gap: "0.5rem", listStyle: "none", padding: 0, margin: 0, minWidth: 0 }, children: index.tokens.map((token) => /* @__PURE__ */ jsxs4("li", { style: { minWidth: 0, overflowWrap: "anywhere" }, children: [
1089
+ /* @__PURE__ */ jsx4("strong", { children: token.name }),
1090
+ " \xB7 ",
1091
+ token.scopes.join(", "),
1092
+ token.expires_at !== null && /* @__PURE__ */ jsxs4(Fragment, { children: [
1093
+ " \xB7 expires ",
1094
+ new Date(token.expires_at).toLocaleString()
1095
+ ] }),
1096
+ " ",
1097
+ /* @__PURE__ */ jsx4(Button, { type: "button", disabled: pending.includes(token.id), onClick: () => void revoke(token), children: "Revoke" })
1098
+ ] }, token.id)) })
1099
+ ] });
1100
+ }
1101
+ function AppSection({ index, components, csrfToken, onIssued, reload, onSuccess, onError, removeLocally }) {
1102
+ const { Button, Input, Label } = resolveAuthComponents(components);
1103
+ const [name, setName] = React5.useState("");
1104
+ const [redirects, setRedirects] = React5.useState("");
1105
+ const [confidential, setConfidential] = React5.useState(true);
1106
+ const [scopes, setScopes] = React5.useState([]);
1107
+ const [busy, setBusy] = React5.useState(false);
1108
+ const [error, setError] = React5.useState(null);
1109
+ const redirectUris = redirects.split("\n").map((line) => line.trim()).filter((line) => line !== "");
1110
+ async function register(event) {
1111
+ event.preventDefault();
1112
+ if (index.register_app_href === null) {
1113
+ return;
1114
+ }
1115
+ setBusy(true);
1116
+ const result = await credentialRequest(
1117
+ "POST",
1118
+ index.register_app_href,
1119
+ { name, redirect_uris: redirectUris, confidential, scopes },
1120
+ csrfToken
1121
+ );
1122
+ setBusy(false);
1123
+ if (!result.ok) {
1124
+ setError(result.message);
1125
+ onError?.("oauth-apps", result.message);
1126
+ return;
1127
+ }
1128
+ setError(null);
1129
+ setName("");
1130
+ setRedirects("");
1131
+ setScopes([]);
1132
+ onIssued(result.data);
1133
+ onSuccess?.("OAuth app registered.");
1134
+ await reload();
1135
+ }
1136
+ const [pending, setPending] = React5.useState([]);
1137
+ async function remove(app) {
1138
+ if (pending.includes(app.id)) {
1139
+ return;
1140
+ }
1141
+ setPending((current) => [...current, app.id]);
1142
+ const result = await credentialRequest("DELETE", app.delete_href, void 0, csrfToken);
1143
+ if (!result.ok) {
1144
+ setPending((current) => current.filter((id) => id !== app.id));
1145
+ setError(result.message);
1146
+ onError?.("oauth-apps", result.message);
1147
+ return;
1148
+ }
1149
+ setError(null);
1150
+ removeLocally("apps", app.id);
1151
+ onSuccess?.("OAuth app deleted and its tokens revoked.");
1152
+ await reload();
1153
+ setPending((current) => current.filter((id) => id !== app.id));
1154
+ }
1155
+ return /* @__PURE__ */ jsxs4("section", { style: { display: "grid", gap: "0.75rem", minWidth: 0 }, children: [
1156
+ /* @__PURE__ */ jsx4("h3", { children: "OAuth apps" }),
1157
+ index.register_app_href !== null && /* @__PURE__ */ jsxs4("form", { onSubmit: register, style: { display: "grid", gap: "0.75rem" }, children: [
1158
+ /* @__PURE__ */ jsxs4("div", { style: { display: "grid", gap: "0.25rem" }, children: [
1159
+ /* @__PURE__ */ jsx4(Label, { htmlFor: "oauth-app-name", children: "App name" }),
1160
+ /* @__PURE__ */ jsx4(Input, { id: "oauth-app-name", value: name, maxLength: 120, onChange: (event) => setName(event.target.value) })
1161
+ ] }),
1162
+ /* @__PURE__ */ jsxs4("div", { style: { display: "grid", gap: "0.25rem" }, children: [
1163
+ /* @__PURE__ */ jsx4(Label, { htmlFor: "oauth-app-redirects", children: "Redirect URIs (one per line)" }),
1164
+ /* @__PURE__ */ jsx4("textarea", { id: "oauth-app-redirects", rows: 3, value: redirects, onChange: (event) => setRedirects(event.target.value) })
1165
+ ] }),
1166
+ /* @__PURE__ */ jsxs4("fieldset", { style: { display: "grid", gap: "0.25rem", border: 0, padding: 0 }, children: [
1167
+ /* @__PURE__ */ jsx4("legend", { children: "Client type" }),
1168
+ /* @__PURE__ */ jsxs4("label", { children: [
1169
+ /* @__PURE__ */ jsx4("input", { type: "radio", name: "oauth-app-type", checked: confidential, onChange: () => setConfidential(true) }),
1170
+ " Confidential: the app keeps a client secret on its server"
1171
+ ] }),
1172
+ /* @__PURE__ */ jsxs4("label", { children: [
1173
+ /* @__PURE__ */ jsx4("input", { type: "radio", name: "oauth-app-type", checked: !confidential, onChange: () => setConfidential(false) }),
1174
+ " Public: no secret, PKCE only"
1175
+ ] })
1176
+ ] }),
1177
+ /* @__PURE__ */ jsx4(ScopePicker, { idPrefix: "oauth-app-scope", scopes: index.scopes, selected: scopes, onChange: setScopes }),
1178
+ /* @__PURE__ */ jsx4("div", { children: /* @__PURE__ */ jsx4(Button, { type: "submit", disabled: busy || name.trim() === "" || redirectUris.length === 0 || scopes.length === 0, children: "Register OAuth app" }) })
1179
+ ] }),
1180
+ error !== null && /* @__PURE__ */ jsx4("p", { role: "alert", children: error }),
1181
+ /* @__PURE__ */ jsx4("ul", { style: { display: "grid", gap: "0.5rem", listStyle: "none", padding: 0, margin: 0, minWidth: 0 }, children: index.apps.map((app) => /* @__PURE__ */ jsxs4("li", { style: { minWidth: 0, overflowWrap: "anywhere" }, children: [
1182
+ /* @__PURE__ */ jsx4("strong", { children: app.name }),
1183
+ " \xB7 client ID ",
1184
+ /* @__PURE__ */ jsx4("code", { children: app.id }),
1185
+ " \xB7 ",
1186
+ app.confidential ? "confidential" : "public",
1187
+ /* @__PURE__ */ jsx4("br", {}),
1188
+ app.redirect_uris.join(", "),
1189
+ /* @__PURE__ */ jsx4("br", {}),
1190
+ "May request: ",
1191
+ app.scopes.join(", "),
1192
+ " ",
1193
+ /* @__PURE__ */ jsx4(Button, { type: "button", disabled: pending.includes(app.id), onClick: () => void remove(app), children: "Delete" })
1194
+ ] }, app.id)) })
1195
+ ] });
1196
+ }
1197
+ function ScopePicker({
1198
+ idPrefix,
1199
+ scopes,
1200
+ selected,
1201
+ onChange
1202
+ }) {
1203
+ return /* @__PURE__ */ jsxs4("fieldset", { style: { display: "grid", gap: "0.25rem", border: 0, padding: 0, minWidth: 0 }, children: [
1204
+ /* @__PURE__ */ jsx4("legend", { children: "Permissions" }),
1205
+ scopes.map((scope) => {
1206
+ const id = `${idPrefix}-${scope.id}`;
1207
+ return /* @__PURE__ */ jsxs4("label", { htmlFor: id, style: { overflowWrap: "anywhere" }, children: [
1208
+ /* @__PURE__ */ jsx4(
1209
+ "input",
1210
+ {
1211
+ id,
1212
+ type: "checkbox",
1213
+ checked: selected.includes(scope.id),
1214
+ onChange: (event) => onChange(event.target.checked ? [...selected, scope.id] : selected.filter((value) => value !== scope.id))
1215
+ }
1216
+ ),
1217
+ " ",
1218
+ /* @__PURE__ */ jsx4("code", { children: scope.id }),
1219
+ " ",
1220
+ scope.description
1221
+ ] }, scope.id);
1222
+ })
1223
+ ] });
1224
+ }
1225
+ function IssuedNotice({
1226
+ issued,
1227
+ components,
1228
+ onDismiss
1229
+ }) {
1230
+ const { Button } = resolveAuthComponents(components);
1231
+ const values = issued.kind === "token" ? [{ label: "API token", url: issued.token }] : [
1232
+ { label: "Client ID", url: issued.client_id },
1233
+ ...issued.client_secret !== null ? [{ label: "Client secret", url: issued.client_secret }] : []
1234
+ ];
1235
+ return /* @__PURE__ */ jsxs4("div", { role: "status", style: { display: "grid", gap: "0.5rem", minWidth: 0 }, children: [
1236
+ /* @__PURE__ */ jsxs4("p", { style: { overflowWrap: "anywhere" }, children: [
1237
+ issued.kind === "token" ? `API token \u201C${issued.name}\u201D created.` : `OAuth app \u201C${issued.name}\u201D registered.`,
1238
+ " Copy it now: it will not be shown again."
1239
+ ] }),
1240
+ values.map((value) => /* @__PURE__ */ jsxs4("div", { style: { minWidth: 0, overflowWrap: "anywhere" }, children: [
1241
+ value.label,
1242
+ ": ",
1243
+ /* @__PURE__ */ jsx4("code", { children: value.url }),
1244
+ " ",
1245
+ /* @__PURE__ */ jsx4(CopyButton, { text: value.url, label: value.label, components })
1246
+ ] }, value.label)),
1247
+ /* @__PURE__ */ jsx4("div", { children: /* @__PURE__ */ jsx4(Button, { type: "button", onClick: onDismiss, children: "Done" }) })
1248
+ ] });
1249
+ }
1250
+ function CopyButton({ text, label, components }) {
1251
+ const { Button } = resolveAuthComponents(components);
1252
+ const [state, setState] = React5.useState("idle");
1253
+ return /* @__PURE__ */ jsxs4(Fragment, { children: [
1254
+ /* @__PURE__ */ jsx4(
1255
+ Button,
1256
+ {
1257
+ type: "button",
1258
+ "aria-label": `Copy ${label}`,
1259
+ onClick: async () => {
1260
+ if (typeof navigator === "undefined" || typeof navigator.clipboard?.writeText !== "function") {
1261
+ setState("failed");
1262
+ return;
1263
+ }
1264
+ try {
1265
+ await navigator.clipboard.writeText(text);
1266
+ setState("copied");
1267
+ } catch {
1268
+ setState("failed");
1269
+ }
1270
+ },
1271
+ children: state === "copied" ? "Copied" : "Copy"
1272
+ }
1273
+ ),
1274
+ state === "failed" && /* @__PURE__ */ jsx4("span", { role: "status", children: " Copying is unavailable here; select the text and copy it manually." })
1275
+ ] });
1276
+ }
1277
+ function describeDuration(spec) {
1278
+ const match = /^P(?:(\d+)Y)?(?:(\d+)M)?(?:(\d+)W)?(?:(\d+)D)?(?:T(?:(\d+)H)?(?:(\d+)M)?)?$/.exec(spec);
1279
+ if (!match) {
1280
+ return spec;
1281
+ }
1282
+ const units = ["year", "month", "week", "day", "hour", "minute"];
1283
+ const parts = match.slice(1).map((value, position) => value ? `${Number(value)} ${units[position]}${Number(value) === 1 ? "" : "s"}` : null).filter((part) => part !== null);
1284
+ return parts.length > 0 ? parts.join(" ") : spec;
1285
+ }
1286
+ async function credentialRequest(method, url, body, csrfToken) {
1287
+ let response;
1288
+ try {
1289
+ response = await fetch(url, {
1290
+ method,
1291
+ credentials: "same-origin",
1292
+ headers: {
1293
+ Accept: "application/json",
1294
+ ...body !== void 0 ? { "Content-Type": "application/json" } : {},
1295
+ ...method !== "GET" ? { "X-CSRF-TOKEN": getCsrfToken(csrfToken) } : {}
1296
+ },
1297
+ body: body !== void 0 ? JSON.stringify(body) : void 0
1298
+ });
1299
+ } catch {
1300
+ return { ok: false, status: 0, message: "The server could not be reached. Check the connection and try again." };
1301
+ }
1302
+ const payload = await response.json().catch(() => null);
1303
+ if (response.ok) {
1304
+ const data = typeof payload === "object" && payload !== null && "data" in payload ? payload.data : payload;
1305
+ return { ok: true, status: response.status, data };
1306
+ }
1307
+ return { ok: false, status: response.status, message: refusalMessage(response.status, payload) };
1308
+ }
1309
+ function refusalMessage(status, payload) {
1310
+ if (status === 401 || status === 419) {
1311
+ return "Your session has expired. Reload the page and sign in again.";
1312
+ }
1313
+ if (typeof payload === "object" && payload !== null) {
1314
+ const errors = payload.errors;
1315
+ if (errors && typeof errors === "object") {
1316
+ const first = Object.values(errors)[0];
1317
+ if (Array.isArray(first) && typeof first[0] === "string") {
1318
+ return first[0];
1319
+ }
1320
+ }
1321
+ const message = payload.message;
1322
+ if (typeof message === "string" && message !== "") {
1323
+ return message;
1324
+ }
1325
+ }
1326
+ if (status === 403) {
1327
+ return "You do not have permission to do that.";
1328
+ }
1329
+ if (status === 404) {
1330
+ return "That credential no longer exists, or creating credentials is unavailable right now.";
1331
+ }
1332
+ return "That action could not be completed.";
1333
+ }
945
1334
  export {
1335
+ ApiCredentialsSection,
946
1336
  ChangePasswordForm,
947
1337
  LoginForm,
948
1338
  PasskeyLoginButton,
@@ -954,6 +1344,7 @@ export {
954
1344
  arrayBufferToBase64url,
955
1345
  authenticateWithPasskey,
956
1346
  base64urlToArrayBuffer,
1347
+ describeDuration,
957
1348
  getCsrfToken,
958
1349
  getDefaultPasskeyName,
959
1350
  isAbortError,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "bwh-auth",
3
- "version": "0.3.3",
3
+ "version": "0.4.0",
4
4
  "description": "Shared React auth UI and browser WebAuthn helpers for BWH applications.",
5
5
  "license": "MIT",
6
6
  "type": "module",