@jini-ai/integrations 0.4.3 → 0.6.11

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 CHANGED
@@ -1,5 +1,100 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.6.11
4
+
5
+ ### Patch Changes
6
+
7
+ - `probeCredentialConnection`: a GET-only credential probe on `credentialed-http`.
8
+ - Updated dependencies
9
+ - Updated dependencies
10
+ - @jini-ai/core@0.6.11
11
+
12
+ ## 0.6.10
13
+
14
+ ### Patch Changes
15
+
16
+ - 39b3f97: Name the update operation when refusing edits to a disabled (deleted) webhook subscription.
17
+ - 9b30143: Add `@jini-ai/integrations/saved-requests`: a declarative fixed-target HTTPS interpreter
18
+ with closed bounded input schemas, query/JSON-body value bindings, host-resolved credential
19
+ IDs and revision/origin binding, and typed positive output selection marked as untrusted.
20
+ Reuse credentialed HTTP authentication, redaction and audit over platform guarded egress
21
+ with no redirects, private-address denial, 64 KiB response/decompression caps and a 10s
22
+ deadline. Requires the existing optional platform and JSON-schema peers for this subpath.
23
+
24
+ Add the opt-in `makeCredentialedRequest` option `responseFormat: "json"` for decoded JSON
25
+ secret redaction, including refusal of credential-bearing keys/numbers and incomplete JSON.
26
+
27
+ - dc6efe5: Composio and the media-provider gateway collapse from two sibling packages under
28
+ `packages/integrations/` into subpaths of one package: `@jini-ai/integrations/composio` and
29
+ `@jini-ai/integrations/media-providers`. An npm package name allows only one slash, so the literal
30
+ import paths the repo owner wants require exactly this shape — one package with two subpath
31
+ exports, not two packages grouped under a shared directory.
32
+
33
+ This closes out two moves that happened earlier the same day. Composio was folded into
34
+ `@jini-ai/admin` as `./server` on 2026-08-01, then un-folded back into its own package under its
35
+ original published name, `@jini-ai/composio` (see the now-superseded
36
+ `composio-un-retirement.md`) — that un-retirement was never itself published, so no registry
37
+ version exists under that name beyond the pre-fold `0.2.1`. `@jini-ai/media` was separately renamed
38
+ and relocated to `@jini-ai/integrations-media-providers` (see the now-superseded
39
+ `media-providers-rename.md`); that rename was likewise never published — its own text notes the
40
+ version stays at `0.1.2` on disk pending a real release. Both collapse directly into this package's
41
+ two subpaths without ever taking an independent consumer-facing release under either intermediate
42
+ name.
43
+
44
+ **Breaking: `better-sqlite3` becomes an optional peer dependency of `./media-providers`, not a
45
+ regular dependency.** The concern that originally kept these as two separate packages — a
46
+ composio-only consumer being forced to install `better-sqlite3`, a native compiled addon — no
47
+ longer applies once both integrations share one package, because `better-sqlite3` is only ever
48
+ reached through a dynamic `await import('better-sqlite3')` inside `createSqliteMediaTaskStore`;
49
+ every other `./media-providers` export (the dispatch engine, capability registry, in-memory task
50
+ store, `renderStub`) never touches it. A consumer who calls `createSqliteMediaTaskStore` must now
51
+ `npm install better-sqlite3` themselves; everyone else installs nothing extra. This mirrors
52
+ `@jini-ai/admin`'s `react`/`react-dom` optional-peer convention.
53
+
54
+ No production logic changed — every file moved as-is from
55
+ `packages/integrations/{composio,media-providers}/src/**` into
56
+ `packages/integrations/src/{composio,media-providers}/**`. `examples/reference-web`, the one real
57
+ consumer of `./media-providers` in this workspace, is updated to the new import specifier.
58
+
59
+ **The standalone published names `@jini-ai/media` (`0.1.2`) and `@jini-ai/composio`
60
+ (`0.1.0`, `0.2.0`, `0.2.1`) are retired for good** — neither is versioned forward under its own
61
+ identity again. `@jini-ai/composio`'s deprecation was already flagged as a release
62
+ follow-up in `fold-composio-into-admin.md` (from the 2026-08-01 fold) and, as far as this workspace
63
+ shows, never acted on; it is restated here since it is still outstanding. `@jini-ai/media`'s
64
+ deprecation was not previously flagged anywhere. Whoever runs the next release should run both:
65
+
66
+ ```
67
+ npm deprecate @jini-ai/media "Renamed and merged into @jini-ai/integrations; import from '@jini-ai/integrations/media-providers' instead."
68
+ npm deprecate @jini-ai/composio "Merged into @jini-ai/integrations; import from '@jini-ai/integrations/composio' instead."
69
+ ```
70
+
71
+ - dc6efe5: Add `@jini-ai/integrations/media-providers/catalog` — a browser-safe entry exporting only the
72
+ vendor catalogue (`providers.ts`) and its types (`types.ts`).
73
+
74
+ The existing `./media-providers` entry is `jini.runtime: "node"` and its barrel statically pulls in
75
+ `node:crypto`/`node:fs`/`node:path` (`staging.ts`), `node:dns` (`dispatch/ssrf-guard.ts`), and
76
+ `undici` (`dispatch/providers/openai.ts`). A browser consumer that only needs the provider list to
77
+ render a credentials screen — Tovu's admin SPA is the first — previously had no way to get it
78
+ without dragging the whole dispatch engine into its bundle.
79
+
80
+ `providers.ts` imports only types from `types.ts`, and `types.ts` imports nothing, so the pair is
81
+ genuinely dependency-free; the new entry is marked `"universal"` in `jini.entries`. Verified by
82
+ importing the built subpath from a directory containing nothing but this package's `dist/` and
83
+ `package.json` — 11 exports, 25 vendors, no dispatch symbols reachable — while
84
+ `./media-providers` fails with `ERR_MODULE_NOT_FOUND` on `@jini-ai/core` in the same environment.
85
+
86
+ `__tests__/catalog.test.ts` walks the transitive source graph and asserts it contains exactly
87
+ `catalog.ts`/`providers.ts`/`types.ts` with zero bare import specifiers, so re-exporting anything
88
+ node-bound from this entry fails a test rather than a downstream bundle.
89
+
90
+ Additive only — no existing entry, export, or type changed.
91
+
92
+ - ea8d883: Refuse subscription updates after soft deletion, before target validation or repository writes.
93
+ - Updated dependencies [22f0619]
94
+ - Updated dependencies [82ed2d3]
95
+ - Updated dependencies [5a3de86]
96
+ - @jini-ai/core@0.6.10
97
+
3
98
  ## 0.4.3 — 2026-10-22
4
99
 
5
100
  - 2026-10-22: Webhook delivery deadlines, leases and fencing; media-provider model-id collision refusal; provider contributions.
@@ -61,7 +156,6 @@
61
156
  - Composio retains 2000ms timeout, 10ms polling and no age/dead-owner stealing. Shared locking adds owned-create cleanup and inode/device snapshot checks.
62
157
  - Native fetch ABIs and media egress paths remain unchanged; provider-host policy retains existing loopback allowance.
63
158
 
64
-
65
159
  ## Unreleased
66
160
 
67
161
  - Add `./credentialed-http`: resolver, HTTP, scheme-registry and audit ports; origin binding,
package/README.md CHANGED
@@ -8,6 +8,7 @@ exports. Import the capability you need; each entry owns its dependencies and ru
8
8
  | `./media-providers` | Node | Image/video/audio gateway, policy, staging and task stores |
9
9
  | `./media-providers/catalog` | Universal | Browser-safe provider/model catalog |
10
10
  | `./credentialed-http` | Node | Credential-origin binding, authentication, redacted responses and audit ports |
11
+ | `./saved-requests` | Node | Fixed-target declarative requests, bounded schemas and typed public projections |
11
12
  | `./webhooks` | Node | Subscriptions, delivery/retries and signing through host ports |
12
13
 
13
14
  ## No root `.` export
@@ -72,6 +72,10 @@ export interface CredentialedRequestDeps {
72
72
  export interface CredentialedRequestOptions {
73
73
  readonly headers?: unknown;
74
74
  readonly body?: unknown;
75
+ /** Opt-in structured redaction after transport completeness checks. Existing text callers keep
76
+ * their original body formatting. JSON escapes cannot disguise a reflected credential value;
77
+ * credential-bearing keys and numbers refuse the body rather than changing its schema/types. */
78
+ readonly responseFormat?: "json";
75
79
  readonly errorPolicy?: CredentialedRequestErrorPolicyPort;
76
80
  readonly diagnosticMapper?: (required: {
77
81
  diagnostic: AuthFailureDiagnostic;
@@ -91,20 +95,53 @@ export declare function resolveRequestTarget(required: {
91
95
  url: URL;
92
96
  }>;
93
97
  export type CustomCredentialCheckStatus = "valid" | "invalid" | "unreachable";
98
+ /** A refusal establishes only that this GET was refused, not that the key is invalid. */
99
+ export type CredentialConnectionProbeStatus = "ok" | "refused" | "unavailable";
100
+ /** Host-owned probe input. The host must resolve the plugin-declared URL against the saved base
101
+ * origin before calling; no credential store or plugin/model-input parser is loaded here. */
102
+ export interface CredentialConnectionProbeInput {
103
+ readonly connection: CredentialConnection;
104
+ readonly url: string;
105
+ readonly schemes: readonly CredentialSchemeRule[];
106
+ /** Omit for GET. Explicit methods are checked at runtime, including untyped callers. */
107
+ readonly method?: "GET";
108
+ }
109
+ /** Send one bodyless GET through the guarded HTTP port without following redirects.
110
+ * @param required Plaintext connection, trusted host-resolved URL and auth-scheme rules.
111
+ * @param options Guarded HTTP client; owns DNS/address policy, peer pinning and response bounds.
112
+ * @returns Only ok/refused/unavailable; no bodies, headers, URLs, secrets or transport errors.
113
+ * @throws CredentialedRequestValidationError with value-free text for non-GET or malformed URLs.
114
+ * @complexity One bounded HTTP send plus O(r) auth matching for r supplied scheme rules.
115
+ * @example await probeCredentialConnection({ connection, url, schemes }, { httpClient });
116
+ */
117
+ export declare function probeCredentialConnection(required: CredentialConnectionProbeInput, options: {
118
+ httpClient: HttpClientPort;
119
+ }): Promise<CredentialConnectionProbeStatus>;
94
120
  export interface CustomCredentialVerificationResult {
95
121
  readonly status: CustomCredentialCheckStatus;
96
122
  readonly message: string;
97
123
  readonly checkedAt: string;
98
124
  readonly authDiagnostic?: AuthFailureDiagnostic;
99
125
  }
100
- /** Probe the saved origin root and classify 2xx/401/403/other outcomes; audit without returning response bodies. */
126
+ export interface CustomCredentialVerificationOptions extends CredentialedRequestOptions {
127
+ /** Trusted plugin-declared path relative to baseUrl; omission keeps the origin-root probe. */
128
+ readonly path?: string;
129
+ }
130
+ /** Probe the origin root or a trusted relative path; retain verification messages, diagnostics and audit.
131
+ * @param required Resolver/HTTP/audit ports and workspace-bound credential identity.
132
+ * @param optional Optional relative path and existing diagnostic mapping policy.
133
+ * @returns The existing valid/invalid/unreachable result, without response bodies or secrets.
134
+ * @throws CredentialedRequestValidationError for invalid labels/paths; resolver/registry errors propagate.
135
+ * @complexity One credential resolution, registry load and bounded HTTP probe; O(r) scheme matching.
136
+ * @example await verifyCustomCredential({ deps, input }, { path: "/user" });
137
+ */
101
138
  export declare function verifyCustomCredential(required: {
102
139
  deps: CredentialedRequestDeps;
103
140
  input: {
104
141
  workspaceId: UUID;
105
142
  label: unknown;
106
143
  };
107
- }, optional?: CredentialedRequestOptions): Promise<CustomCredentialVerificationResult>;
144
+ }, optional?: CustomCredentialVerificationOptions): Promise<CustomCredentialVerificationResult>;
108
145
  export interface CredentialedRequestExecutedResult {
109
146
  readonly executed: true;
110
147
  readonly status: number;
@@ -9,7 +9,7 @@
9
9
  import { IntegrationError } from "../argument-error.js";
10
10
  import { nowIso } from "@jini-ai/core/primitives";
11
11
  import { detectSelfDescribingAuthScheme } from "./auth-schemes.js";
12
- import { redactResponseHeaders, resolveRedactedResponseBody } from "./response-redaction.js";
12
+ import { redactJsonResponseBody, redactResponseHeaders, resolveRedactedResponseBody } from "./response-redaction.js";
13
13
  export class CredentialNotFoundError extends IntegrationError {
14
14
  }
15
15
  // Multiple saved origins support providers with separate API hosts. A single absolute URL keeps
@@ -45,10 +45,10 @@ function validateMethod(raw) {
45
45
  }
46
46
  return raw;
47
47
  }
48
- // This binds the original caller URL only. Any redirect comes from the already-approved host;
49
- // the injected transport must recheck its address and strip credentials on cross-origin hops,
50
- // rather than widening its global egress allowlist to make the redirected host reachable.
51
- function resolveAllowedRequestUrl(candidate, allowedOrigins) {
48
+ /** Parse an absolute HTTP(S) request URL without userinfo; no I/O or credential-origin decision.
49
+ * @throws CredentialedRequestValidationError for malformed input.
50
+ * @complexity O(n) parsing for n URL characters. */
51
+ function parseRequestUrl(candidate) {
52
52
  if (typeof candidate !== "string" || candidate.trim() === "") {
53
53
  throw new CredentialedRequestValidationError({ message: "url must be a non-empty string" });
54
54
  }
@@ -65,6 +65,13 @@ function resolveAllowedRequestUrl(candidate, allowedOrigins) {
65
65
  if (parsed.username || parsed.password) {
66
66
  throw new CredentialedRequestValidationError({ message: "url must not embed credentials (user:pass@) — the server injects the real Authorization header itself" });
67
67
  }
68
+ return parsed;
69
+ }
70
+ // This binds the original caller URL only. Any redirect comes from the already-approved host;
71
+ // the injected transport must recheck its address and strip credentials on cross-origin hops,
72
+ // rather than widening its global egress allowlist to make the redirected host reachable.
73
+ function resolveAllowedRequestUrl(candidate, allowedOrigins) {
74
+ const parsed = parseRequestUrl(candidate);
68
75
  if (!allowedOrigins.includes(parsed.origin)) {
69
76
  throw new CredentialedRequestValidationError({ message: `url '${candidate}' resolves to origin '${parsed.origin}', which is not one of this credential's saved hosts (${allowedOrigins.join(", ")})` });
70
77
  }
@@ -200,14 +207,54 @@ async function resolveCredentialOrThrow(deps, input) {
200
207
  throw new CredentialNotFoundError({ message: `no custom credential labeled '${input.label}' in this workspace` });
201
208
  return resolved;
202
209
  }
203
- // Only 401/403 affirmatively reject it; redirects and other statuses reaching this classifier say
204
- // nothing about validity. Keep this local rather than coupling independent provider features.
205
- function classifyCustomCredentialStatus(status) {
210
+ /** Send one bodyless GET through the guarded HTTP port without following redirects.
211
+ * @param required Plaintext connection, trusted host-resolved URL and auth-scheme rules.
212
+ * @param options Guarded HTTP client; owns DNS/address policy, peer pinning and response bounds.
213
+ * @returns Only ok/refused/unavailable; no bodies, headers, URLs, secrets or transport errors.
214
+ * @throws CredentialedRequestValidationError with value-free text for non-GET or malformed URLs.
215
+ * @complexity One bounded HTTP send plus O(r) auth matching for r supplied scheme rules.
216
+ * @example await probeCredentialConnection({ connection, url, schemes }, { httpClient });
217
+ */
218
+ export async function probeCredentialConnection(required, options) {
219
+ if (required.method !== undefined && required.method !== "GET") {
220
+ throw new CredentialedRequestValidationError({ message: "credential probes only support GET" });
221
+ }
222
+ let url;
223
+ try {
224
+ url = parseRequestUrl(required.url);
225
+ }
226
+ catch {
227
+ // URL parse errors may contain their input; probe failures must never echo caller values.
228
+ throw new CredentialedRequestValidationError({ message: "credential probe requires an absolute HTTP(S) URL without embedded credentials" });
229
+ }
230
+ return classifyCredentialProbeStatus(await sendCredentialGet({ ...required, url, httpClient: options.httpClient }, { strict: true }));
231
+ }
232
+ /** One bodyless authenticated GET shared by the probe and verification. Returns the HTTP status,
233
+ * or 0 when the transport failed; transport errors are dropped because they can echo request values.
234
+ * `strict` refuses redirects and bounds the whole operation (the probe contract); verification omits
235
+ * it to keep its original follow-redirect, idle-timeout-only policy so its results do not change.
236
+ * @complexity One HTTP send plus O(r) auth matching for r scheme rules. */
237
+ async function sendCredentialGet(required, optional = {}) {
238
+ try {
239
+ const response = await required.httpClient.send({ request: {
240
+ method: "GET", url: required.url.href,
241
+ headers: { Authorization: buildAuthorizationHeader(required) },
242
+ timeoutMs: CREDENTIALED_REQUEST_TIMEOUT_MS,
243
+ ...(optional.strict ? { totalDeadlineMs: CREDENTIALED_REQUEST_TIMEOUT_MS } : {}),
244
+ } }, optional.strict ? { redirect: "error" } : undefined);
245
+ return response.status;
246
+ }
247
+ catch {
248
+ return 0;
249
+ }
250
+ }
251
+ /** Classify only affirmative success/refusal; redirects and all other statuses are inconclusive. */
252
+ function classifyCredentialProbeStatus(status) {
206
253
  if (status >= 200 && status < 300)
207
- return "valid";
254
+ return "ok";
208
255
  if (isAuthRejectionStatus(status))
209
- return "invalid";
210
- return "unreachable";
256
+ return "refused";
257
+ return "unavailable";
211
258
  }
212
259
  // 401 and 403 are the only affirmative authentication rejections; both classification and
213
260
  // diagnostics key off this one predicate so they cannot disagree.
@@ -223,7 +270,32 @@ function buildVerificationMessage(label, status, outcome) {
223
270
  }
224
271
  return `Could not get a clear accept or reject from '${label}' (HTTP ${status}) — this does not necessarily mean the credential is bad.`;
225
272
  }
226
- /** Probe the saved origin root and classify 2xx/401/403/other outcomes; audit without returning response bodies. */
273
+ /** Resolve an optional relative probe path against the saved primary base, never additional hosts.
274
+ * Invalid stored URLs/paths produce value-free errors before any HTTP send.
275
+ * @complexity O(n) URL parsing for n URL/path characters; no I/O. */
276
+ function resolveVerificationUrl(baseUrl, path) {
277
+ try {
278
+ const base = parseRequestUrl(baseUrl);
279
+ if (path === undefined)
280
+ return new URL("/", base);
281
+ // Schemes and network-path references ("//host") are absolute, even when they repeat the saved host.
282
+ if (typeof path === "string" && path.trim() !== "" && !/[\u0000-\u001f\u007f]/.test(path) && !/^([a-z][a-z\d+.-]*:|[\\/]{2})/i.test(path.trim())) {
283
+ return resolveAllowedRequestUrl(new URL(path, base).href, [base.origin]);
284
+ }
285
+ }
286
+ catch {
287
+ // Fall through: URL errors can echo their input, so every failure gets the same value-free text.
288
+ }
289
+ throw new CredentialedRequestValidationError({ message: "probe path must be relative to the saved base URL and remain on its origin" });
290
+ }
291
+ /** Probe the origin root or a trusted relative path; retain verification messages, diagnostics and audit.
292
+ * @param required Resolver/HTTP/audit ports and workspace-bound credential identity.
293
+ * @param optional Optional relative path and existing diagnostic mapping policy.
294
+ * @returns The existing valid/invalid/unreachable result, without response bodies or secrets.
295
+ * @throws CredentialedRequestValidationError for invalid labels/paths; resolver/registry errors propagate.
296
+ * @complexity One credential resolution, registry load and bounded HTTP probe; O(r) scheme matching.
297
+ * @example await verifyCustomCredential({ deps, input }, { path: "/user" });
298
+ */
227
299
  // Probe the primary saved origin to answer whether the credential works at all, rather than trying
228
300
  // every additional API host. Provider bodies never belong in verification results; transport failure
229
301
  // remains "unreachable", and only an affirmative auth rejection has a diagnostic worth attaching.
@@ -232,25 +304,16 @@ export async function verifyCustomCredential(required, optional = {}) {
232
304
  const label = requireLabel(input.label);
233
305
  const checkedAt = nowIso({ clock: deps.clock });
234
306
  const { baseUrl, connection } = await resolveCredentialOrThrow(deps, { workspaceId: input.workspaceId, label });
235
- const url = new URL(`${new URL(baseUrl).origin}/`);
307
+ const url = resolveVerificationUrl(baseUrl, optional.path);
236
308
  const auditBase = { label, host: url.hostname, method: "GET", bodyBytes: 0, at: checkedAt };
237
309
  const schemes = await deps.schemeRegistry.load({ workspaceId: input.workspaceId });
238
- let status;
239
- try {
240
- const response = await deps.httpClient.send({ request: {
241
- method: "GET",
242
- url: url.toString(),
243
- headers: { Authorization: buildAuthorizationHeader({ connection, schemes }) },
244
- timeoutMs: CREDENTIALED_REQUEST_TIMEOUT_MS,
245
- } });
246
- status = response.status;
247
- }
248
- catch {
249
- deps.audit.record({ entry: auditEntry(auditBase, 0) });
310
+ const status = await sendCredentialGet({ connection, url, schemes, httpClient: deps.httpClient });
311
+ deps.audit.record({ entry: auditEntry(auditBase, status) });
312
+ if (status === 0) {
250
313
  return { status: "unreachable", message: `Could not reach '${label}' to verify this credential — this does not necessarily mean the credential is bad.`, checkedAt };
251
314
  }
252
- deps.audit.record({ entry: auditEntry(auditBase, status) });
253
- const outcome = classifyCustomCredentialStatus(status);
315
+ const outcomes = { ok: "valid", refused: "invalid", unavailable: "unreachable" };
316
+ const outcome = outcomes[classifyCredentialProbeStatus(status)];
254
317
  const authDiagnostic = isAuthRejectionStatus(status) ? mapAuthDiagnostic(connection, status, schemes, optional) : undefined;
255
318
  return { status: outcome, message: buildVerificationMessage(label, status, outcome), checkedAt, ...(authDiagnostic ? { authDiagnostic } : {}) };
256
319
  }
@@ -328,8 +391,22 @@ function buildExecutedResult(required, optional) {
328
391
  executed: true,
329
392
  status: response.status,
330
393
  headers: redactResponseHeaders(response.headers, redaction.secrets),
331
- bodyText: resolveRedactedResponseBody(response.bodyText, redaction.connection.token, redaction.secrets, response.bodyTruncated === true),
394
+ bodyText: redactExecutedBody({ response, redaction }, optional),
332
395
  ...(authDiagnostic ? { authDiagnostic } : {}),
333
396
  };
334
397
  }
398
+ /** Keep decoded-string redaction in the credential owner, before any caller's projection. */
399
+ function redactExecutedBody({ response, redaction }, options = {}) {
400
+ if (options.responseFormat === "json") {
401
+ if (response.bodyTruncated || response.bodyBytesTruncated)
402
+ throw new CredentialedRequestValidationError({ message: "JSON response must be complete" });
403
+ try {
404
+ return redactJsonResponseBody({ bodyText: response.bodyText, token: redaction.connection.token, secrets: redaction.secrets });
405
+ }
406
+ catch {
407
+ throw new CredentialedRequestValidationError({ message: "JSON response must be valid" });
408
+ }
409
+ }
410
+ return resolveRedactedResponseBody(response.bodyText, redaction.connection.token, redaction.secrets, response.bodyTruncated === true);
411
+ }
335
412
  //# sourceMappingURL=credentialed-request.js.map
@@ -2,4 +2,14 @@ export declare function redactResponseHeaders(headers: Readonly<Record<string, s
2
2
  export declare function redactSecretSubstrings(text: string, secrets: readonly string[]): string;
3
3
  export declare function redactTruncatedTail(body: string, secrets: readonly string[]): string;
4
4
  export declare function resolveRedactedResponseBody(bodyText: string, token: string, secrets: readonly string[], bodyTruncated: boolean): string;
5
+ /** Opt-in JSON release boundary: decode escaped strings before using the same credential-secret
6
+ * owner. Scrubbing only serialized bytes misses a provider echo such as `\u0073ecret-token`.
7
+ * Callers must reject truncated responses first. Malformed JSON or secrets in keys/numbers throw;
8
+ * short tokens withhold the whole body under the existing rule. The reviver visits decoded keys
9
+ * and values at every depth. @complexity O(n * s), bounded body and secrets. */
10
+ export declare function redactJsonResponseBody({ bodyText, token, secrets }: {
11
+ bodyText: string;
12
+ token: string;
13
+ secrets: readonly string[];
14
+ }, _options?: Record<string, never>): string;
5
15
  //# sourceMappingURL=response-redaction.d.ts.map
@@ -59,4 +59,24 @@ export function resolveRedactedResponseBody(bodyText, token, secrets, bodyTrunca
59
59
  const redacted = redactSecretSubstrings(bodyText, secrets);
60
60
  return bodyTruncated ? redactTruncatedTail(redacted, secrets) : redacted;
61
61
  }
62
+ /** Opt-in JSON release boundary: decode escaped strings before using the same credential-secret
63
+ * owner. Scrubbing only serialized bytes misses a provider echo such as `\u0073ecret-token`.
64
+ * Callers must reject truncated responses first. Malformed JSON or secrets in keys/numbers throw;
65
+ * short tokens withhold the whole body under the existing rule. The reviver visits decoded keys
66
+ * and values at every depth. @complexity O(n * s), bounded body and secrets. */
67
+ export function redactJsonResponseBody({ bodyText, token, secrets }, _options = {}) {
68
+ if (token.length < MIN_SAFE_BODY_REDACTION_TOKEN_LENGTH)
69
+ return BODY_WITHHELD_SHORT_TOKEN_MARKER;
70
+ const decoded = JSON.parse(bodyText, (key, value) => {
71
+ // Refuse rather than rename fields or change numeric types in the provider's data.
72
+ if (secrets.some(secret => secret !== "" && key.includes(secret)))
73
+ throw new TypeError("JSON response key contains a credential");
74
+ if (typeof value === "number" && secrets.some(secret => secret !== "" && String(value).includes(secret)))
75
+ throw new TypeError("JSON response number contains a credential");
76
+ if (typeof value === "string")
77
+ return redactSecretSubstrings(value, secrets);
78
+ return value;
79
+ });
80
+ return JSON.stringify(decoded);
81
+ }
62
82
  //# sourceMappingURL=response-redaction.js.map
@@ -0,0 +1,17 @@
1
+ import type { SavedRequestDefinition } from "./types.js";
2
+ import { compileInputSchema } from "./schema.js";
3
+ /** Validate persisted configuration at save AND invocation time. Unsupported keys refuse rather
4
+ * than becoming a more general HTTP/template tool. Returns a detached snapshot or a safe refusal.
5
+ * @complexity O(n) over a definition bounded to 16 KiB; no I/O. */
6
+ export declare function parseSavedRequestDefinition({ value }: {
7
+ value: unknown;
8
+ }, _options?: Record<string, never>): SavedRequestDefinition;
9
+ /** Internal execution preparation: retain the validator built while checking the detached schema.
10
+ * @complexity O(n) over the same 16 KiB definition bound; no I/O. */
11
+ export declare function prepareSavedRequestDefinition({ value }: {
12
+ value: unknown;
13
+ }, _options?: Record<string, never>): {
14
+ definition: SavedRequestDefinition;
15
+ validator: ReturnType<typeof compileInputSchema>;
16
+ };
17
+ //# sourceMappingURL=definition.d.ts.map
@@ -0,0 +1,84 @@
1
+ import { compileInputSchema } from "./schema.js";
2
+ import { closed, dataKey, fieldPath, httpsUrl, integer, name, record, requireCondition, snapshot } from "./validation.js";
3
+ /** Validate persisted configuration at save AND invocation time. Unsupported keys refuse rather
4
+ * than becoming a more general HTTP/template tool. Returns a detached snapshot or a safe refusal.
5
+ * @complexity O(n) over a definition bounded to 16 KiB; no I/O. */
6
+ export function parseSavedRequestDefinition({ value }, _options = {}) {
7
+ return prepareSavedRequestDefinition({ value }).definition;
8
+ }
9
+ /** Internal execution preparation: retain the validator built while checking the detached schema.
10
+ * @complexity O(n) over the same 16 KiB definition bound; no I/O. */
11
+ export function prepareSavedRequestDefinition({ value }, _options = {}) {
12
+ const definition = record({ value: snapshot({ value, maxBytes: 16_384, code: "invalid_definition" }) });
13
+ closed({ value: definition, keys: ["version", "method", "url", "credential", "inputSchema", "queryBindings", "bodyBindings", "staticBody", "output"] });
14
+ requireCondition({ valid: definition.version === 1 });
15
+ requireCondition({ valid: ["GET", "POST", "PUT", "PATCH", "DELETE"].includes(String(definition.method)) });
16
+ const url = httpsUrl({ value: definition.url });
17
+ checkCredential({ value: definition.credential, url });
18
+ for (const key of url.searchParams.keys())
19
+ dataKey({ value: key });
20
+ const schema = record({ value: definition.inputSchema });
21
+ const validator = compileInputSchema({ schema });
22
+ checkBindings({ definition, schema, url });
23
+ checkProjection({ value: definition.output });
24
+ return { definition: definition, validator };
25
+ }
26
+ function checkCredential({ value, url }, _options = {}) {
27
+ const credential = record({ value });
28
+ closed({ value: credential, keys: ["id", "revision", "origin"] });
29
+ for (const key of ["id", "revision"]) {
30
+ const text = credential[key];
31
+ requireCondition({ valid: typeof text === "string" && /^[\w:-]{1,128}$/.test(text) });
32
+ }
33
+ requireCondition({ valid: httpsUrl({ value: credential.origin }).origin === credential.origin });
34
+ requireCondition({ valid: url.origin === credential.origin });
35
+ }
36
+ function checkBindings({ definition, schema, url }, _options = {}) {
37
+ const properties = record({ value: schema.properties });
38
+ checkBindingMap({ value: definition.queryBindings, properties, occupied: [...url.searchParams.keys()], query: true });
39
+ const body = definition.staticBody === undefined ? {} : record({ value: definition.staticBody });
40
+ for (const key of Object.keys(body))
41
+ dataKey({ value: key });
42
+ checkBindingMap({ value: definition.bodyBindings, properties, occupied: Object.keys(body), query: false });
43
+ if (definition.method === "GET") {
44
+ requireCondition({ valid: Object.keys(record({ value: definition.bodyBindings })).length === 0 && Object.keys(body).length === 0 });
45
+ }
46
+ }
47
+ function checkBindingMap({ value, properties, occupied, query }, _options = {}) {
48
+ const bindings = record({ value });
49
+ integer({ value: Object.keys(bindings).length, max: 32 });
50
+ for (const [destination, source] of Object.entries(bindings)) {
51
+ dataKey({ value: destination });
52
+ const sourceKey = name({ value: source });
53
+ requireCondition({ valid: !occupied.includes(destination) && Object.hasOwn(properties, sourceKey) });
54
+ if (query)
55
+ requireCondition({ valid: !["object", "array"].includes(String(record({ value: properties[sourceKey] }).type)) });
56
+ }
57
+ }
58
+ function checkProjection({ value }, _options = {}) {
59
+ const projection = record({ value });
60
+ closed({ value: projection, keys: ["path", "maxItems", "fields"] });
61
+ fieldPath({ value: projection.path });
62
+ integer({ value: projection.maxItems, min: 1, max: 50 });
63
+ const fields = record({ value: projection.fields });
64
+ integer({ value: Object.keys(fields).length, min: 1, max: 32 });
65
+ for (const [key, field] of Object.entries(fields)) {
66
+ name({ value: key });
67
+ checkOutputField({ value: field });
68
+ }
69
+ }
70
+ function checkOutputField({ value }, _options = {}) {
71
+ const field = record({ value });
72
+ closed({ value: field, keys: ["path", "type", "maxLength", "allowedOrigin"] });
73
+ fieldPath({ value: field.path });
74
+ requireCondition({ valid: ["string", "number", "boolean", "url"].includes(String(field.type)) });
75
+ if (field.type === "string" || field.type === "url")
76
+ integer({ value: field.maxLength, min: 1, max: 4096 });
77
+ else
78
+ requireCondition({ valid: field.maxLength === undefined });
79
+ if (field.type === "url")
80
+ requireCondition({ valid: httpsUrl({ value: field.allowedOrigin }).origin === field.allowedOrigin });
81
+ else
82
+ requireCondition({ valid: field.allowedOrigin === undefined });
83
+ }
84
+ //# sourceMappingURL=definition.js.map
@@ -0,0 +1,17 @@
1
+ import type { SavedRequestDeps, SavedRequestResult } from "./types.js";
2
+ /** Execute an already-authorized host definition with visitor data. The model supplies only input;
3
+ * callers must recheck live policy/consent/quotas before calling. No retries of ambiguous effects.
4
+ * @param required Host ports, mounted workspace, saved definition and untrusted input.
5
+ * @param options Optional cancellation; the guard also imposes a whole-request 10s deadline.
6
+ * @returns Positively projected data explicitly marked untrusted.
7
+ * @throws SavedRequestError with value-free public refusal codes.
8
+ * @complexity O(n) bounded validation plus one credential resolution and one guarded HTTP send. */
9
+ export declare function executeSavedRequest({ deps, workspaceId, definition: raw, input: rawInput }: {
10
+ deps: SavedRequestDeps;
11
+ workspaceId: string;
12
+ definition: unknown;
13
+ input: unknown;
14
+ }, options?: {
15
+ signal?: AbortSignal;
16
+ }): Promise<SavedRequestResult>;
17
+ //# sourceMappingURL=execute.d.ts.map
@@ -0,0 +1,95 @@
1
+ import { createHttpClient } from "@jini-ai/platform/http/guarded";
2
+ import { CredentialedRequestValidationError, makeCredentialedRequest } from "../credentialed-http/credentialed-request.js";
3
+ import { prepareSavedRequestDefinition } from "./definition.js";
4
+ import { projectSavedRequestResponse } from "./projection.js";
5
+ import { requireCondition, SavedRequestError, snapshot } from "./validation.js";
6
+ /** Execute an already-authorized host definition with visitor data. The model supplies only input;
7
+ * callers must recheck live policy/consent/quotas before calling. No retries of ambiguous effects.
8
+ * @param required Host ports, mounted workspace, saved definition and untrusted input.
9
+ * @param options Optional cancellation; the guard also imposes a whole-request 10s deadline.
10
+ * @returns Positively projected data explicitly marked untrusted.
11
+ * @throws SavedRequestError with value-free public refusal codes.
12
+ * @complexity O(n) bounded validation plus one credential resolution and one guarded HTTP send. */
13
+ export async function executeSavedRequest({ deps, workspaceId, definition: raw, input: rawInput }, options = {}) {
14
+ const { definition, validator } = prepareSavedRequestDefinition({ value: raw });
15
+ const input = validatedInput({ validator, value: rawInput });
16
+ const bound = bindRequest({ definition, input });
17
+ let responseReceived = false;
18
+ try {
19
+ requireCondition({ valid: !deps.forbiddenOrigins.some(origin => new URL(origin).hostname === new URL(definition.url).hostname) });
20
+ options.signal?.throwIfAborted();
21
+ const credential = await resolveCredential({ deps, workspaceId, definition });
22
+ options.signal?.throwIfAborted();
23
+ const response = await makeCredentialedRequest({
24
+ deps: {
25
+ resolver: { describe: async () => credential, resolve: async () => credential },
26
+ schemeRegistry: deps.schemeRegistry, audit: deps.audit, clock: deps.clock,
27
+ httpClient: boundedHttpClient({ deps, signal: options.signal, onResponse: () => { responseReceived = true; } }),
28
+ },
29
+ input: { workspaceId, label: definition.credential.id, method: definition.method, url: bound.url },
30
+ }, { body: bound.body, headers: { Accept: "application/json", ...(bound.body === undefined ? {} : { "Content-Type": "application/json" }) }, responseFormat: "json" });
31
+ checkResponse({ response });
32
+ return projectSavedRequestResponse({ bodyText: response.bodyText, output: definition.output });
33
+ }
34
+ catch (error) {
35
+ if (error instanceof SavedRequestError)
36
+ throw error;
37
+ // The credential owner audits answered requests before JSON completeness/redaction checks.
38
+ // Preserve those refusals without misclassifying pre-send credential validation failures.
39
+ if (responseReceived && error instanceof CredentialedRequestValidationError)
40
+ throw new SavedRequestError({ code: "invalid_response" });
41
+ throw new SavedRequestError({ code: "execution_failed" });
42
+ }
43
+ }
44
+ function validatedInput({ validator, value }, _options = {}) {
45
+ const input = snapshot({ value, maxBytes: 16_384, code: "invalid_input" });
46
+ requireCondition({ valid: validator.validate(input).valid, code: "invalid_input" });
47
+ return input;
48
+ }
49
+ function bindRequest({ definition, input }, _options = {}) {
50
+ const url = new URL(definition.url);
51
+ for (const [key, source] of Object.entries(definition.queryBindings)) {
52
+ if (Object.hasOwn(input, source))
53
+ url.searchParams.set(key, String(input[source]));
54
+ }
55
+ const body = { ...definition.staticBody };
56
+ for (const [key, source] of Object.entries(definition.bodyBindings)) {
57
+ if (Object.hasOwn(input, source))
58
+ body[key] = input[source];
59
+ }
60
+ snapshot({ value: { url: url.href, body }, maxBytes: 16_384, code: "invalid_input" });
61
+ return { url: url.href, body: Object.keys(body).length === 0 ? undefined : JSON.stringify(body) };
62
+ }
63
+ async function resolveCredential({ deps, workspaceId, definition }, _options = {}) {
64
+ const credential = await deps.credentials.resolve({ workspaceId, credentialId: definition.credential.id });
65
+ if (!credential)
66
+ throw new SavedRequestError({ code: "credential_changed" });
67
+ requireCondition({ valid: credential.revision === definition.credential.revision, code: "credential_changed" });
68
+ requireCondition({ valid: new URL(credential.baseUrl).origin === definition.credential.origin, code: "credential_changed" });
69
+ // Legacy credentials allow additional hosts; visitor release approval covers only the base origin.
70
+ requireCondition({ valid: !/[\r\n\u0000]/u.test(credential.connection.token), code: "credential_changed" });
71
+ return { ...credential, additionalHosts: [] };
72
+ }
73
+ function boundedHttpClient({ deps, signal, onResponse }, _options = {}) {
74
+ // Equivalent to SINGLE_HOP_HTTPS_EGRESS_POLICY: the product policy stays in host composition.
75
+ // Construct the existing guard here so redirects/dev overrides cannot silently widen this grant.
76
+ const client = createHttpClient({ dns: deps.dns, transport: deps.transport, clock: deps.clock, userAgent: deps.userAgent, policy: {
77
+ allowedSchemes: ["https"], denyPrivateAddresses: true, devHostAllowlist: [], maxRedirects: 0,
78
+ connectTimeoutMs: 10_000, maxResponseBytes: 65_536, maxDecompressedBytes: 65_536,
79
+ } });
80
+ return { async send({ request }) {
81
+ const bounded = { ...request, totalDeadlineMs: 10_000, maxResponseBytes: 65_536, ...(signal === undefined ? {} : { signal }) };
82
+ const response = await client.send({ request: bounded }, { redirect: "error" });
83
+ onResponse();
84
+ return response;
85
+ } };
86
+ }
87
+ function checkResponse({ response }, _options = {}) {
88
+ requireCondition({ valid: response.status >= 200 && response.status < 300, code: "invalid_response" });
89
+ const headers = Object.fromEntries(Object.entries(response.headers).map(([key, value]) => [key.toLowerCase(), value]));
90
+ const contentType = headers["content-type"]?.split(";")[0]?.trim() ?? "";
91
+ requireCondition({ valid: /^application\/(?:[a-z0-9.-]+\+)?json$/i.test(contentType), code: "invalid_response" });
92
+ // The platform guard caps bytes and the credential owner's JSON mode refuses truncation.
93
+ // Check status/media type after that owner records the real status, before field projection.
94
+ }
95
+ //# sourceMappingURL=execute.js.map
@@ -0,0 +1,6 @@
1
+ export { parseSavedRequestDefinition } from "./definition.js";
2
+ export { executeSavedRequest } from "./execute.js";
3
+ export { SavedRequestError } from "./validation.js";
4
+ export type { SavedRequestErrorCode } from "./validation.js";
5
+ export type * from "./types.js";
6
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1,4 @@
1
+ export { parseSavedRequestDefinition } from "./definition.js";
2
+ export { executeSavedRequest } from "./execute.js";
3
+ export { SavedRequestError } from "./validation.js";
4
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,9 @@
1
+ import type { SavedRequestDefinition, SavedRequestResult } from "./types.js";
2
+ /** Project only declared, typed fields after credentialed-request redaction. No provider text
3
+ * becomes an instruction or browser directive. Bad types/URLs refuse; selected arrays are bounded.
4
+ * @complexity O(rows * fields * path depth), bounded by 50 * 32 * 8 and 16 KiB output. */
5
+ export declare function projectSavedRequestResponse({ bodyText, output }: {
6
+ bodyText: string;
7
+ output: SavedRequestDefinition["output"];
8
+ }, _options?: Record<string, never>): SavedRequestResult;
9
+ //# sourceMappingURL=projection.d.ts.map
@@ -0,0 +1,48 @@
1
+ import { requireCondition, SavedRequestError, snapshot } from "./validation.js";
2
+ /** Project only declared, typed fields after credentialed-request redaction. No provider text
3
+ * becomes an instruction or browser directive. Bad types/URLs refuse; selected arrays are bounded.
4
+ * @complexity O(rows * fields * path depth), bounded by 50 * 32 * 8 and 16 KiB output. */
5
+ export function projectSavedRequestResponse({ bodyText, output }, _options = {}) {
6
+ try {
7
+ const selected = readPath({ value: JSON.parse(bodyText), path: output.path });
8
+ const rows = Array.isArray(selected) ? selected.slice(0, output.maxItems) : [selected];
9
+ const items = rows.map(row => projectRow({ row, fields: output.fields }));
10
+ const result = { trust: "untrusted", items };
11
+ snapshot({ value: result, maxBytes: 16_384, code: "invalid_response" });
12
+ return result;
13
+ }
14
+ catch {
15
+ throw new SavedRequestError({ code: "invalid_response" });
16
+ }
17
+ }
18
+ function readPath({ value, path }, _options = {}) {
19
+ for (const key of path) {
20
+ requireCondition({ valid: typeof value === "object" && value !== null && !Array.isArray(value), code: "invalid_response" });
21
+ requireCondition({ valid: Object.hasOwn(value, key), code: "invalid_response" });
22
+ value = value[key];
23
+ }
24
+ return value;
25
+ }
26
+ function projectRow({ row, fields }, _options = {}) {
27
+ return Object.fromEntries(Object.entries(fields).map(([key, field]) => {
28
+ const value = readPath({ value: row, path: field.path });
29
+ checkValue({ value, field });
30
+ return [key, value];
31
+ }));
32
+ }
33
+ function checkValue({ value, field }, _options = {}) {
34
+ const type = field.type === "url" ? "string" : field.type;
35
+ requireCondition({ valid: typeof value === type, code: "invalid_response" });
36
+ if (typeof value === "number")
37
+ requireCondition({ valid: Number.isFinite(value), code: "invalid_response" });
38
+ if (typeof value === "string")
39
+ requireCondition({ valid: [...value].length <= field.maxLength, code: "invalid_response" });
40
+ if (field.type === "url")
41
+ checkPublicUrl({ value: value, origin: field.allowedOrigin });
42
+ }
43
+ function checkPublicUrl({ value, origin }, _options = {}) {
44
+ const url = new URL(value);
45
+ requireCondition({ valid: url.protocol === "https:" && url.origin === origin && !url.username && !url.password, code: "invalid_response" });
46
+ requireCondition({ valid: !/[\s\u0000-\u001f\u007f]/u.test(value), code: "invalid_response" });
47
+ }
48
+ //# sourceMappingURL=projection.js.map
@@ -0,0 +1,7 @@
1
+ import { Validator } from "@cfworker/json-schema";
2
+ /** Closed, bounded schemas only; no refs, combinators, formats, regex or executable expressions.
3
+ * @complexity O(s), with depth <= 4 and <= 32 properties per object; serialized schema is capped. */
4
+ export declare function compileInputSchema({ schema }: {
5
+ schema: Record<string, unknown>;
6
+ }, _options?: Record<string, never>): Validator;
7
+ //# sourceMappingURL=schema.d.ts.map
@@ -0,0 +1,73 @@
1
+ import { Validator } from "@cfworker/json-schema";
2
+ import { closed, integer, name, record, requireCondition } from "./validation.js";
3
+ const KEYS = {
4
+ object: ["type", "properties", "required", "additionalProperties"],
5
+ array: ["type", "items", "minItems", "maxItems"],
6
+ string: ["type", "minLength", "maxLength", "enum"],
7
+ number: ["type", "minimum", "maximum", "enum"],
8
+ integer: ["type", "minimum", "maximum", "enum"],
9
+ boolean: ["type", "enum"],
10
+ };
11
+ /** Closed, bounded schemas only; no refs, combinators, formats, regex or executable expressions.
12
+ * @complexity O(s), with depth <= 4 and <= 32 properties per object; serialized schema is capped. */
13
+ export function compileInputSchema({ schema }, _options = {}) {
14
+ requireCondition({ valid: schema.type === "object" });
15
+ checkNode({ schema, depth: 0 });
16
+ return new Validator(schema, "2020-12", true);
17
+ }
18
+ function checkNode({ schema, depth }, _options = {}) {
19
+ requireCondition({ valid: depth <= 4 });
20
+ requireCondition({ valid: typeof schema.type === "string" && Object.hasOwn(KEYS, schema.type) });
21
+ const keys = KEYS[schema.type];
22
+ closed({ value: schema, keys });
23
+ if (schema.type === "object")
24
+ return checkObject({ schema, depth });
25
+ if (schema.type === "array")
26
+ return checkArray({ schema, depth });
27
+ checkPrimitive({ schema });
28
+ }
29
+ function checkObject({ schema, depth }, _options = {}) {
30
+ requireCondition({ valid: schema.additionalProperties === false });
31
+ const properties = record({ value: schema.properties });
32
+ integer({ value: Object.keys(properties).length, max: 32 });
33
+ for (const [key, child] of Object.entries(properties)) {
34
+ name({ value: key });
35
+ checkNode({ schema: record({ value: child }), depth: depth + 1 });
36
+ }
37
+ if (schema.required === undefined)
38
+ return;
39
+ requireCondition({ valid: Array.isArray(schema.required) });
40
+ const required = schema.required;
41
+ requireCondition({ valid: required.every(key => typeof key === "string" && Object.hasOwn(properties, key)) });
42
+ requireCondition({ valid: new Set(required).size === required.length });
43
+ }
44
+ function checkArray({ schema, depth }, _options = {}) {
45
+ integer({ value: schema.maxItems, max: 50 });
46
+ if (schema.minItems !== undefined)
47
+ integer({ value: schema.minItems, max: Number(schema.maxItems) });
48
+ checkNode({ schema: record({ value: schema.items }), depth: depth + 1 });
49
+ }
50
+ function checkPrimitive({ schema }, _options = {}) {
51
+ if (schema.type === "string") {
52
+ integer({ value: schema.maxLength, max: 4096 });
53
+ if (schema.minLength !== undefined)
54
+ integer({ value: schema.minLength, max: Number(schema.maxLength) });
55
+ }
56
+ if (schema.type === "number" || schema.type === "integer")
57
+ checkRange({ schema });
58
+ if (schema.enum !== undefined)
59
+ checkEnum({ schema });
60
+ }
61
+ function checkRange({ schema }, _options = {}) {
62
+ requireCondition({ valid: typeof schema.minimum === "number" && Number.isFinite(schema.minimum) });
63
+ requireCondition({ valid: typeof schema.maximum === "number" && Number.isFinite(schema.maximum) });
64
+ requireCondition({ valid: Number(schema.minimum) <= Number(schema.maximum) });
65
+ }
66
+ function checkEnum({ schema }, _options = {}) {
67
+ requireCondition({ valid: Array.isArray(schema.enum) });
68
+ const values = schema.enum;
69
+ integer({ value: values.length, min: 1, max: 32 });
70
+ const type = schema.type === "integer" ? "number" : schema.type;
71
+ requireCondition({ valid: values.every(value => typeof value === type) });
72
+ }
73
+ //# sourceMappingURL=schema.js.map
@@ -0,0 +1,58 @@
1
+ import type { CredentialedRequestAuditPort } from "../credentialed-http/credentialed-request.js";
2
+ import type { CredentialSchemeRegistryPort, ResolvedCredential } from "../credentialed-http/ports.js";
3
+ import type { DnsResolver, GuardedClock, PinnedHttpTransport } from "@jini-ai/platform/http/guarded";
4
+ /** Persisted data only. Identity, policy, consent and quotas belong to the calling host. */
5
+ export interface SavedRequestDefinition {
6
+ readonly version: 1;
7
+ readonly method: "GET" | "POST" | "PUT" | "PATCH" | "DELETE";
8
+ readonly url: string;
9
+ readonly credential: {
10
+ readonly id: string;
11
+ readonly revision: string;
12
+ readonly origin: string;
13
+ };
14
+ readonly inputSchema: Readonly<Record<string, unknown>>;
15
+ readonly queryBindings: Readonly<Record<string, string>>;
16
+ readonly bodyBindings: Readonly<Record<string, string>>;
17
+ readonly staticBody?: Readonly<Record<string, unknown>>;
18
+ readonly output: {
19
+ readonly path: readonly string[];
20
+ readonly maxItems: number;
21
+ readonly fields: Readonly<Record<string, SavedRequestOutputField>>;
22
+ };
23
+ }
24
+ export interface SavedRequestOutputField {
25
+ readonly path: readonly string[];
26
+ readonly type: "string" | "number" | "boolean" | "url";
27
+ readonly maxLength?: number;
28
+ readonly allowedOrigin?: string;
29
+ }
30
+ /** Resolve opaque IDs within the mounted workspace, never editable display labels. A revision
31
+ * must change whenever account, token, origin or visitor-use authorization changes. */
32
+ export interface SavedRequestCredentialResolverPort {
33
+ resolve(required: {
34
+ workspaceId: string;
35
+ credentialId: string;
36
+ }): Promise<(ResolvedCredential & {
37
+ readonly revision: string;
38
+ }) | null>;
39
+ }
40
+ /** All effects are injected. The interpreter constructs the existing guard, so callers cannot
41
+ * accidentally supply an HTTP client with redirects or development bypasses enabled. */
42
+ export interface SavedRequestDeps {
43
+ readonly credentials: SavedRequestCredentialResolverPort;
44
+ readonly schemeRegistry: CredentialSchemeRegistryPort;
45
+ readonly audit: CredentialedRequestAuditPort;
46
+ readonly clock: GuardedClock;
47
+ readonly dns: DnsResolver;
48
+ readonly transport: PinnedHttpTransport;
49
+ readonly userAgent: string;
50
+ /** Trusted composition supplies the site's public, admin, API and control origins. */
51
+ readonly forbiddenOrigins: readonly string[];
52
+ }
53
+ /** Only positively selected values; no provider headers, diagnostics or credential metadata. */
54
+ export interface SavedRequestResult {
55
+ readonly trust: "untrusted";
56
+ readonly items: readonly Readonly<Record<string, string | number | boolean>>[];
57
+ }
58
+ //# sourceMappingURL=types.d.ts.map
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=types.js.map
@@ -0,0 +1,46 @@
1
+ import { IntegrationError } from "../argument-error.js";
2
+ export type SavedRequestErrorCode = "invalid_definition" | "invalid_input" | "credential_changed" | "execution_failed" | "invalid_response";
3
+ /** Safe public refusal. Raw URLs, provider bodies, secrets and underlying errors never escape. */
4
+ export declare class SavedRequestError extends IntegrationError {
5
+ readonly code: SavedRequestErrorCode;
6
+ constructor(required: {
7
+ code: SavedRequestErrorCode;
8
+ }, _options?: Record<string, never>);
9
+ }
10
+ export declare function requireCondition({ valid, code }: {
11
+ valid: boolean;
12
+ code?: SavedRequestErrorCode;
13
+ }, _options?: Record<string, never>): void;
14
+ export declare function record({ value }: {
15
+ value: unknown;
16
+ }, _options?: Record<string, never>): Record<string, unknown>;
17
+ export declare function closed({ value, keys }: {
18
+ value: Record<string, unknown>;
19
+ keys: readonly string[];
20
+ }, _options?: Record<string, never>): void;
21
+ export declare function name({ value }: {
22
+ value: unknown;
23
+ }, _options?: Record<string, never>): string;
24
+ export declare function integer({ value, min, max }: {
25
+ value: unknown;
26
+ min?: number;
27
+ max: number;
28
+ }, _options?: Record<string, never>): void;
29
+ /** Bound serialized bytes before parsing/compiling. Snapshotting also prevents edits while awaiting
30
+ * credentials or DNS from changing the reviewed definition/input. @complexity O(n) bounded bytes. */
31
+ export declare function snapshot({ value, maxBytes, code }: {
32
+ value: unknown;
33
+ maxBytes: number;
34
+ code: SavedRequestErrorCode;
35
+ }, _options?: Record<string, never>): unknown;
36
+ export declare function httpsUrl({ value }: {
37
+ value: unknown;
38
+ }, _options?: Record<string, never>): URL;
39
+ export declare function fieldPath({ value }: {
40
+ value: unknown;
41
+ }, _options?: Record<string, never>): void;
42
+ /** Authentication is injected solely by the credential owner, never by bindings or static data. */
43
+ export declare function dataKey({ value }: {
44
+ value: unknown;
45
+ }, _options?: Record<string, never>): string;
46
+ //# sourceMappingURL=validation.d.ts.map
@@ -0,0 +1,66 @@
1
+ import { IntegrationError } from "../argument-error.js";
2
+ /** Safe public refusal. Raw URLs, provider bodies, secrets and underlying errors never escape. */
3
+ export class SavedRequestError extends IntegrationError {
4
+ code;
5
+ constructor(required, _options = {}) {
6
+ super({ message: `Saved request refused: ${required.code}` });
7
+ this.code = required.code;
8
+ }
9
+ }
10
+ export function requireCondition({ valid, code = "invalid_definition" }, _options = {}) {
11
+ if (!valid)
12
+ throw new SavedRequestError({ code });
13
+ }
14
+ export function record({ value }, _options = {}) {
15
+ requireCondition({ valid: typeof value === "object" && value !== null && !Array.isArray(value) });
16
+ return value;
17
+ }
18
+ export function closed({ value, keys }, _options = {}) {
19
+ requireCondition({ valid: Object.keys(value).every(key => keys.includes(key)) });
20
+ }
21
+ export function name({ value }, _options = {}) {
22
+ requireCondition({ valid: typeof value === "string" && /^[A-Za-z][A-Za-z0-9_.-]{0,63}$/.test(value) });
23
+ requireCondition({ valid: !["__proto__", "prototype", "constructor"].includes(value) });
24
+ return value;
25
+ }
26
+ export function integer({ value, min = 0, max }, _options = {}) {
27
+ requireCondition({ valid: Number.isSafeInteger(value) && Number(value) >= min && Number(value) <= max });
28
+ }
29
+ /** Bound serialized bytes before parsing/compiling. Snapshotting also prevents edits while awaiting
30
+ * credentials or DNS from changing the reviewed definition/input. @complexity O(n) bounded bytes. */
31
+ export function snapshot({ value, maxBytes, code }, _options = {}) {
32
+ try {
33
+ const json = JSON.stringify(value);
34
+ requireCondition({ valid: typeof json === "string" && Buffer.byteLength(json, "utf8") <= maxBytes, code });
35
+ return JSON.parse(json);
36
+ }
37
+ catch {
38
+ throw new SavedRequestError({ code });
39
+ }
40
+ }
41
+ export function httpsUrl({ value }, _options = {}) {
42
+ try {
43
+ requireCondition({ valid: typeof value === "string" });
44
+ // No template syntax or parser normalization of control characters in persisted targets.
45
+ requireCondition({ valid: !/[\s{}<>`\\]/u.test(decodeURIComponent(value)) });
46
+ const url = new URL(value);
47
+ requireCondition({ valid: url.protocol === "https:" && url.port === "" && !url.username && !url.password && !url.hash });
48
+ return url;
49
+ }
50
+ catch {
51
+ throw new SavedRequestError({ code: "invalid_definition" });
52
+ }
53
+ }
54
+ export function fieldPath({ value }, _options = {}) {
55
+ requireCondition({ valid: Array.isArray(value) && value.length <= 8 });
56
+ for (const part of value)
57
+ name({ value: part });
58
+ }
59
+ /** Authentication is injected solely by the credential owner, never by bindings or static data. */
60
+ export function dataKey({ value }, _options = {}) {
61
+ const key = name({ value });
62
+ const normalized = key.toLowerCase().replace(/[_.-]/g, "");
63
+ requireCondition({ valid: !["authorization", "proxyauthorization", "cookie", "host", "token", "accesstoken", "apikey", "password", "secret", "credential", "credentialid", "username"].includes(normalized) });
64
+ return key;
65
+ }
66
+ //# sourceMappingURL=validation.js.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jini-ai/integrations",
3
- "version": "0.4.3",
3
+ "version": "0.6.11",
4
4
  "description": "Third-party vendor integrations and outbound services, each independently importable: media generation, credentialed HTTP and webhooks.",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {
@@ -18,7 +18,8 @@
18
18
  "./credentialed-http": "node",
19
19
  "./webhooks": "node",
20
20
  "./api-connections": "node",
21
- "./media-providers/node": "node"
21
+ "./media-providers/node": "node",
22
+ "./saved-requests": "node"
22
23
  }
23
24
  },
24
25
  "type": "module",
@@ -53,6 +54,11 @@
53
54
  "types": "./dist/media-providers/dispatch/node.d.ts",
54
55
  "import": "./dist/media-providers/dispatch/node.js",
55
56
  "default": "./dist/media-providers/dispatch/node.js"
57
+ },
58
+ "./saved-requests": {
59
+ "types": "./dist/saved-requests/index.d.ts",
60
+ "import": "./dist/saved-requests/index.js",
61
+ "default": "./dist/saved-requests/index.js"
56
62
  }
57
63
  },
58
64
  "typesVersions": {
@@ -74,6 +80,9 @@
74
80
  ],
75
81
  "media-providers/node": [
76
82
  "./dist/media-providers/dispatch/node.d.ts"
83
+ ],
84
+ "saved-requests": [
85
+ "./dist/saved-requests/index.d.ts"
77
86
  ]
78
87
  }
79
88
  },
@@ -94,13 +103,14 @@
94
103
  "registry": "https://registry.npmjs.org"
95
104
  },
96
105
  "dependencies": {
97
- "@jini-ai/core": "^0.4.9"
106
+ "@jini-ai/core": "^0.6.11"
98
107
  },
99
108
  "peerDependencies": {
100
- "@jini-ai/db": "^0.3.0",
109
+ "@jini-ai/db": "^0.6.10",
101
110
  "better-sqlite3": "^13.0.0",
102
- "@jini-ai/platform": "^0.5.1",
103
- "@jini-ai/oauth": "^0.2.2"
111
+ "@jini-ai/platform": "^0.6.10",
112
+ "@jini-ai/oauth": "^0.6.10",
113
+ "@cfworker/json-schema": "^4.1.1"
104
114
  },
105
115
  "peerDependenciesMeta": {
106
116
  "@jini-ai/db": {
@@ -114,17 +124,21 @@
114
124
  },
115
125
  "@jini-ai/oauth": {
116
126
  "optional": true
127
+ },
128
+ "@cfworker/json-schema": {
129
+ "optional": true
117
130
  }
118
131
  },
119
132
  "devDependencies": {
120
133
  "@types/better-sqlite3": "^7.6.11",
121
134
  "better-sqlite3": "^13.0.0",
122
135
  "@vitest/coverage-v8": "^2.1.9",
123
- "@jini-ai/oauth": "0.2.3",
124
- "@jini-ai/core": "0.4.9",
125
- "@jini-ai/agent-plugins": "0.4.8",
126
- "@jini-ai/db": "^0.3.6",
127
- "@jini-ai/platform": "0.5.10"
136
+ "@cfworker/json-schema": "^4.1.1",
137
+ "@jini-ai/oauth": "0.6.11",
138
+ "@jini-ai/db": "^0.6.11",
139
+ "@jini-ai/agent-plugins": "0.6.11",
140
+ "@jini-ai/core": "0.6.11",
141
+ "@jini-ai/platform": "0.6.11"
128
142
  },
129
143
  "scripts": {
130
144
  "build": "tsc -p tsconfig.json",