@jini-ai/integrations 0.6.19 → 0.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +41 -0
- package/dist/api-connections/access-token.js +4 -14
- package/dist/api-connections/account-actions.d.ts +6 -1
- package/dist/api-connections/attempt-state.d.ts +2 -2
- package/dist/api-connections/attempt-state.js +10 -11
- package/dist/api-connections/authorization.js +13 -20
- package/dist/api-connections/budgets.d.ts +91 -0
- package/dist/api-connections/budgets.js +87 -0
- package/dist/api-connections/byo-client.d.ts +38 -0
- package/dist/api-connections/byo-client.js +28 -0
- package/dist/api-connections/connect.d.ts +87 -0
- package/dist/api-connections/connect.js +143 -0
- package/dist/api-connections/declarations.d.ts +68 -0
- package/dist/api-connections/declarations.js +178 -0
- package/dist/api-connections/deps.d.ts +4 -1
- package/dist/api-connections/descriptor.d.ts +15 -0
- package/dist/api-connections/descriptor.js +1 -5
- package/dist/api-connections/finish-authorization.d.ts +1 -1
- package/dist/api-connections/hook-http.d.ts +20 -0
- package/dist/api-connections/hook-http.js +27 -0
- package/dist/api-connections/host-ports.d.ts +244 -0
- package/dist/api-connections/host-ports.js +2 -0
- package/dist/api-connections/host.d.ts +81 -0
- package/dist/api-connections/host.js +320 -0
- package/dist/api-connections/hosted-mcp/contracts.d.ts +291 -0
- package/dist/api-connections/hosted-mcp/contracts.js +2 -0
- package/dist/api-connections/hosted-mcp/index.d.ts +5 -0
- package/dist/api-connections/hosted-mcp/index.js +3 -0
- package/dist/api-connections/hosted-mcp/shared-sign-in.d.ts +167 -0
- package/dist/api-connections/hosted-mcp/shared-sign-in.js +293 -0
- package/dist/api-connections/hosted-mcp/sign-in.d.ts +25 -0
- package/dist/api-connections/hosted-mcp/sign-in.js +889 -0
- package/dist/api-connections/hosted-sign-in.d.ts +48 -0
- package/dist/api-connections/hosted-sign-in.js +51 -0
- package/dist/api-connections/index.d.ts +23 -1
- package/dist/api-connections/index.js +15 -0
- package/dist/api-connections/install-credential.d.ts +1 -1
- package/dist/api-connections/oauth-capabilities.d.ts +63 -0
- package/dist/api-connections/oauth-capabilities.js +2 -0
- package/dist/api-connections/ports.d.ts +1 -1
- package/dist/api-connections/request-checks.d.ts +11 -1
- package/dist/api-connections/request-checks.js +2 -3
- package/dist/api-connections/shared.d.ts +79 -0
- package/dist/api-connections/shared.js +106 -0
- package/dist/api-connections/token-store/record.d.ts +2 -2
- package/dist/api-connections/token-store/vault-token-store.d.ts +30 -4
- package/dist/api-connections/token-store/vault-token-store.js +1 -4
- package/dist/credentialed-http/sets/host.d.ts +146 -0
- package/dist/credentialed-http/sets/host.js +2 -0
- package/dist/credentialed-http/sets/index.d.ts +24 -0
- package/dist/credentialed-http/sets/index.js +24 -0
- package/dist/credentialed-http/sets/store.d.ts +193 -0
- package/dist/credentialed-http/sets/store.js +489 -0
- package/dist/credentialed-http/sets/vault-repo.d.ts +81 -0
- package/dist/credentialed-http/sets/vault-repo.js +147 -0
- package/dist/credentialed-http/tools/credential-copy-tool.d.ts +34 -0
- package/dist/credentialed-http/tools/credential-copy-tool.js +132 -0
- package/dist/credentialed-http/tools/credential-tool-host.d.ts +152 -0
- package/dist/credentialed-http/tools/credential-tool-host.js +2 -0
- package/dist/credentialed-http/tools/credential-tool-operations.d.ts +370 -0
- package/dist/credentialed-http/tools/credential-tool-operations.js +2 -0
- package/dist/credentialed-http/tools/index.d.ts +7 -0
- package/dist/credentialed-http/tools/index.js +4 -0
- package/dist/credentialed-http/tools/tool-registrations.d.ts +55 -0
- package/dist/credentialed-http/tools/tool-registrations.js +729 -0
- package/package.json +34 -11
|
@@ -0,0 +1,729 @@
|
|
|
1
|
+
// ToolInputError marks caller-correctable validation instead of an internal failure that transports redact.
|
|
2
|
+
import { decorateWithSchema, ToolInputError, redactSecrets, requireInputRecord, requireString, adaptLegacyAuthorize, requireToolPermission, buildDomainRegistrations, requireNoInput, withSchemaOnRejection } from "@jini-ai/core";
|
|
3
|
+
import { CustomCredentialValidationError, CustomCredentialNotFoundError, CustomCredentialDuplicateLabelError } from "../sets/store.js";
|
|
4
|
+
import { buildAuthorizationHeader } from "../credentialed-request.js";
|
|
5
|
+
import { callerSafeErrorMessage, withModelFacingErrors } from "@jini-ai/core/model-facing-tool-errors";
|
|
6
|
+
import { CredentialedRequestValidationError } from "../../contracts/credentialed-request-errors.js";
|
|
7
|
+
/** Stamps the host's app identity on a card a host builder made; the host's own values keep the same bytes. */
|
|
8
|
+
function withCardApp({ spec, app }) {
|
|
9
|
+
return { ...spec, app };
|
|
10
|
+
}
|
|
11
|
+
/**
|
|
12
|
+
* Decides which of `custom_credential_make_request`'s rejections are the CALLER's to fix — the same
|
|
13
|
+
* schema-decorated validation classification used for caller-correctable input failures: an
|
|
14
|
+
* unclassified rejection reaches `@jini-ai/daemon`'s `ToolExecutor` as `errorKind: 'internal'`, which
|
|
15
|
+
* `@jini-ai/http-kit`'s `delegatedToolExecuteRoute` SEC-005-redacts into a bare `INTERNAL_ERROR` —
|
|
16
|
+
* stripping the one piece of information (WHICH rule refused the call) a caller could actually act on.
|
|
17
|
+
*
|
|
18
|
+
* Two classes:
|
|
19
|
+
* - `CredentialedRequestValidationError` — a bad `method`/`url`/`headers`/`body` shape, OR a `url`
|
|
20
|
+
* whose origin is not one of the credential's own saved hosts (`resolveAllowedRequestUrl`'s
|
|
21
|
+
* allowlist refusal — the "off-allowlist host" case).
|
|
22
|
+
* - `EgressRefusedError` — the shared `HttpClientPort` (ADR-038) refused the target before ever
|
|
23
|
+
* connecting: a non-public resolved address on the first hop or any re-verified redirect hop, a
|
|
24
|
+
* disallowed scheme, or credentials embedded in the URL.
|
|
25
|
+
*
|
|
26
|
+
* makeCredentialedRequest must preserve EgressRefusedError rather than wrapping it as a
|
|
27
|
+
* transport failure. Otherwise this instanceof classification loses the actionable egress reason
|
|
28
|
+
* and a URL refusal becomes indistinguishable from a DNS/timeout crash.
|
|
29
|
+
*
|
|
30
|
+
* An `EgressRefusedError` reaches the model in its `callerSafeMessage` form only — without the
|
|
31
|
+
* address the hostname resolved to — via {@link makeModelFacingCredentialedRequest}, which every
|
|
32
|
+
* call site uses through the same classification boundary.
|
|
33
|
+
*
|
|
34
|
+
* Deliberately NOT `CredentialedRequestTransportError` (a DNS failure, timeout, or connection error
|
|
35
|
+
* is not a decision this process made, and a different URL does not reliably fix it) and NOT
|
|
36
|
+
* `CustomCredentialNotFoundError` (a different call shape — a wrong label — unrelated to this tool's
|
|
37
|
+
* egress/allowlist boundary and out of scope for this fix).
|
|
38
|
+
*
|
|
39
|
+
* The port's `classifyError` names those two classes `validation` and `egress-refused`.
|
|
40
|
+
*
|
|
41
|
+
* @complexity O(1) — one `classifyError` call.
|
|
42
|
+
*/
|
|
43
|
+
/**
|
|
44
|
+
* `makeCredentialedRequest` as the model may see it fail: validation and egress rejections schema-decorated
|
|
45
|
+
* using only their classified `callerSafeMessage`. The original rejection is classified once,
|
|
46
|
+
* before any decoration can read its private `.message`.
|
|
47
|
+
*
|
|
48
|
+
* The refusal and requested hostname reach the model; the resolved address stays server-side.
|
|
49
|
+
* A model that can name any host and read back its resolved address can map internal
|
|
50
|
+
* DNS one call at a time (`internal-db.corp` -> `10.0.4.7`). The full message, address included, is
|
|
51
|
+
* kept server-side in the audit entry `makeCredentialedRequest` records (`egressRefusal`).
|
|
52
|
+
*
|
|
53
|
+
* @complexity O(1) beyond `makeCredentialedRequest` itself.
|
|
54
|
+
*/
|
|
55
|
+
async function makeModelFacingCredentialedRequest({ port, input, catalog, toolId }) {
|
|
56
|
+
const { headers, body, ...required } = input;
|
|
57
|
+
try {
|
|
58
|
+
return await port.request(required, { headers, body });
|
|
59
|
+
}
|
|
60
|
+
catch (error) {
|
|
61
|
+
const classified = port.classifyError({ error });
|
|
62
|
+
if (classified.category === "validation" || classified.category === "egress-refused") {
|
|
63
|
+
throw decorateWithSchema({ toolId, catalog, message: classified.callerSafeMessage });
|
|
64
|
+
}
|
|
65
|
+
throw error;
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
/**
|
|
69
|
+
* The same classification for `custom_credential_write_files`, which validates its whole input
|
|
70
|
+
* (`validateWriteFilesInput`) BEFORE the credential is even resolved. Every rejection from there is
|
|
71
|
+
* `CustomCredentialValidationError`, and every one of them names a rule a different call would
|
|
72
|
+
* satisfy: a bad owner/repo/branch/commitMessage, a path that is absolute, escapes the repository
|
|
73
|
+
* root, nests under `.git`, or duplicates another entry, a file over the per-file cap, or a batch
|
|
74
|
+
* over the file-count or aggregate-byte cap.
|
|
75
|
+
*
|
|
76
|
+
* That class extends plain `Error`, so an undecorated throw reaches `@jini-ai/daemon`'s
|
|
77
|
+
* `ToolExecutor` as `errorKind: 'internal'` and `@jini-ai/http-kit`'s `delegatedToolExecuteRoute`
|
|
78
|
+
* SEC-005-redacts it into a bare `INTERNAL_ERROR` — a model told only "something broke" about a
|
|
79
|
+
* refusal it could have fixed by moving one file out of `.git/`. Deliberately narrow: this predicate
|
|
80
|
+
* runs only around the validation call, so it never reclassifies the resolve/plan/commit failures
|
|
81
|
+
* that follow it.
|
|
82
|
+
*
|
|
83
|
+
* @complexity O(1) — one `instanceof` check.
|
|
84
|
+
*/
|
|
85
|
+
function isWriteFilesShapeRejection(error) {
|
|
86
|
+
return error instanceof CustomCredentialValidationError;
|
|
87
|
+
}
|
|
88
|
+
/**
|
|
89
|
+
* Commits using the SAME validated provider plan the handler obtained, rather than re-planning.
|
|
90
|
+
* This keeps the tree and branch-freshness checks tied to the read-only reconnaissance result.
|
|
91
|
+
* Keeping the write separate also bounds the handler's branching complexity.
|
|
92
|
+
*
|
|
93
|
+
* @complexity O(1) beyond the provider's `commitFiles`'s own O(files) cost.
|
|
94
|
+
*/
|
|
95
|
+
async function performRepositoryFilesWrite({ operations, port, provider, resolved, validated, plan }, _optional = {}) {
|
|
96
|
+
const commitResult = await port.commitFiles({ provider,
|
|
97
|
+
input: { ...writeTarget(resolved, validated), branch: validated.branch, commitMessage: validated.commitMessage, files: validated.files },
|
|
98
|
+
plan });
|
|
99
|
+
if (!commitResult.ok) {
|
|
100
|
+
operations.diagnostics.writeFailure({ phase: "commit", failure: commitResult });
|
|
101
|
+
return { executed: false, cancelled: false, reason: "error", message: commitResult.message };
|
|
102
|
+
}
|
|
103
|
+
return { executed: true, commitSha: commitResult.commitSha, commitUrl: commitResult.commitUrl, filesWritten: validated.files.length };
|
|
104
|
+
}
|
|
105
|
+
/** Where a write goes: the credential's API plus the `Authorization` header built from its connection. */
|
|
106
|
+
function writeTarget(resolved, validated) {
|
|
107
|
+
return { baseUrl: resolved.baseUrl, authorization: buildAuthorizationHeader({ connection: resolved.connection, schemes: [] }), owner: validated.owner, repo: validated.repo };
|
|
108
|
+
}
|
|
109
|
+
/** The exact keys `custom_credential_set_username` accepts — nothing else, ever. This is the
|
|
110
|
+
* structural half of "this tool can never accept a token" promised by the host's tool catalog
|
|
111
|
+
* description: `additionalProperties: false` on that catalog entry's `inputSchema` is descriptive
|
|
112
|
+
* only (the kernel "neither parses nor validates" a tool's schema — see `@jini-ai/core`'s own
|
|
113
|
+
* `ToolDescriptor.inputSchema` doc), so THIS handler-level check is the one that is actually
|
|
114
|
+
* enforced. */
|
|
115
|
+
const SET_USERNAME_ALLOWED_FIELDS = new Set(["label", "username"]);
|
|
116
|
+
/**
|
|
117
|
+
* Refuses a `custom_credential_set_username` call carrying any field other than `label`/`username` —
|
|
118
|
+
* in particular, a `token`/`connection`/`secret`-shaped field a model might try to smuggle a
|
|
119
|
+
* credential rotation through. This is the property that makes it defensible to leave this tool
|
|
120
|
+
* un-confirmed (see this file's header): there is no field on this call shape capable of carrying a
|
|
121
|
+
* secret, so there is nothing a confirmation dialog would even be protecting against.
|
|
122
|
+
*
|
|
123
|
+
* @throws {CustomCredentialValidationError} `input` carries a key other than `label`/`username`.
|
|
124
|
+
* @complexity O(n) in the number of supplied input keys.
|
|
125
|
+
*/
|
|
126
|
+
function rejectUnexpectedSetUsernameFields({ input, messages }, _optional = {}) {
|
|
127
|
+
const unexpected = Object.keys(input).filter((key) => !SET_USERNAME_ALLOWED_FIELDS.has(key));
|
|
128
|
+
if (unexpected.length > 0) {
|
|
129
|
+
throw new CustomCredentialValidationError(messages.unexpectedUsername({ keys: unexpected }));
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
/**
|
|
133
|
+
* Reads and validates this tool's required `username` field: a non-empty string to set it, or `null`
|
|
134
|
+
* to explicitly clear it. Unlike `../sets/store.ts`'s own `validateUsernamePatch` (which validates
|
|
135
|
+
* `updateCustomCredential`'s OPTIONAL `username` patch, where omitting the field entirely means "leave
|
|
136
|
+
* unchanged"), omitting the key here is itself a caller error — this tool exists for exactly one job,
|
|
137
|
+
* set-or-clear, so "say nothing" is never a valid call into it. Mirrors that function's own two
|
|
138
|
+
* non-omitted values and their exact wording for the one case they share (a blank string), so the two
|
|
139
|
+
* surfaces never describe the same rule two different ways.
|
|
140
|
+
*
|
|
141
|
+
* @throws {CustomCredentialValidationError} `username` is omitted, or present but neither `null` nor a
|
|
142
|
+
* non-empty string.
|
|
143
|
+
* @complexity O(1).
|
|
144
|
+
*/
|
|
145
|
+
function requireUsernameOrClearSentinel({ input, messages }, _optional = {}) {
|
|
146
|
+
if (input.username === undefined) {
|
|
147
|
+
throw new CustomCredentialValidationError(messages.missingUsername);
|
|
148
|
+
}
|
|
149
|
+
if (input.username === null)
|
|
150
|
+
return null;
|
|
151
|
+
if (typeof input.username !== "string" || input.username.trim() === "") {
|
|
152
|
+
throw new CustomCredentialValidationError(messages.invalidUsername);
|
|
153
|
+
}
|
|
154
|
+
return input.username;
|
|
155
|
+
}
|
|
156
|
+
/** The exact keys `custom_credential_set_token` accepts on the MODEL-ISSUED call — `label`, nothing
|
|
157
|
+
* else, ever. The API rotation schema supplied by the host already has no `token` property to fill in, but
|
|
158
|
+
* `additionalProperties: false` is descriptive only (same caveat `SET_USERNAME_ALLOWED_FIELDS`'s own
|
|
159
|
+
* doc gives) — this is the layer that is actually enforced. */
|
|
160
|
+
const SET_TOKEN_ALLOWED_FIELDS = new Set(["label"]);
|
|
161
|
+
/**
|
|
162
|
+
* Refuses a `custom_credential_set_token` call carrying any field other than `label` — the ONLY
|
|
163
|
+
* gate standing between "the model can never supply a token to this tool" and a future edit that adds
|
|
164
|
+
* a second property to its schema without also widening this check. There is no legitimate reason for
|
|
165
|
+
* this call to ever carry anything else: the token itself can only ever arrive later, through the
|
|
166
|
+
* rendered form's own submission, which this function never sees (it validates the ORIGINAL call that
|
|
167
|
+
* opens the exchange, before any form exists).
|
|
168
|
+
*
|
|
169
|
+
* @throws {CustomCredentialValidationError} `input` carries a key other than `label`.
|
|
170
|
+
* @complexity O(n) in the number of supplied input keys.
|
|
171
|
+
*/
|
|
172
|
+
function rejectUnexpectedSetTokenFields({ input, messages }, _optional = {}) {
|
|
173
|
+
const unexpected = Object.keys(input).filter((key) => !SET_TOKEN_ALLOWED_FIELDS.has(key));
|
|
174
|
+
if (unexpected.length > 0) {
|
|
175
|
+
throw new CustomCredentialValidationError(messages.unexpectedToken({ keys: unexpected }));
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
/** Probe only plugin-owned API cards before sealing, keeping every failure value-free.
|
|
179
|
+
* @throws CustomCredentialValidationError for refusal/unavailability or an origin mismatch.
|
|
180
|
+
* @complexity One bounded GET plus the installed auth-scheme load; no persistence.
|
|
181
|
+
*/
|
|
182
|
+
async function probeCardBeforeSave({ card, baseUrl, connection, routeDeps, operations, probe, signal }, { replacing = false } = {}) {
|
|
183
|
+
if (!card?.probeUrl)
|
|
184
|
+
return;
|
|
185
|
+
// Rotation must not send a key to a card's old origin after the saved row was re-pointed.
|
|
186
|
+
if (new URL(card.probeUrl).origin !== new URL(baseUrl).origin)
|
|
187
|
+
throw new CustomCredentialValidationError(operations.messages.probeOriginMismatch);
|
|
188
|
+
const schemes = await routeDeps.loadAuthSchemes({ workspaceId: routeDeps.workspaceId });
|
|
189
|
+
signal.throwIfAborted();
|
|
190
|
+
const status = await probe({ connection, url: card.probeUrl, schemes });
|
|
191
|
+
signal.throwIfAborted();
|
|
192
|
+
if (status === 'refused' || status === 'unavailable')
|
|
193
|
+
throw new CustomCredentialValidationError(operations.messages.probeFailure({ status, keyHint: card.keyHint, replacing }));
|
|
194
|
+
}
|
|
195
|
+
/**
|
|
196
|
+
* `custom_credential_set_token`'s `askThenReport` answer handling — extracted to a top-level function
|
|
197
|
+
* so its own complexity is measured independently of the handler that opens the exchange and builds
|
|
198
|
+
* the form.
|
|
199
|
+
*
|
|
200
|
+
* `askThenReport`, not `askOnce`: a submitted form's `tools/call` resolves the instant
|
|
201
|
+
* the answer route DELIVERS it to this parked call, before the replacement operation below
|
|
202
|
+
* has even run. Each
|
|
203
|
+
* non-success branch that sends an `outcome` does so because the confirmation-turned-form's own script
|
|
204
|
+
* would otherwise leave a bare "Done." on screen for work that has not actually happened yet; the
|
|
205
|
+
* cancel/no-answer branches send none, because the form's own script already reports "Dismissed."/an
|
|
206
|
+
* expiry locally the moment this call resolves, and that IS the truth for those two cases (nothing
|
|
207
|
+
* asynchronous happens afterward that could still fail).
|
|
208
|
+
*
|
|
209
|
+
* The token itself lives in a single local parameter for the width of this function and is never
|
|
210
|
+
* assigned to any field this function returns, logged, or otherwise retained — the property
|
|
211
|
+
* the host's catalog description promises the model.
|
|
212
|
+
*
|
|
213
|
+
* @complexity O(1) locally, an optional bounded GET, and one `updateCustomCredential` call (validate, seal, write).
|
|
214
|
+
*/
|
|
215
|
+
// Lifecycle classification and outcome delivery now belong to Jini; this function is only the save port.
|
|
216
|
+
async function saveSetToken({ token, signal, routeDeps, operations, probe, existing, pluginCard, principalId }, _optional = {}) {
|
|
217
|
+
// Paste artifacts are dropped before anything is read or written; see card-token.ts.
|
|
218
|
+
const cleanedToken = operations.policy.cleanToken({ token });
|
|
219
|
+
// Re-reads the username HERE, at write time — never trusts `existing` (captured back when
|
|
220
|
+
// `custom_credential_set_token`'s handler first resolved the label, before the form was even shown
|
|
221
|
+
// to a human who may sit on it for an arbitrarily long time). `custom_credential_set_username` can
|
|
222
|
+
// run against this same row while the form is open; if this handler carried `existing.username`
|
|
223
|
+
// forward as a captured literal, that concurrent change would be silently overwritten with the
|
|
224
|
+
// value the username held before the form opened. `existing.id` is still safe to reuse — it names
|
|
225
|
+
// WHICH row to update and cannot go stale the way a plaintext column value can.
|
|
226
|
+
const current = await operations.sets.describe({ id: existing.id });
|
|
227
|
+
if (!current)
|
|
228
|
+
throw new CustomCredentialNotFoundError(operations.messages.notFoundId({ id: existing.id }));
|
|
229
|
+
// Half-migrated credentials keep the username only in their sealed connection. Resolve that
|
|
230
|
+
// fallback from the current row, retaining the fresh-read protection against form-open races.
|
|
231
|
+
const resolved = current.username === undefined
|
|
232
|
+
? await operations.sets.resolve({ label: current.label })
|
|
233
|
+
: null;
|
|
234
|
+
const username = current.username ?? resolved?.connection.username;
|
|
235
|
+
if (signal.aborted)
|
|
236
|
+
throw new ToolInputError({ message: operations.messages.runEnded });
|
|
237
|
+
const connection = { token: cleanedToken, ...(username !== undefined ? { username } : {}) };
|
|
238
|
+
await probeCardBeforeSave({ card: pluginCard, baseUrl: current.baseUrl, connection, routeDeps, operations, probe, signal }, { replacing: true });
|
|
239
|
+
return await operations.sets.replace({
|
|
240
|
+
id: existing.id,
|
|
241
|
+
signal, principalId, guardRepo: operations.policy.guardRepo,
|
|
242
|
+
// Carries the CURRENT (just re-read) username forward into the fresh connection. Replacing
|
|
243
|
+
// `connection` WITHOUT one would silently CLEAR a saved username — `../sets/store.ts`'s own
|
|
244
|
+
// `updateCustomCredential` doc: "replacing the connection replaces the username ... including
|
|
245
|
+
// clearing it, when the new connection omits one". A token-only fix must never have that side
|
|
246
|
+
// effect, and must never resurrect a value the username has since moved on from either — hence
|
|
247
|
+
// the fresh read above rather than the `existing` snapshot. A row deleted while the form
|
|
248
|
+
// was open is refused before probing; the store also catches deletion after this read.
|
|
249
|
+
connection,
|
|
250
|
+
});
|
|
251
|
+
}
|
|
252
|
+
/** Reads optional non-secret prefill hints from the model-issued call.
|
|
253
|
+
* Blank strings are absent; unknown category options remain subject to store validation on save.
|
|
254
|
+
* @complexity O(1) — fixed field reads.
|
|
255
|
+
*/
|
|
256
|
+
function readCreateCredentialPrefill({ input, operations }, _optional = {}) {
|
|
257
|
+
const prefill = {};
|
|
258
|
+
if (input.worksFor !== undefined) {
|
|
259
|
+
try {
|
|
260
|
+
prefill.worksFor = operations.policy.normalizeWorksFor({ value: input.worksFor });
|
|
261
|
+
for (const value of prefill.worksFor)
|
|
262
|
+
operations.policy.assertFreeField({ value, field: "worksFor" });
|
|
263
|
+
}
|
|
264
|
+
catch {
|
|
265
|
+
throw new ToolInputError({ message: operations.messages.invalidWorksFor });
|
|
266
|
+
}
|
|
267
|
+
}
|
|
268
|
+
for (const field of ["label", "baseUrl", "category"]) {
|
|
269
|
+
if (typeof input[field] === "string" && input[field].trim() !== "") {
|
|
270
|
+
operations.policy.assertFreeField({ value: input[field], field });
|
|
271
|
+
prefill[field] = input[field];
|
|
272
|
+
}
|
|
273
|
+
}
|
|
274
|
+
return prefill;
|
|
275
|
+
}
|
|
276
|
+
/**
|
|
277
|
+
* Narrows `custom_credential_create`'s five submitted params to strings, with no defaulting — a
|
|
278
|
+
* missing or non-string field reads as `""`, exactly like every other `answer.params[...]` read in
|
|
279
|
+
* this file; parsing never changes the submitted token bytes.
|
|
280
|
+
*
|
|
281
|
+
* @complexity O(1) — five fixed field reads.
|
|
282
|
+
*/
|
|
283
|
+
function readRawCreateCredentialFields(params) {
|
|
284
|
+
return {
|
|
285
|
+
worksFor: params.worksFor ?? [],
|
|
286
|
+
label: typeof params["label"] === "string" ? params["label"] : "",
|
|
287
|
+
baseUrl: typeof params["baseUrl"] === "string" ? params["baseUrl"] : "",
|
|
288
|
+
category: typeof params["category"] === "string" ? params["category"] : "",
|
|
289
|
+
username: typeof params["username"] === "string" ? params["username"] : "",
|
|
290
|
+
token: typeof params["token"] === "string" ? params["token"] : "",
|
|
291
|
+
};
|
|
292
|
+
}
|
|
293
|
+
/**
|
|
294
|
+
* Applies `custom_credential_create`'s three field defaults on top of {@link readRawCreateCredentialFields}'s
|
|
295
|
+
* raw extraction. Every REAL field validation (non-empty label/baseUrl, a closed category, the
|
|
296
|
+
* `(workspaceId, label)` uniqueness constraint) is still left entirely to `../sets/store.ts`'s own
|
|
297
|
+
* `createCustomCredential` — this function only decides what a blank/missing field DEFAULTS to before
|
|
298
|
+
* that validation ever runs:
|
|
299
|
+
*
|
|
300
|
+
* - `category`: defaults to `"general"` (the closed set's catch-all, same as the admin Access Tokens
|
|
301
|
+
* page's own "Add custom provider" form) rather than passing a blank string through to `../sets/store.ts`'s
|
|
302
|
+
* `validateCategory`, which would reject it outright and block the save on a required field the human
|
|
303
|
+
* had no obvious answer for. Also enforced by the host's own form
|
|
304
|
+
* default: that default lives in the rendered `<select>`'s pre-selected option, this one covers a
|
|
305
|
+
* submission that somehow arrives without it. `"general"` is itself a member of the closed set
|
|
306
|
+
* `validateCategory` enforces, so a caller-supplied INVALID category (anything outside the fixed set)
|
|
307
|
+
* is still rejected exactly as before — this default never widens what counts as valid.
|
|
308
|
+
* - `username`: a blank string is treated as "omitted", matching `readCreateCredentialPrefill`'s own
|
|
309
|
+
* identical convention for the same optional field.
|
|
310
|
+
* - `displayLabel`: a blank `label` still needs a human-readable name for the outcome surface (see its
|
|
311
|
+
* own field doc above); `token` is passed through unchanged — the engine checks blankness before
|
|
312
|
+
* calling the domain save port.
|
|
313
|
+
*
|
|
314
|
+
* @complexity O(1) — three fixed defaulting decisions.
|
|
315
|
+
*/
|
|
316
|
+
function safeCredentialLabel({ label, operations }, _optional = {}) {
|
|
317
|
+
try {
|
|
318
|
+
operations.policy.assertFreeField({ value: label, field: 'label' });
|
|
319
|
+
return label.trim() === '' ? operations.messages.unlabeled : label;
|
|
320
|
+
}
|
|
321
|
+
catch {
|
|
322
|
+
return operations.messages.unlabeled;
|
|
323
|
+
}
|
|
324
|
+
}
|
|
325
|
+
function deriveCreateCredentialSubmission({ raw, operations }, _optional = {}) {
|
|
326
|
+
return {
|
|
327
|
+
worksFor: raw.worksFor,
|
|
328
|
+
label: raw.label,
|
|
329
|
+
baseUrl: raw.baseUrl,
|
|
330
|
+
category: raw.category.trim() === "" ? operations.policy.defaultCategory : raw.category,
|
|
331
|
+
username: raw.username.trim() === "" ? undefined : raw.username,
|
|
332
|
+
token: raw.token,
|
|
333
|
+
displayLabel: safeCredentialLabel({ label: raw.label, operations }),
|
|
334
|
+
};
|
|
335
|
+
}
|
|
336
|
+
/**
|
|
337
|
+
* Maps a `createCustomCredential` rejection onto `custom_credential_create`'s own failure shape — the
|
|
338
|
+
* error-type dispatch returns a value instead of writing a transport response.
|
|
339
|
+
*
|
|
340
|
+
* A collision is refused, never silently overwritten — and the refusal names the correct tool for a
|
|
341
|
+
* rotation, so the model does not retry this CREATE-only tool against an existing row. Every other
|
|
342
|
+
* failure's message goes through the same caller-safe allowlist as rotation — never an unlisted
|
|
343
|
+
* `err.message`, which can quote the submitted token.
|
|
344
|
+
*
|
|
345
|
+
* @complexity O(r) in operations.formErrors' rule count.
|
|
346
|
+
*/
|
|
347
|
+
function mapCreateCredentialError(required, _optional = {}) {
|
|
348
|
+
const { err, locale, label, operations } = required;
|
|
349
|
+
if (err instanceof CustomCredentialDuplicateLabelError) {
|
|
350
|
+
if (operations.policy.isProjectConflict({ error: err }))
|
|
351
|
+
return { reason: 'duplicate-label', message: err.message };
|
|
352
|
+
const message = operations.messages.duplicateLabel({ label });
|
|
353
|
+
return { reason: 'duplicate-label', message };
|
|
354
|
+
}
|
|
355
|
+
const message = operations.locale.translate({ message: callerSafeErrorMessage({ err, rules: operations.formErrors, fallback: operations.messages.formSaveFailure }), locale });
|
|
356
|
+
return { reason: err instanceof CustomCredentialValidationError ? 'invalid' : 'error', message };
|
|
357
|
+
}
|
|
358
|
+
/**
|
|
359
|
+
* The create card's domain save port stays separate from the engine's exchange lifecycle so its
|
|
360
|
+
* persistence cost is visible. askThenReport, rather than askOnce, keeps the human's submission
|
|
361
|
+
* waiting until the real store operation has finished instead of reporting premature Done.
|
|
362
|
+
*
|
|
363
|
+
* Every real field validation (non-empty label/baseUrl, closed category, workspace/label uniqueness)
|
|
364
|
+
* remains in createCustomCredential. The engine refuses blank tokens before sealConnection; the
|
|
365
|
+
* domain keeps field parsing/defaulting and the error-type mapper for actionable failures.
|
|
366
|
+
*
|
|
367
|
+
* The token lives only in the local submission and the sealed store. It is never returned, logged,
|
|
368
|
+
* or retained in a projection — the property promised by the host's catalog description.
|
|
369
|
+
* Only the save runs within the engine's error boundary, so Nothing was saved remains truthful.
|
|
370
|
+
* @complexity O(1) locally, an optional bounded GET, and one createCustomCredential call (validate, seal, insert).
|
|
371
|
+
*/
|
|
372
|
+
async function saveCreateCard(required, _optional = {}) {
|
|
373
|
+
const { routeDeps, operations, probe, submission, signal } = required;
|
|
374
|
+
await probeCardBeforeSave({ card: submission.pluginCard, baseUrl: submission.baseUrl,
|
|
375
|
+
connection: { token: operations.policy.cleanToken({ token: submission.token }), ...(submission.username !== undefined ? { username: submission.username } : {}) }, routeDeps, operations, probe, signal });
|
|
376
|
+
// Reuse the existing guard, including vault writes after asynchronous sealing.
|
|
377
|
+
// Only persistence sits in the engine's save boundary, so failure copy stays truthful.
|
|
378
|
+
const invalidate = await operations.publish.prepareInvalidation({});
|
|
379
|
+
const saved = await operations.sets.create({
|
|
380
|
+
signal, guardRepo: operations.policy.guardRepo,
|
|
381
|
+
label: submission.label,
|
|
382
|
+
worksFor: submission.worksFor,
|
|
383
|
+
category: submission.category,
|
|
384
|
+
baseUrl: submission.baseUrl,
|
|
385
|
+
...(submission.additionalHosts === undefined ? {} : { additionalHosts: submission.additionalHosts }),
|
|
386
|
+
...(submission.scope ? { scope: submission.scope } : {}),
|
|
387
|
+
connection: { token: operations.policy.cleanToken({ token: submission.token }), ...(submission.username !== undefined ? { username: submission.username } : {}) },
|
|
388
|
+
});
|
|
389
|
+
invalidate({ after: saved });
|
|
390
|
+
return saved;
|
|
391
|
+
}
|
|
392
|
+
/**
|
|
393
|
+
* Opens a create card and saves its submission as a NEW credential row — shared by the generic API
|
|
394
|
+
* card and a plugin's own key card, which differ only in their form and how a submission maps onto
|
|
395
|
+
* the row. Same engine, save port, safe errors and outcome for both.
|
|
396
|
+
* @complexity O(1) locally plus one createCustomCredential call per submission.
|
|
397
|
+
*/
|
|
398
|
+
async function openCreateCard(required, _optional = {}) {
|
|
399
|
+
const { ctx, emitSurface, routeDeps, operations, probe, cards, surfaces, locale, initialLabel, cardIdentity, form, submissionOf } = required;
|
|
400
|
+
// Fail closed rather than degrade — the only place a token can enter is the rendered form.
|
|
401
|
+
// A ToolInputError preserves this exact wording; a bare Error would become a redacted 500.
|
|
402
|
+
// The engine checks pre-dialog aborts and uses askThenReport so the save completes before Done.
|
|
403
|
+
// These safe projections are scoped to this invocation, never shared between concurrent cards.
|
|
404
|
+
// The error kind selects this tool's existing reason; the engine still owns error redaction.
|
|
405
|
+
let failure;
|
|
406
|
+
let displayLabel = safeCredentialLabel({ label: initialLabel, operations });
|
|
407
|
+
const card = cards.defineSecretCardTool({
|
|
408
|
+
toolId: operations.ids.save,
|
|
409
|
+
prepare: async () => ({}),
|
|
410
|
+
form: () => form(),
|
|
411
|
+
save: ({ values, signal }) => {
|
|
412
|
+
// The shared save-result path attaches a submitted project key to this site.
|
|
413
|
+
const submission = submissionOf(values);
|
|
414
|
+
displayLabel = redactSecrets({ input: submission.displayLabel }, { exactSecrets: [submission.token] });
|
|
415
|
+
return saveCreateCard({ submission, routeDeps, operations, probe, signal });
|
|
416
|
+
},
|
|
417
|
+
result: ({ run }) => {
|
|
418
|
+
if (run.status === 'saved') {
|
|
419
|
+
// The summary's token hint is for the human outcome only; strip it before returning to the model.
|
|
420
|
+
const credential = { ...run.saved };
|
|
421
|
+
delete credential.tokenHint;
|
|
422
|
+
return { created: true, credential };
|
|
423
|
+
}
|
|
424
|
+
if (run.status === 'blank')
|
|
425
|
+
return { created: false, reason: 'invalid', message: operations.locale.text({ id: 'blank', locale }) };
|
|
426
|
+
if (run.status === 'failed')
|
|
427
|
+
return { created: false, reason: failure?.reason ?? 'error', message: run.safeMessage };
|
|
428
|
+
return { created: false, reason: run.status };
|
|
429
|
+
},
|
|
430
|
+
outcome: ({ run }) => {
|
|
431
|
+
if (run.status === 'saved') {
|
|
432
|
+
const hint = operations.locale.hint({ hint: run.saved.tokenHint, locale });
|
|
433
|
+
return withCardApp({ spec: operations.credentialCardForms.createOutcome({ label: run.saved.label, state: 'success', message: `${hint ? hint + '. ' : ''}${operations.locale.text({ id: 'saved', locale })}` }), app: cardIdentity.appNames.createOutcome });
|
|
434
|
+
}
|
|
435
|
+
if (run.status === 'blank' || run.status === 'failed')
|
|
436
|
+
return withCardApp({ spec: operations.credentialCardForms.createOutcome({ label: displayLabel, state: 'failure',
|
|
437
|
+
message: run.status === 'blank' ? operations.locale.text({ id: 'blank', locale }) : run.safeMessage }), app: cardIdentity.appNames.createOutcome });
|
|
438
|
+
// Cancel/expiry/abandonment already render locally: no second outcome is emitted.
|
|
439
|
+
return undefined;
|
|
440
|
+
},
|
|
441
|
+
}, {
|
|
442
|
+
uriHost: cardIdentity.uriNamespace,
|
|
443
|
+
text: { noEmitter: operations.messages.noCreateChannel, saveFailure: operations.messages.formSaveFailure },
|
|
444
|
+
safeError: err => {
|
|
445
|
+
failure = mapCreateCredentialError({ err, locale, label: displayLabel, operations });
|
|
446
|
+
return failure.message;
|
|
447
|
+
},
|
|
448
|
+
// Fixed exchange metadata only: exception text, the label, and submitted values are unsafe.
|
|
449
|
+
logFailure: metadata => operations.diagnostics.createFailure({ metadata }),
|
|
450
|
+
});
|
|
451
|
+
return card.handler({ surfaceExchanges: surfaces.surfaceExchanges, askThenReport: cards.askThenReport })(ctx, emitSurface ? { emitSurface } : {});
|
|
452
|
+
}
|
|
453
|
+
/**
|
|
454
|
+
* API-key cards with every consumed operation supplied by the composing host.
|
|
455
|
+
*
|
|
456
|
+
* @complexity O(1) wiring; each adapter performs the bounded operations documented on its ports.
|
|
457
|
+
*/
|
|
458
|
+
/** @agent-note create accepts optional label/baseUrl/category/worksFor, rotate requires label and pluginProvider requires provider, while secrets arrive only from human card values. */
|
|
459
|
+
export function createCredentialSaveHandlers({ routeDeps, surfaces, host, ports, cards, operations }, _optional = {}) {
|
|
460
|
+
const probe = (input) => ports.credentialedRequest.probe(input);
|
|
461
|
+
const handlers = {
|
|
462
|
+
// An MCP-UI surface for the SECRET itself — see this file's secret-handling header
|
|
463
|
+
// for the full mechanism and why it holds up "a token must never pass through the model's
|
|
464
|
+
// context" rather than merely "an agent must never write one". Shape validation
|
|
465
|
+
// (`rejectUnexpectedSetTokenFields`) and the label->id resolution both run BEFORE any exchange is
|
|
466
|
+
// opened, same ordering `custom_credential_make_request`'s DELETE gate below uses: a malformed or
|
|
467
|
+
// unresolvable call must never raise a dialog for a human to see. WRITE-gated, same permission
|
|
468
|
+
// `custom_credential_set_username`/`custom_credential_make_request` use.
|
|
469
|
+
rotate: async (ctx, options = {}) => {
|
|
470
|
+
const input = requireInputRecord({ input: ctx.input });
|
|
471
|
+
rejectUnexpectedSetTokenFields({ input, messages: operations.messages });
|
|
472
|
+
const label = requireString({ input, key: "label" });
|
|
473
|
+
await requireToolPermission({ authorize: adaptLegacyAuthorize({ authorize: routeDeps.authorize }), workspaceId: routeDeps.workspaceId, principalId: ctx.principal.id, permission: host.vocabulary.permissions.write }, { entityType: host.vocabulary.entityType });
|
|
474
|
+
// Non-decrypting label->id resolution — same lookup `custom_credential_set_username` above uses,
|
|
475
|
+
// and for the identical reason: a bad label should never cost a decrypt. Only `existing.id` is
|
|
476
|
+
// load-bearing past this point: `saveSetToken` deliberately re-reads the username itself,
|
|
477
|
+
// fresh, right before writing — see its own header for why trusting THIS snapshot's username
|
|
478
|
+
// would be wrong once the human's answer can arrive an arbitrarily long time later.
|
|
479
|
+
const existing = await operations.sets.byLabel({ label });
|
|
480
|
+
if (!existing) {
|
|
481
|
+
throw new CustomCredentialNotFoundError(operations.messages.notFoundLabel({ label }));
|
|
482
|
+
}
|
|
483
|
+
// Fail closed rather than degrade — and, unlike every OTHER gated tool in this codebase, there is
|
|
484
|
+
// deliberately no fallback second-call shape for this one even in principle: that shape is a
|
|
485
|
+
// fresh MODEL-ISSUED tool call carrying the human's answer as its own input, which is exactly the
|
|
486
|
+
// path this tool exists to make impossible for a secret. See this file's header.
|
|
487
|
+
// A `ToolInputError` with the wording unchanged: a bare `Error` is redacted to a 500 that
|
|
488
|
+
// no allowlist rule can rescue. No code prefix — the per-tool suites pin this exact string.
|
|
489
|
+
// The run ended during the pre-dialog reads: the engine opens no dialog for an aborted run.
|
|
490
|
+
// `askThenReport`, not `askOnce` — the engine waits for save and replaces the same card URI.
|
|
491
|
+
const locale = await operations.locale.resolve({ principalId: ctx.principal.id });
|
|
492
|
+
const pluginCard = await operations.pluginCards.find({ workspaceId: routeDeps.workspaceId, saveKind: 'api', target: label });
|
|
493
|
+
let errorSummary = "";
|
|
494
|
+
const card = cards.defineSecretCardTool({
|
|
495
|
+
toolId: operations.ids.save,
|
|
496
|
+
prepare: async () => ({ label }),
|
|
497
|
+
form: ({ prep }) => operations.credentialCardForms.applyPlugin({ card: pluginCard, form: withCardApp({ spec: operations.credentialCardForms.rotate(prep), app: host.cardIdentity.appNames.setToken }) }),
|
|
498
|
+
save: ({ values, signal }) => saveSetToken({ token: values.token, signal, routeDeps, operations, probe, existing, pluginCard, principalId: ctx.principal.id }),
|
|
499
|
+
result: ({ run }) => {
|
|
500
|
+
// Token hints belong on the human's card, never in the model-facing result or audit output.
|
|
501
|
+
if (run.status === "saved")
|
|
502
|
+
return { saved: true };
|
|
503
|
+
if (run.status === "blank")
|
|
504
|
+
return { saved: false, reason: "invalid", message: operations.locale.text({ id: "blank", locale }) };
|
|
505
|
+
if (run.status === "failed")
|
|
506
|
+
return { saved: false, reason: "error", message: run.safeMessage };
|
|
507
|
+
return { saved: false, reason: run.status };
|
|
508
|
+
},
|
|
509
|
+
outcome: ({ run }) => {
|
|
510
|
+
if (run.status === "saved") {
|
|
511
|
+
const hint = operations.locale.hint({ hint: run.saved.tokenHint, locale });
|
|
512
|
+
return withCardApp({ spec: operations.credentialCardForms.rotateOutcome({ label, state: "success", message: `${hint ? hint + ". " : ""}${operations.locale.text({ id: "saved", locale })}` }), app: host.cardIdentity.appNames.setTokenOutcome });
|
|
513
|
+
}
|
|
514
|
+
if (run.status === "blank" || run.status === "failed")
|
|
515
|
+
return withCardApp({ spec: operations.credentialCardForms.rotateOutcome({ label, state: "failure",
|
|
516
|
+
message: run.status === "blank" ? operations.locale.text({ id: "blank", locale }) : run.safeMessage }), app: host.cardIdentity.appNames.setTokenOutcome });
|
|
517
|
+
return undefined;
|
|
518
|
+
},
|
|
519
|
+
}, {
|
|
520
|
+
uriHost: host.cardIdentity.uriNamespace,
|
|
521
|
+
text: { noEmitter: operations.messages.noRotateChannel },
|
|
522
|
+
safeError: err => {
|
|
523
|
+
// Never `err.message`: it can quote the token just submitted. See operations.formErrors.
|
|
524
|
+
errorSummary = operations.diagnostics.describeError({ error: err });
|
|
525
|
+
return operations.locale.translate({ message: callerSafeErrorMessage({ err, rules: operations.formErrors, fallback: operations.messages.formSaveFailure }), locale });
|
|
526
|
+
},
|
|
527
|
+
logFailure: ({ toolId, exchangeId }) => operations.diagnostics.rotateFailure({ toolId, exchangeId, credentialId: existing.id, errorSummary }),
|
|
528
|
+
});
|
|
529
|
+
return card.handler({ surfaceExchanges: surfaces.surfaceExchanges, askThenReport: cards.askThenReport })(ctx, options);
|
|
530
|
+
},
|
|
531
|
+
// Creates a brand-new credential row — see this file's creation-ordering header for the
|
|
532
|
+
// full mechanism and the incident it closes. Unlike every other write handler in this domain, there
|
|
533
|
+
// is no existing row to resolve or fail closed on before opening the form: a CREATE's row does not
|
|
534
|
+
// exist yet, so the only pre-form checks are the permission gate and the `emitSurface` fail-closed
|
|
535
|
+
// guard below. All three prefill fields are optional and non-secret by schema
|
|
536
|
+
// in the host's API creation schema — a call with none of them is a normal, valid call.
|
|
537
|
+
create: async (ctx, { emitSurface } = {}) => {
|
|
538
|
+
// `requireInputRecord` refuses `undefined` outright, but this tool's schema has no required
|
|
539
|
+
// field at all (same `required: []` shape `custom_credential_list`'s own `NO_INPUT_SCHEMA`
|
|
540
|
+
// documents) — a model-issued call with no arguments at all is a normal, valid call here, not a
|
|
541
|
+
// malformed one, so it is treated the same as an explicit `{}` rather than rejected.
|
|
542
|
+
const input = ctx.input === undefined ? {} : requireInputRecord({ input: ctx.input });
|
|
543
|
+
const prefill = readCreateCredentialPrefill({ input, operations });
|
|
544
|
+
await requireToolPermission({ authorize: adaptLegacyAuthorize({ authorize: routeDeps.authorize }), workspaceId: routeDeps.workspaceId, principalId: ctx.principal.id, permission: host.vocabulary.permissions.write }, { entityType: host.vocabulary.entityType });
|
|
545
|
+
const providers = await operations.publish.loadProviders({});
|
|
546
|
+
const locale = await operations.locale.resolve({ principalId: ctx.principal.id });
|
|
547
|
+
return openCreateCard({ ctx, emitSurface, routeDeps, operations, probe, cards, surfaces, locale, initialLabel: prefill.label ?? '', cardIdentity: host.cardIdentity,
|
|
548
|
+
form: () => withCardApp({ spec: operations.credentialCardForms.create({ prefill, providers }), app: host.cardIdentity.appNames.create }),
|
|
549
|
+
submissionOf: values => deriveCreateCredentialSubmission({ raw: readRawCreateCredentialFields(values), operations }) });
|
|
550
|
+
},
|
|
551
|
+
// A plugin's own key card (credential_save kind plugin-provider): plugin copy, a masked token
|
|
552
|
+
// and declared public fields, with fixed row metadata resolved on the server. Same
|
|
553
|
+
// permission, save port and outcome as the generic create card. The host supplies these through operations.pluginCards.
|
|
554
|
+
pluginProvider: async (ctx, { emitSurface } = {}) => {
|
|
555
|
+
const input = requireInputRecord({ input: ctx.input });
|
|
556
|
+
const providerId = requireString({ input, key: "provider" });
|
|
557
|
+
await requireToolPermission({ authorize: adaptLegacyAuthorize({ authorize: routeDeps.authorize }), workspaceId: routeDeps.workspaceId, principalId: ctx.principal.id, permission: host.vocabulary.permissions.write }, { entityType: host.vocabulary.entityType });
|
|
558
|
+
const card = (await operations.pluginCards.load({ workspaceId: routeDeps.workspaceId })).find(entry => entry.providerId === providerId);
|
|
559
|
+
if (!card)
|
|
560
|
+
throw new ToolInputError({ message: operations.messages.missingPluginCard({ providerId }) });
|
|
561
|
+
const locale = await operations.locale.resolve({ principalId: ctx.principal.id });
|
|
562
|
+
return openCreateCard({ ctx, emitSurface, routeDeps, operations, probe, cards, surfaces, locale, initialLabel: card.label, cardIdentity: host.cardIdentity,
|
|
563
|
+
form: () => operations.credentialCardForms.buildPlugin({ card }),
|
|
564
|
+
submissionOf: values => {
|
|
565
|
+
const fields = operations.pluginCards.readValues({ card, values });
|
|
566
|
+
return { ...deriveCreateCredentialSubmission({ raw: readRawCreateCredentialFields({ ...fields, worksFor: [] }), operations }), pluginCard: card,
|
|
567
|
+
...(fields.additionalHosts === undefined ? {} : { additionalHosts: fields.additionalHosts }) };
|
|
568
|
+
} });
|
|
569
|
+
},
|
|
570
|
+
};
|
|
571
|
+
return withModelFacingErrors({ handlers, rules: operations.modelFacingErrors });
|
|
572
|
+
}
|
|
573
|
+
/**
|
|
574
|
+
* Credential tool handlers over required host operations and core-only consumer contracts.
|
|
575
|
+
*
|
|
576
|
+
* @complexity O(t) wiring, plus the bounded costs of each named host operation.
|
|
577
|
+
*/
|
|
578
|
+
/** @agent-note operations.ids must exactly match catalog, metadata and risk names and the host answer routing. */
|
|
579
|
+
export function createCredentialToolRegistrations({ routeDeps, host, ports, operations }, _optional = {}) {
|
|
580
|
+
const { credentialedRequest, sourceControlWrite } = ports;
|
|
581
|
+
const handlers = {
|
|
582
|
+
// Non-decrypting read-back through the existing store, scoped by the read permission and
|
|
583
|
+
// empty-input contract. Saved origins and usernames reach the model; token hints remain
|
|
584
|
+
// on human surfaces. One workspace read plus O(n + c) projection for saved rows and active cards.
|
|
585
|
+
[operations.ids.list]: async (ctx) => {
|
|
586
|
+
requireNoInput({ input: ctx.input });
|
|
587
|
+
await requireToolPermission({ authorize: adaptLegacyAuthorize({ authorize: routeDeps.authorize }), workspaceId: routeDeps.workspaceId, principalId: ctx.principal.id, permission: host.vocabulary.permissions.read }, { entityType: host.vocabulary.entityType });
|
|
588
|
+
const credentials = await operations.sets.list({});
|
|
589
|
+
const cards = await operations.pluginCards.load({ workspaceId: routeDeps.workspaceId });
|
|
590
|
+
const apiCards = new Map(cards.filter(card => card.saveKind === undefined || card.saveKind === 'api').map(card => [card.ownedApiLabel ?? card.label, card]));
|
|
591
|
+
// Exact owned labels attach display copy only; usedFor never participates in key selection.
|
|
592
|
+
return { credentials: credentials.map(({ tokenHint: _humanHint, ...credential }) => {
|
|
593
|
+
const card = apiCards.get(credential.label);
|
|
594
|
+
return card ? { ...credential, pluginId: card.pluginId, usedFor: card.usedFor ?? [] } : credential;
|
|
595
|
+
}) };
|
|
596
|
+
},
|
|
597
|
+
[operations.ids.verify]: async (ctx) => {
|
|
598
|
+
const input = requireInputRecord({ input: ctx.input });
|
|
599
|
+
const label = requireString({ input, key: "label" });
|
|
600
|
+
await requireToolPermission({ authorize: adaptLegacyAuthorize({ authorize: routeDeps.authorize }), workspaceId: routeDeps.workspaceId, principalId: ctx.principal.id, permission: host.vocabulary.permissions.read }, { entityType: host.vocabulary.entityType });
|
|
601
|
+
return operations.recovery.withSetup({ label, verification: true, invoke: () => credentialedRequest.verify({ workspaceId: routeDeps.workspaceId, label }) }, {});
|
|
602
|
+
},
|
|
603
|
+
// The self-healing FIX half of the 401/403 diagnostic `custom_credential_verify`/
|
|
604
|
+
// `custom_credential_make_request` now carry (`../credentialed-request.ts`'s `AuthFailureDiagnostic`)
|
|
605
|
+
// — see this file's username-update header for the full incident and design.
|
|
606
|
+
// Shape/security validation (`rejectUnexpectedSetUsernameFields`, `requireUsernameOrClearSentinel`)
|
|
607
|
+
// runs BEFORE the permission check, same ordering `custom_credential_make_request` below uses — a
|
|
608
|
+
// malformed call is refused on its own terms regardless of who is asking. WRITE-gated (this durably
|
|
609
|
+
// changes a host-side column), and — by the owner's own standing "no confirm ceremonies" instruction
|
|
610
|
+
// — deliberately NOT wrapped in the DELETE-style confirmation dialog: this field is not a secret,
|
|
611
|
+
// and there is structurally no way for this call to carry one.
|
|
612
|
+
[operations.ids.setUsername]: async (ctx) => {
|
|
613
|
+
const input = requireInputRecord({ input: ctx.input });
|
|
614
|
+
rejectUnexpectedSetUsernameFields({ input, messages: operations.messages });
|
|
615
|
+
const label = requireString({ input, key: "label" });
|
|
616
|
+
const username = requireUsernameOrClearSentinel({ input, messages: operations.messages });
|
|
617
|
+
await requireToolPermission({ authorize: adaptLegacyAuthorize({ authorize: routeDeps.authorize }), workspaceId: routeDeps.workspaceId, principalId: ctx.principal.id, permission: host.vocabulary.permissions.write }, { entityType: host.vocabulary.entityType });
|
|
618
|
+
// Non-decrypting label->id resolution — same lookup `resolveRequestTarget` above uses for the
|
|
619
|
+
// identical reason: a bad label should never cost a decrypt, and this update never needs one
|
|
620
|
+
// either (see `CustomCredentialsToolDeps.siteAssistantSecretKeyring`'s own doc).
|
|
621
|
+
const existing = await operations.sets.byLabel({ label });
|
|
622
|
+
if (!existing) {
|
|
623
|
+
throw new CustomCredentialNotFoundError(operations.messages.notFoundLabel({ label }));
|
|
624
|
+
}
|
|
625
|
+
return operations.sets.setUsername({ id: existing.id, username });
|
|
626
|
+
},
|
|
627
|
+
// GET/POST/PUT/PATCH run immediately (no ceremony — parity with the site). DELETE opens an
|
|
628
|
+
// in-chat confirmation and parks until answered; see this file's own header for the full
|
|
629
|
+
// mechanism and why. All shape/security-boundary validation (`method`/`url`/`headers`/`body`,
|
|
630
|
+
// label existence, host allowlist) happens inside `resolveRequestTarget`/`makeCredentialedRequest`
|
|
631
|
+
// themselves — this handler's only job is deciding WHETHER to gate, never re-validating.
|
|
632
|
+
[operations.ids.makeRequest]: async (ctx, { emitSurface } = {}) => {
|
|
633
|
+
ctx = { ...ctx, input: structuredClone(ctx.input), principal: { ...ctx.principal }, run: { ...ctx.run } };
|
|
634
|
+
const input = requireInputRecord({ input: ctx.input });
|
|
635
|
+
const label = requireString({ input, key: "label" });
|
|
636
|
+
const method = requireString({ input, key: "method" });
|
|
637
|
+
const url = requireString({ input, key: "url" });
|
|
638
|
+
await requireToolPermission({ authorize: adaptLegacyAuthorize({ authorize: routeDeps.authorize }), workspaceId: routeDeps.workspaceId, principalId: ctx.principal.id, permission: host.vocabulary.permissions.write }, { entityType: host.vocabulary.entityType });
|
|
639
|
+
if (method !== "DELETE") {
|
|
640
|
+
return operations.recovery.withSetup({ label, url, invoke: () => makeModelFacingCredentialedRequest({ port: credentialedRequest, input: { workspaceId: routeDeps.workspaceId, label, method, url, headers: input.headers, body: input.body }, catalog: host.vocabulary.catalog, toolId: operations.ids.makeRequest }) }, {});
|
|
641
|
+
}
|
|
642
|
+
// Non-decrypting: a declined/expired/off-allowlist DELETE must never have cost a decrypt.
|
|
643
|
+
// Classify the original preflight rejection once before map-level message publication.
|
|
644
|
+
// Preserve the validation class and existing DELETE text; only caller-safe copy may enter it.
|
|
645
|
+
// Other rejection identities stay unchanged. Schema decoration here would change that text.
|
|
646
|
+
const target = await operations.recovery.withSetup({ label, url, invoke: async () => {
|
|
647
|
+
try {
|
|
648
|
+
return await credentialedRequest.resolveTarget({ workspaceId: routeDeps.workspaceId, label, url });
|
|
649
|
+
}
|
|
650
|
+
catch (error) {
|
|
651
|
+
const classified = credentialedRequest.classifyError({ error });
|
|
652
|
+
if (classified.category === "validation")
|
|
653
|
+
throw new CredentialedRequestValidationError({ message: classified.callerSafeMessage });
|
|
654
|
+
throw error;
|
|
655
|
+
}
|
|
656
|
+
} }, {});
|
|
657
|
+
if ("credentialSetup" in target)
|
|
658
|
+
return target;
|
|
659
|
+
// Fail closed rather than degrade — same posture `content_post_delete`'s own handler documents:
|
|
660
|
+
// an execution context that cannot hold this call open cannot run a gated DELETE at all.
|
|
661
|
+
if (!emitSurface) {
|
|
662
|
+
// A `ToolInputError` with the wording unchanged: a bare `Error` is redacted to a 500 that
|
|
663
|
+
// no allowlist rule can rescue. No code prefix — the per-tool suites pin this exact string.
|
|
664
|
+
throw new ToolInputError({ message: operations.messages.noDeleteChannel });
|
|
665
|
+
}
|
|
666
|
+
// A run aborted during reconnaissance must not proceed to the external commit.
|
|
667
|
+
if (ctx.signal.aborted)
|
|
668
|
+
return { executed: false, cancelled: false, reason: "abandoned" };
|
|
669
|
+
return operations.approval.handler({
|
|
670
|
+
prepare: async () => ({ label: target.label, host: target.url.host, path: `${target.url.pathname}${target.url.search}` }),
|
|
671
|
+
describe: ({ prepared }) => ({ ask: true, description: operations.approval.describeDelete(prepared) }),
|
|
672
|
+
askHuman: (required, optional) => operations.approval.askHuman(required, optional),
|
|
673
|
+
run: async ({ ctx: approvedCtx }) => {
|
|
674
|
+
await requireToolPermission({ authorize: adaptLegacyAuthorize({ authorize: routeDeps.authorize }), workspaceId: routeDeps.workspaceId, principalId: approvedCtx.principal.id, permission: host.vocabulary.permissions.write }, { entityType: host.vocabulary.entityType });
|
|
675
|
+
if (approvedCtx.signal.aborted)
|
|
676
|
+
return { executed: false, cancelled: false, reason: "abandoned" };
|
|
677
|
+
const frozen = requireInputRecord({ input: approvedCtx.input });
|
|
678
|
+
return operations.recovery.withSetup({ label, url, invoke: () => makeModelFacingCredentialedRequest({ port: credentialedRequest, input: { workspaceId: routeDeps.workspaceId, label, method: "DELETE", url, headers: frozen.headers, body: frozen.body }, catalog: host.vocabulary.catalog, toolId: operations.ids.makeRequest }) }, {});
|
|
679
|
+
},
|
|
680
|
+
notConfirmed: ({ reason }) => reason === "declined" ? { executed: false, cancelled: true } : { executed: false, cancelled: false, reason },
|
|
681
|
+
})(ctx, { emitSurface });
|
|
682
|
+
},
|
|
683
|
+
// See this file's header for file-write validation, provider-plan and freshness boundaries.
|
|
684
|
+
[operations.ids.writeFiles]: async (ctx) => {
|
|
685
|
+
const input = requireInputRecord({ input: ctx.input });
|
|
686
|
+
const label = requireString({ input, key: "label" });
|
|
687
|
+
const shapeRejection = { toolId: operations.ids.writeFiles, catalog: host.vocabulary.catalog, isShapeRejection: ({ error }) => isWriteFilesShapeRejection(error) };
|
|
688
|
+
const request = await withSchemaOnRejection({ ...shapeRejection, fn: async () => operations.policy.validateWriteFiles({ branch: input.branch, commitMessage: input.commitMessage, files: input.files })
|
|
689
|
+
});
|
|
690
|
+
await requireToolPermission({ authorize: adaptLegacyAuthorize({ authorize: routeDeps.authorize }), workspaceId: routeDeps.workspaceId, principalId: ctx.principal.id, permission: host.vocabulary.permissions.write }, { entityType: host.vocabulary.entityType });
|
|
691
|
+
// The host first, from the credential's plaintext base URL (no decrypt): its owner/repo rules
|
|
692
|
+
// decide whether this call is well formed at all.
|
|
693
|
+
const summary = await operations.sets.byLabel({ label });
|
|
694
|
+
if (!summary) {
|
|
695
|
+
throw new CustomCredentialNotFoundError(operations.messages.notFoundLabel({ label }));
|
|
696
|
+
}
|
|
697
|
+
const built = await sourceControlWrite.build({ workspaceId: routeDeps.workspaceId, baseUrl: summary.baseUrl });
|
|
698
|
+
if (!built.ok)
|
|
699
|
+
throw new Error(operations.messages.writeFailure({ message: built.message }));
|
|
700
|
+
const provider = built.provider;
|
|
701
|
+
const target = await withSchemaOnRejection({ ...shapeRejection, fn: async () => sourceControlWrite.validateTarget({ provider, target: { owner: input.owner, repo: input.repo } }) });
|
|
702
|
+
const validated = { ...request, ...target };
|
|
703
|
+
// A DECRYPTING resolve: the plan phase's read-only host calls need the token regardless of
|
|
704
|
+
// whether the human goes on to confirm. The row was just seen above; one deleted in between
|
|
705
|
+
// is the same not-found refusal.
|
|
706
|
+
const resolved = await operations.sets.resolve({ label });
|
|
707
|
+
if (!resolved) {
|
|
708
|
+
throw new CustomCredentialNotFoundError(operations.messages.notFoundLabel({ label }));
|
|
709
|
+
}
|
|
710
|
+
const planResult = await sourceControlWrite.planFileWrite({ provider, input: { ...writeTarget(resolved, validated), branch: validated.branch, files: validated.files } });
|
|
711
|
+
if (!planResult.ok) {
|
|
712
|
+
operations.diagnostics.writeFailure({ phase: "plan", failure: planResult });
|
|
713
|
+
throw new Error(operations.messages.writeFailure({ message: planResult.message }));
|
|
714
|
+
}
|
|
715
|
+
// A run aborted during reconnaissance must not proceed to the external commit.
|
|
716
|
+
if (ctx.signal.aborted)
|
|
717
|
+
return { executed: false, cancelled: false, reason: "abandoned" };
|
|
718
|
+
return performRepositoryFilesWrite({ operations, port: sourceControlWrite, provider, resolved, validated, plan: planResult.plan });
|
|
719
|
+
},
|
|
720
|
+
};
|
|
721
|
+
return buildDomainRegistrations({ metadata: host.vocabulary.metadata,
|
|
722
|
+
domain: host.vocabulary.domain,
|
|
723
|
+
catalogModule: host.vocabulary.catalogModule,
|
|
724
|
+
catalog: host.vocabulary.catalog,
|
|
725
|
+
handlers: withModelFacingErrors({ handlers, rules: operations.modelFacingErrors }),
|
|
726
|
+
derivedRisk: operations.derivedRisk,
|
|
727
|
+
});
|
|
728
|
+
}
|
|
729
|
+
//# sourceMappingURL=tool-registrations.js.map
|