loopctl-mcp-server 3.44.0 → 3.46.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.
@@ -0,0 +1,157 @@
1
+ /**
2
+ * `channel_quarantine_list` / `channel_quarantine_release` — `GET /api/v1/channel/posts/quarantined` and
3
+ * `POST /api/v1/channel/posts/:id/release` (`ChannelPostController.quarantined` / `.release`,
4
+ * issue #499), loopctl #872.
5
+ *
6
+ * KEY: both are `role: :user` WITH the hierarchy plus `RequireHumanAnchor`, so an agent or
7
+ * orchestrator key is 403 insufficient_role and an agent-rooted tenant 403
8
+ * custody_tier_required. They travel on LOOPCTL_USER_KEY when set, else the default key (index.js
9
+ * `userKeyApiCall`). Neither is custody surface, so a custody halt does not block them.
10
+ *
11
+ * WHY THE BODIES GO TO A FILE. The quarantine read is the ONE endpoint that returns the full
12
+ * text of posts the secret rescan flagged as carrying a credential shape, and it is gated at
13
+ * user role precisely so that no agent reads one back. A tool result lands in the session
14
+ * transcript, so returning those fields would copy each suspected credential into the
15
+ * transcript of whichever session asked. `api_key_create` keeps a raw key out of the transcript
16
+ * the same way: the full rows are written to `rows_file` (an absolute path that must not exist
17
+ * yet, created 0600 before the request), and the result carries every row with the fields the
18
+ * rescan scans REMOVED — `quarantine_reason` names which of them tripped. A person reads the
19
+ * file, judges, then redacts (`channel_delete`) or releases (`channel_quarantine_release`), and deletes
20
+ * the file.
21
+ *
22
+ * The release answers with the released post; its scanned fields are removed from the result
23
+ * for the same reason (a mistaken release is still a credential), and `channel_get` reads it
24
+ * back. Release refusals: 404, byte-identical, for a post that is missing, another tenant's,
25
+ * malformed or not quarantined; 500 audit_write_failed when the audit entry could not be written
26
+ * (the release rolled back and the post is still quarantined).
27
+ *
28
+ * CHECKED HERE, because the server would answer it WRONGLY rather than refuse: a `limit`
29
+ * outside 1..100 (0 or less reads as the default 25, more is clamped to 100). A `project_id` is
30
+ * an id, or a slug or repo name `ResolveProjectRef` rewrites to one; a reference that resolves
31
+ * to no project is not refused by the server, it matches nothing and answers an empty list, and
32
+ * nothing here can tell that apart from an empty quarantine, so the description says so. A
33
+ * non-UUID post id is refused: it answers the same 404 as a post that is not quarantined.
34
+ */
35
+
36
+ import { isAbsolute } from "node:path";
37
+ import { uuid } from "./delivery-loop.js";
38
+ import { createSecretFile } from "./secret-file.js";
39
+
40
+ // `ChannelPost.secret_fields/1`'s scanned set (`@scanned_text_fields` + `refs`), as the
41
+ // controller's `quarantined_json/1` returns them.
42
+ export const SCANNED_FIELDS = [
43
+ "body",
44
+ "key",
45
+ "session_id",
46
+ "host",
47
+ "to_host",
48
+ "to_capability",
49
+ "idempotency_key",
50
+ "refs",
51
+ ];
52
+
53
+ function refuse(body) {
54
+ return { error: true, status: 0, body };
55
+ }
56
+
57
+ // ONE template literal per builder (see `test/tool-surface.js`).
58
+ export function quarantinedPath(query = "") {
59
+ return `/api/v1/channel/posts/quarantined${query}`;
60
+ }
61
+
62
+ export function releasePath(postId) {
63
+ return `/api/v1/channel/posts/${encodeURIComponent(postId)}/release`;
64
+ }
65
+
66
+ export function withoutScannedFields(row) {
67
+ if (row === null || typeof row !== "object" || Array.isArray(row)) return row;
68
+ const out = {};
69
+ for (const [field, value] of Object.entries(row)) {
70
+ if (!SCANNED_FIELDS.includes(field)) out[field] = value;
71
+ }
72
+ return out;
73
+ }
74
+
75
+ /**
76
+ * `deps.apiCall(method, path, body)` is the user-key caller; `deps.openRows(path)` creates the
77
+ * file and returns `{ writeSecret(text), discardSecret() }` (injected so a test owns the disk it touches).
78
+ */
79
+ export async function listQuarantinedPosts(
80
+ { project_id, limit, rows_file } = {},
81
+ { apiCall, openRows = createSecretFile } = {},
82
+ ) {
83
+ if (project_id != null && (typeof project_id !== "string" || project_id.trim() === "")) {
84
+ return refuse("`project_id` must be a non-empty string: a project's id, slug or repo name.");
85
+ }
86
+
87
+ if (limit != null && !(Number.isInteger(limit) && limit >= 1 && limit <= 100)) {
88
+ return refuse("`limit` must be an integer from 1 to 100 (default 25).");
89
+ }
90
+
91
+ if (typeof rows_file !== "string" || !isAbsolute(rows_file)) {
92
+ return refuse(
93
+ "`rows_file` must be an absolute path that does not exist yet. The quarantined posts' " +
94
+ "full fields are written there (mode 0600) and never returned, because a tool result " +
95
+ "lands in the transcript and these posts were quarantined as suspected credentials.",
96
+ );
97
+ }
98
+
99
+ let sink;
100
+ try {
101
+ sink = openRows(rows_file);
102
+ } catch (error) {
103
+ return refuse(
104
+ `${rows_file} could not be created (${error.code || error.message}); nothing was read. ` +
105
+ "Pass a path that does not exist yet, in a directory that does.",
106
+ );
107
+ }
108
+
109
+ const params = new URLSearchParams();
110
+ if (project_id != null) params.set("project_id", project_id);
111
+ if (limit != null) params.set("limit", String(limit));
112
+ const qs = params.toString();
113
+
114
+ let result;
115
+ try {
116
+ result = await apiCall("GET", quarantinedPath(qs === "" ? "" : `?${qs}`), null);
117
+ } catch (error) {
118
+ sink.discardSecret();
119
+ throw error;
120
+ }
121
+
122
+ if (!result || result.error || !Array.isArray(result.data)) {
123
+ sink.discardSecret();
124
+ return result;
125
+ }
126
+
127
+ try {
128
+ sink.writeSecret(JSON.stringify(result, null, 2) + "\n");
129
+ } catch (error) {
130
+ sink.discardSecret();
131
+ return refuse(
132
+ `${rows_file} could not be written (${error.code || error.message}); the posts were read ` +
133
+ "and are not returned here. Read again with a new rows_file.",
134
+ );
135
+ }
136
+
137
+ return {
138
+ data: result.data.map(withoutScannedFields),
139
+ meta: result.meta,
140
+ rows_file,
141
+ withheld_fields: SCANNED_FIELDS,
142
+ };
143
+ }
144
+
145
+ export async function releaseQuarantinedPost({ post_id } = {}, { apiCall } = {}) {
146
+ const bad = uuid(post_id, "post_id");
147
+ if (bad) return bad;
148
+
149
+ const result = await apiCall("POST", releasePath(post_id), null);
150
+
151
+ if (result && !result.error && result.post) {
152
+ return { ...result, post: withoutScannedFields(result.post), withheld_fields: SCANNED_FIELDS };
153
+ }
154
+
155
+ return result;
156
+ }
157
+
@@ -0,0 +1,141 @@
1
+ /**
2
+ * `cost_trends` / `model_mix` / `agent_model_profile` — `GET /api/v1/analytics/trends`,
3
+ * `GET /api/v1/analytics/model-mix` and `GET /api/v1/analytics/agents/:id/model-profile`
4
+ * (`AnalyticsController`), loopctl #872.
5
+ *
6
+ * KEY: all three are `role: :orchestrator` WITH the hierarchy, so an agent key is 403
7
+ * insufficient_role. They travel on LOOPCTL_ORCH_KEY, else LOOPCTL_USER_KEY, sent verbatim
8
+ * when set (index.js `orchestratorPinnedApiCall`). Read-only; empty data when nothing was
9
+ * reported.
10
+ *
11
+ * `project_id` may be a UUID, a slug or the repo directory name (loopctl resolves it); one that
12
+ * names no project is 422. The model profile answers 404 for an agent that is not this
13
+ * tenant's.
14
+ *
15
+ * CHECKED HERE, because the server would answer them WRONGLY rather than refuse:
16
+ *
17
+ * - `since` / `until` that are not a real `YYYY-MM-DD` date: loopctl DROPS an unparseable
18
+ * date, widening the read to all time;
19
+ * - trends' `granularity` outside daily / weekly: loopctl answers daily for anything else;
20
+ * - trends' `page` / `page_size`: a non-integer is dropped and `page_size` clamped to 1..100;
21
+ * - a non-UUID `agent_id`, which is not a filter loopctl can run (a cast error, not a 422).
22
+ */
23
+
24
+ import { uuid } from "./delivery-loop.js";
25
+
26
+ export const TREND_GRANULARITIES = ["daily", "weekly"];
27
+
28
+ function refuse(body) {
29
+ return { error: true, status: 0, body };
30
+ }
31
+
32
+ // ONE template literal per builder (see `test/tool-surface.js`).
33
+ export function costTrendsPath(query = "") {
34
+ return `/api/v1/analytics/trends${query}`;
35
+ }
36
+
37
+ export function modelMixPath(query = "") {
38
+ return `/api/v1/analytics/model-mix${query}`;
39
+ }
40
+
41
+ export function agentModelProfilePath(agentId, query = "") {
42
+ return `/api/v1/analytics/agents/${encodeURIComponent(agentId)}/model-profile${query}`;
43
+ }
44
+
45
+ const DATE_RE = /^(\d{4})-(\d{2})-(\d{2})$/;
46
+
47
+ function realDate(value) {
48
+ const m = typeof value === "string" ? DATE_RE.exec(value) : null;
49
+ if (!m) return false;
50
+ const [y, mo, d] = [Number(m[1]), Number(m[2]), Number(m[3])];
51
+ const date = new Date(Date.UTC(y, mo - 1, d));
52
+ return date.getUTCFullYear() === y && date.getUTCMonth() === mo - 1 && date.getUTCDate() === d;
53
+ }
54
+
55
+ // The shared filters: project, date range. Returns `{ bad }` or `{ params }`.
56
+ function commonFilters({ project_id, since, until }) {
57
+ if (project_id != null && (typeof project_id !== "string" || project_id.trim() === "")) {
58
+ return { bad: refuse("`project_id` must be a project's UUID, slug or repo name.") };
59
+ }
60
+
61
+ for (const [field, value] of [
62
+ ["since", since],
63
+ ["until", until],
64
+ ]) {
65
+ if (value != null && !realDate(value)) {
66
+ return {
67
+ bad: refuse(
68
+ `\`${field}\` must be a real date as YYYY-MM-DD. loopctl drops a date it cannot ` +
69
+ "parse and would answer for all time.",
70
+ ),
71
+ };
72
+ }
73
+ }
74
+
75
+ const params = new URLSearchParams();
76
+ if (project_id != null) params.set("project_id", project_id);
77
+ if (since != null) params.set("since", since);
78
+ if (until != null) params.set("until", until);
79
+
80
+ return { params };
81
+ }
82
+
83
+ function asQuery(params) {
84
+ const qs = params.toString();
85
+ return qs === "" ? "" : `?${qs}`;
86
+ }
87
+
88
+ export async function costTrends(
89
+ { granularity, project_id, since, until, page, page_size } = {},
90
+ { apiCall } = {},
91
+ ) {
92
+ if (granularity != null && !TREND_GRANULARITIES.includes(granularity)) {
93
+ return refuse(
94
+ `\`granularity\` is one of: ${TREND_GRANULARITIES.join(", ")} (default daily); loopctl ` +
95
+ "would answer daily for any other value.",
96
+ );
97
+ }
98
+
99
+ const { bad, params } = commonFilters({ project_id, since, until });
100
+ if (bad) return bad;
101
+
102
+ if (page != null && !(Number.isInteger(page) && page >= 1)) {
103
+ return refuse("`page` must be a positive integer.");
104
+ }
105
+
106
+ if (page_size != null && !(Number.isInteger(page_size) && page_size >= 1 && page_size <= 100)) {
107
+ return refuse("`page_size` must be an integer from 1 to 100 (default 20).");
108
+ }
109
+
110
+ if (granularity != null) params.set("granularity", granularity);
111
+ if (page != null) params.set("page", String(page));
112
+ if (page_size != null) params.set("page_size", String(page_size));
113
+
114
+ return apiCall("GET", costTrendsPath(asQuery(params)), null);
115
+ }
116
+
117
+ export async function modelMix({ project_id, agent_id, since, until } = {}, { apiCall } = {}) {
118
+ const { bad, params } = commonFilters({ project_id, since, until });
119
+ if (bad) return bad;
120
+
121
+ if (agent_id != null) {
122
+ const agentBad = uuid(agent_id, "agent_id");
123
+ if (agentBad) return agentBad;
124
+ params.set("agent_id", agent_id);
125
+ }
126
+
127
+ return apiCall("GET", modelMixPath(asQuery(params)), null);
128
+ }
129
+
130
+ export async function agentModelProfile(
131
+ { agent_id, project_id, since, until } = {},
132
+ { apiCall } = {},
133
+ ) {
134
+ const agentBad = uuid(agent_id, "agent_id");
135
+ if (agentBad) return agentBad;
136
+
137
+ const { bad, params } = commonFilters({ project_id, since, until });
138
+ if (bad) return bad;
139
+
140
+ return apiCall("GET", agentModelProfilePath(agent_id, asQuery(params)), null);
141
+ }
@@ -0,0 +1,40 @@
1
+ /**
2
+ * The one sink for a secret a tool must keep out of the session transcript (a raw API key,
3
+ * quarantined channel rows). The file is created exclusively with mode 0600 BEFORE the request
4
+ * that produces the secret, so a path that exists or a missing directory is refused with nothing
5
+ * sent. Any hardening of how a secret reaches disk belongs here, not in a caller.
6
+ *
7
+ * Returns `{ writeSecret(text), discardSecret() }`: the first writes once and closes; the
8
+ * second closes and unlinks, and is safe to call after a write or twice. The method names are
9
+ * deliberately not `write`/`discard`: test/tool-surface.js reaches functions by NAME, and a
10
+ * bare `write(` call would be credited with the holder journal's `write` and its routes.
11
+ */
12
+
13
+ import { closeSync, openSync, unlinkSync, writeSync } from "node:fs";
14
+
15
+ export function createSecretFile(path) {
16
+ const fd = openSync(path, "wx", 0o600);
17
+ let open = true;
18
+
19
+ const close = () => {
20
+ if (open) {
21
+ open = false;
22
+ closeSync(fd);
23
+ }
24
+ };
25
+
26
+ return {
27
+ writeSecret: (text) => {
28
+ writeSync(fd, text);
29
+ close();
30
+ },
31
+ discardSecret: () => {
32
+ close();
33
+ try {
34
+ unlinkSync(path);
35
+ } catch {
36
+ // already gone
37
+ }
38
+ },
39
+ };
40
+ }
@@ -0,0 +1,90 @@
1
+ /**
2
+ * `bulk_claim` / `unclaim_story` — `POST /api/v1/stories/bulk/claim`
3
+ * (`BulkOperationsController.claim`) and `POST /api/v1/stories/:id/unclaim`
4
+ * (`StoryStatusController.unclaim`), loopctl #872.
5
+ *
6
+ * KEY: the session's own key (`agentKey()` in index.js, the holder credential when this session
7
+ * has one, else LOOPCTL_AGENT_KEY). Both actions are `exact_role: :agent` with NO hierarchy, so
8
+ * an orchestrator, user or superadmin key is 403 insufficient_role like any non-member, and the
9
+ * user key must never be reached for. Both are human-anchored (403 custody_tier_required on an
10
+ * agent-rooted tenant) and custody surface (`LoopctlWeb.CustodySurface`: `stories/bulk/claim`
11
+ * and `stories/:id/unclaim`), so a custody halt answers 503 tenant_halted.
12
+ *
13
+ * WHAT THE ENDPOINTS DO, read from the controllers and `Loopctl.BulkOperations.bulk_claim/4`:
14
+ *
15
+ * - bulk claim takes `story_ids` (at most 50; 422 when empty, too long or not a list) and
16
+ * claims each `contracted` story for the key's agent and holder, one transaction, sorted
17
+ * ids, partial success: 200 with `results` when any story was claimed, 422 with `results`
18
+ * when none was. Each result is `{story_id, status, reason?}`; per-story reasons include a
19
+ * story not in `contracted`, `story_held`, `dependencies_not_met` and `Story not found`.
20
+ * 409 chg_root_review_only refuses the whole batch for a chg-rooted key. Unlike
21
+ * `claim_story` it mints NO start capability: `start_story` recovers one through
22
+ * `recover-cap`.
23
+ * - unclaim releases the caller's own claim. 403 when the key's agent is not the assignee,
24
+ * 409 for a story in no claimable state or 409 held_by_other_holder (another session holds
25
+ * it), 404 for another tenant's story, 422 when the release's write or audit entry was
26
+ * rejected, 500 audit_chain_append_failed when the release reached the retry ceiling and the
27
+ * escalation's chain entry was refused (the whole release rolled back). A delivery story is
28
+ * re-contracted below the retry ceiling and escalated over `attempts_exhausted` at it.
29
+ *
30
+ * CHECKED HERE: a non-UUID id (a story id is a `:binary_id`, and a bad one in the batch fails
31
+ * the lock query's cast instead of reading as one story's error), a duplicate in the batch
32
+ * (claimed once, then reported as a second story not in `contracted`), and the batch bounds the
33
+ * server would refuse anyway, so a call that cannot succeed sends nothing.
34
+ */
35
+
36
+ import { uuid } from "./delivery-loop.js";
37
+
38
+ export const BULK_MAX = 50;
39
+
40
+ function refuse(body) {
41
+ return { error: true, status: 0, body };
42
+ }
43
+
44
+ // ONE template literal per builder (see `test/tool-surface.js`).
45
+ export function bulkClaimPath() {
46
+ return `/api/v1/stories/bulk/claim`;
47
+ }
48
+
49
+ export function unclaimPath(storyId) {
50
+ return `/api/v1/stories/${encodeURIComponent(storyId)}/unclaim`;
51
+ }
52
+
53
+ /**
54
+ * Refuses a story-id batch the server would refuse or misread; `null` when it is sendable.
55
+ * `field` names the batch in a message and `label(i)` names one of its ids.
56
+ */
57
+ export function badStoryIdBatch(ids, field, label = (i) => `${field}[${i}]`) {
58
+ if (!Array.isArray(ids) || ids.length === 0) {
59
+ return refuse(`\`${field}\` is required: a non-empty array.`);
60
+ }
61
+
62
+ if (ids.length > BULK_MAX) {
63
+ return refuse(`\`${field}\` carries ${ids.length} stories; loopctl takes at most ${BULK_MAX}.`);
64
+ }
65
+
66
+ for (const [i, id] of ids.entries()) {
67
+ const bad = uuid(id, label(i));
68
+ if (bad) return bad;
69
+ }
70
+
71
+ const seen = new Set();
72
+ for (const id of ids) {
73
+ const key = id.toLowerCase();
74
+ if (seen.has(key)) return refuse(`\`${field}\` names story ${id} twice; name each story once.`);
75
+ seen.add(key);
76
+ }
77
+
78
+ return null;
79
+ }
80
+
81
+ export async function bulkClaimStories({ story_ids } = {}, { apiCall } = {}) {
82
+ const bad = badStoryIdBatch(story_ids, "story_ids");
83
+ if (bad) return bad;
84
+
85
+ return apiCall("POST", bulkClaimPath(), { story_ids });
86
+ }
87
+
88
+ export async function unclaimStory({ story_id } = {}, { apiCall } = {}) {
89
+ return uuid(story_id, "story_id") ?? apiCall("POST", unclaimPath(story_id), null);
90
+ }
@@ -0,0 +1,139 @@
1
+ /**
2
+ * The tenant's own settings and its authenticator labels: `update_tenant`
3
+ * (`PATCH /api/v1/tenants/me`, `TenantController.update`), `list_authenticators` and
4
+ * `rename_authenticator` (`GET /api/v1/tenants/:id/authenticators`,
5
+ * `PATCH /api/v1/tenants/:id/authenticators/:auth_id`, `TenantAuthenticatorController.index` /
6
+ * `.rename`), and `list_trusted_endpoints` (`GET /api/v1/egress/trusted-endpoints`,
7
+ * `EgressController.list_trusted`), loopctl #872.
8
+ *
9
+ * KEYS, from the controllers' plugs:
10
+ *
11
+ * - update_tenant is `role: :user` WITH the hierarchy (403 insufficient_role below it), not
12
+ * human-anchored and not custody surface: index.js `userKeyApiCall`, LOOPCTL_USER_KEY when
13
+ * set. It casts `name`, `email`, `settings`, `default_story_budget_millicents` and
14
+ * `token_data_retention_days`; `settings` is MERGED into the stored map key by key, never
15
+ * replaced. 422 for a malformed or taken email, a `settings` that is not an object or whose
16
+ * `knowledge_auto_extract` / `kb_curation_log` is not a boolean, a budget that is not above
17
+ * 0, and a retention that is not an integer of at least 30 (null turns retention off).
18
+ * - the authenticator list and rename are `role: :user` plus tenant ownership: 403 (insufficient_role
19
+ * below user, a bare `Forbidden` when `tenant_id` is not the key's own tenant). Neither
20
+ * verifies a WebAuthn assertion, unlike enroll and revoke, so a tool can complete both. The
21
+ * list carries ids, labels and `credential_fingerprint` (the identity to confirm before
22
+ * `revoke_authenticator`; a label is rewritable by any user key), never credential
23
+ * material. Rename refusals: 400 without a string `friendly_name`, 404 for an unknown
24
+ * authenticator, 422 friendly_name_blank / friendly_name_invalid / friendly_name_too_long
25
+ * (over 120 bytes after trimming), 429 past the per-tenant rename budget (300 an hour), 500
26
+ * when the rename or its audit entry could not be written.
27
+ * - the trusted-endpoint list has no role plug: any key of the tenant, the session's own.
28
+ * Every entry is an UNVERIFIED tenant attestation, not network locality.
29
+ *
30
+ * CHECKED HERE, because the server would answer them WRONGLY rather than refuse:
31
+ *
32
+ * - update_tenant's `slug`: the update never casts it (it keys the audit-key secret, rls-02),
33
+ * so a body carrying one answers 200 with the slug unchanged;
34
+ * - an update with no field at all, which answers 200 having changed nothing;
35
+ * - a `tenant_id` in upper case: ownership compares the id as a STRING against the key's
36
+ * lower-case tenant id, so the right tenant in the wrong case answers 403. It is sent lower
37
+ * case, which names the same tenant;
38
+ * - non-UUID ids and a label the server would refuse, so a call that cannot succeed sends
39
+ * nothing.
40
+ */
41
+
42
+ import { uuid } from "./delivery-loop.js";
43
+
44
+ export const TENANT_UPDATE_FIELDS = [
45
+ "name",
46
+ "email",
47
+ "settings",
48
+ "default_story_budget_millicents",
49
+ "token_data_retention_days",
50
+ ];
51
+
52
+ export const MAX_FRIENDLY_NAME_BYTES = 120;
53
+
54
+ function refuse(body) {
55
+ return { error: true, status: 0, body };
56
+ }
57
+
58
+ // ONE template literal per builder (see `test/tool-surface.js`).
59
+ export function tenantMePath() {
60
+ return `/api/v1/tenants/me`;
61
+ }
62
+
63
+ export function authenticatorsPath(tenantId) {
64
+ return `/api/v1/tenants/${encodeURIComponent(tenantId)}/authenticators`;
65
+ }
66
+
67
+ export function authenticatorPath(tenantId, authenticatorId) {
68
+ return `/api/v1/tenants/${encodeURIComponent(tenantId)}/authenticators/${encodeURIComponent(authenticatorId)}`;
69
+ }
70
+
71
+ export function trustedEndpointsPath() {
72
+ return `/api/v1/egress/trusted-endpoints`;
73
+ }
74
+
75
+ export async function updateTenant(args = {}, { apiCall } = {}) {
76
+ if (Object.hasOwn(args, "slug")) {
77
+ return refuse(
78
+ "`slug` is immutable: it keys the tenant's audit-key secret, and loopctl ignores it on " +
79
+ "update and answers 200 with the slug unchanged. Nothing was sent.",
80
+ );
81
+ }
82
+
83
+ const body = {};
84
+ for (const field of TENANT_UPDATE_FIELDS) {
85
+ if (args[field] !== undefined) body[field] = args[field];
86
+ }
87
+
88
+ if (Object.keys(body).length === 0) {
89
+ return refuse(`Pass at least one of: ${TENANT_UPDATE_FIELDS.join(", ")}.`);
90
+ }
91
+
92
+ if (
93
+ body.settings !== undefined &&
94
+ (body.settings === null || typeof body.settings !== "object" || Array.isArray(body.settings))
95
+ ) {
96
+ return refuse("`settings` must be an object; its keys are merged into the stored settings.");
97
+ }
98
+
99
+ return apiCall("PATCH", tenantMePath(), body);
100
+ }
101
+
102
+ function tenantIdOf(tenant_id) {
103
+ return uuid(tenant_id, "tenant_id") ?? { ok: tenant_id.toLowerCase() };
104
+ }
105
+
106
+ export async function listAuthenticators({ tenant_id } = {}, { apiCall } = {}) {
107
+ const tenant = tenantIdOf(tenant_id);
108
+ if (!tenant.ok) return tenant;
109
+
110
+ return apiCall("GET", authenticatorsPath(tenant.ok), null);
111
+ }
112
+
113
+ export async function renameAuthenticator(
114
+ { tenant_id, authenticator_id, friendly_name } = {},
115
+ { apiCall } = {},
116
+ ) {
117
+ const tenant = tenantIdOf(tenant_id);
118
+ if (!tenant.ok) return tenant;
119
+
120
+ const bad = uuid(authenticator_id, "authenticator_id");
121
+ if (bad) return bad;
122
+
123
+ if (typeof friendly_name !== "string" || friendly_name.trim() === "") {
124
+ return refuse("`friendly_name` is required: the new label, not blank.");
125
+ }
126
+
127
+ if (Buffer.byteLength(friendly_name.trim(), "utf8") > MAX_FRIENDLY_NAME_BYTES) {
128
+ return refuse(
129
+ `\`friendly_name\` is at most ${MAX_FRIENDLY_NAME_BYTES} bytes after trimming ` +
130
+ "(a multi-byte character counts each byte).",
131
+ );
132
+ }
133
+
134
+ return apiCall("PATCH", authenticatorPath(tenant.ok, authenticator_id), { friendly_name });
135
+ }
136
+
137
+ export async function listTrustedEndpoints(_args = {}, { apiCall } = {}) {
138
+ return apiCall("GET", trustedEndpointsPath(), null);
139
+ }