@k9o/extension-runtime 1.5.0 → 1.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -147,7 +147,7 @@ Output: K9O_ACCESS_DENIED
147
147
 
148
148
  #### 7.2 Namespaces
149
149
 
150
- The client exposes these on the object `createExtensionClient()` returns: `documents`, `collections`, `attributes`, `identity`, `policy`, `kibo`, `audit`, `ai`, `workflow`, `fetch`, `credentials`, `bff`, `tables`, `streaming`, `vectors`, `functions`, `hooks`, `webhookIngress`, `compliance` and `analytics`. Each call is allowed only if the manifest holds the matching grant.
150
+ The client exposes these on the object `createExtensionClient()` returns: `documents`, `collections`, `attributes`, `identity`, `policy`, `kibo`, `audit`, `ai`, `workflow`, `fetch`, `credentials`, `bff`, `tables`, `streaming`, `vectors`, `functions`, `hooks`, `webhookIngress`, `compliance`, `analytics`, `files` and `authMigrations`. Each call is allowed only if the manifest holds the matching grant.
151
151
 
152
152
  #### 7.3 About Kilimanjaro
153
153
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@k9o/extension-runtime",
3
- "version": "1.5.0",
3
+ "version": "1.6.0",
4
4
  "description": "Runtime client for code running inside a Kilimanjaro extension.",
5
5
  "type": "module",
6
6
  "main": "src/index.ts",
@@ -12,7 +12,7 @@
12
12
  "bun": ">=1.1.0"
13
13
  },
14
14
  "dependencies": {
15
- "@k9o/extension-manifest": "1.5.0"
15
+ "@k9o/extension-manifest": "1.6.0"
16
16
  },
17
17
  "license": "Apache-2.0",
18
18
  "homepage": "https://kilimanjaro.dev",
@@ -7,7 +7,7 @@
7
7
  * "bff" -> `payload` is a BffRequest -> k9o.bff.dispatch
8
8
  * "hook" -> hook handler named by `context.hookName`
9
9
  * "webhook" -> webhook handler registered for `context.webhookPath` (verified HTTP webhook or CometD)
10
- * "invoke"/"trigger" -> the ordinary function path
10
+ * "invoke"/"trigger"/"messaging.send" -> the ordinary function path (messaging.send is the platform's provider send)
11
11
  */
12
12
 
13
13
  import type { BffRequest, BffResponse } from "./namespaces/bff.ts";
@@ -15,7 +15,7 @@ import type { FunctionDispatchResult, FunctionInvocationRequest } from "./namesp
15
15
 
16
16
  export type DispatchResult = FunctionDispatchResult;
17
17
 
18
- export const DISPATCH_KINDS = ["bff", "hook", "invoke", "trigger", "webhook"] as const;
18
+ export const DISPATCH_KINDS = ["bff", "hook", "invoke", "messaging.send", "trigger", "webhook"] as const;
19
19
  export type DispatchKind = (typeof DISPATCH_KINDS)[number];
20
20
 
21
21
  export type DiscriminatorDeps = {
@@ -65,6 +65,7 @@ export async function routeExtensionInvocation(
65
65
  return { status: 200, body: result ?? null };
66
66
  }
67
67
  case "invoke":
68
+ case "messaging.send":
68
69
  case "trigger":
69
70
  return deps.dispatchFunction(frame);
70
71
  }
package/src/client.ts CHANGED
@@ -40,6 +40,8 @@ import { makeFunctions, type FunctionsNamespace } from "./namespaces/functions.t
40
40
  import { makeHooks, type HooksNamespace } from "./namespaces/hooks.ts";
41
41
  import { makeWebhookIngress, type WebhookIngressNamespace } from "./namespaces/webhook-ingress.ts";
42
42
  import { makeCompliance, type ComplianceNamespace } from "./namespaces/compliance.ts";
43
+ import { makeFiles, type FilesNamespace } from "./namespaces/files.ts";
44
+ import { makeAuthMigrations, type AuthMigrationsNamespace } from "./namespaces/auth-migrations.ts";
43
45
  import { makeAnalytics, type AnalyticsNamespace } from "./namespaces/analytics.ts";
44
46
 
45
47
  export type ExtensionClient = {
@@ -83,6 +85,10 @@ export type ExtensionClient = {
83
85
  compliance: ComplianceNamespace;
84
86
  /** Data Bridge inbound write into Pulse Analytics. */
85
87
  analytics: AnalyticsNamespace;
88
+ /** Read the bytes of an object in a project storage bucket, in ranges of at most 8 MiB. */
89
+ files: FilesNamespace;
90
+ /** The sign-in migration extension's calls: register a run, read it, and have the platform create its users. */
91
+ authMigrations: AuthMigrationsNamespace;
86
92
  };
87
93
 
88
94
  export type CreateExtensionClientOptions = {
@@ -97,13 +103,23 @@ export type CreateExtensionClientOptions = {
97
103
  * returns a placeholder that throws on subscribe/publish.
98
104
  */
99
105
  streamingTransport?: StreamingTransport;
106
+ /**
107
+ * Allow plain `http:` to a host that is not loopback. `true` or `false` wins over `K9O_ALLOW_INSECURE_HTTP`
108
+ * (`1` or `true`). Off by default: a base URL that is `http:` off loopback throws `K9O_INVALID_BASE_URL`.
109
+ */
110
+ allowInsecureHttp?: boolean;
100
111
  };
101
112
 
102
113
  export function createExtensionClient(
103
114
  options: CreateExtensionClientOptions = {},
104
115
  ): ExtensionClient {
105
116
  const ctx = resolveContext(options.context);
106
- const transport = createTransport(ctx.baseUrl, ctx.pluginToken, options.fetchFn);
117
+ const transport = createTransport(
118
+ ctx.baseUrl,
119
+ ctx.pluginToken,
120
+ options.fetchFn,
121
+ options.allowInsecureHttp === undefined ? {} : { allowInsecureHttp: options.allowInsecureHttp },
122
+ );
107
123
 
108
124
  return {
109
125
  documents: makeDocuments(transport, ctx.projectSlug),
@@ -126,5 +142,7 @@ export function createExtensionClient(
126
142
  webhookIngress: makeWebhookIngress(),
127
143
  compliance: makeCompliance(transport, ctx.projectSlug, ctx.extensionSlug),
128
144
  analytics: makeAnalytics(transport, ctx.projectSlug),
145
+ files: makeFiles(transport, ctx.projectSlug),
146
+ authMigrations: makeAuthMigrations(transport, ctx.projectSlug),
129
147
  };
130
148
  }
package/src/http.ts CHANGED
@@ -11,6 +11,13 @@
11
11
  */
12
12
 
13
13
  import { bytesToBase64 } from "./base64.ts";
14
+ import {
15
+ checkBaseUrlTransport,
16
+ fetchWithRedirectPolicy,
17
+ redirectRefusal,
18
+ resolveInsecureHttpOptIn,
19
+ type RedirectRefusal,
20
+ } from "./insecure-http.ts";
14
21
  import { RuntimeKError } from "./kerror.ts";
15
22
  import type { ApiResponse, KErrorPayload } from "./types.ts";
16
23
 
@@ -27,6 +34,11 @@ export type Transport = {
27
34
  post<T>(path: string, body?: unknown, extraHeaders?: Record<string, string>): Promise<ApiResponse<T>>;
28
35
  /** A POST that also reports the HTTP status, for the route whose 201 and 200 mean different things. */
29
36
  postWithStatus<T>(path: string, body?: unknown): Promise<{ status: number; body: ApiResponse<T> }>;
37
+ /**
38
+ * A POST whose 2xx answer is raw bytes, not a JSON envelope. Returns the body bytes and the response headers.
39
+ * A non-2xx answer is still the JSON KError body and throws a RuntimeKError; the plain-http and redirect policy apply.
40
+ */
41
+ postBytes(path: string, body?: unknown): Promise<{ status: number; bytes: Uint8Array; headers: Headers }>;
30
42
  patch<T>(path: string, body?: unknown): Promise<ApiResponse<T>>;
31
43
  delete_(path: string): Promise<void>;
32
44
  /** Raw fetch through the platform egress proxy — returns the platform-proxied Response. */
@@ -63,32 +75,62 @@ export function encodeProxyBody(
63
75
  /** Response header the egress proxy sets on every pass-through of an upstream response. */
64
76
  export const EGRESS_PROXIED_HEADER = "x-k9o-egress";
65
77
 
78
+ export type TransportOptions = {
79
+ /**
80
+ * Allow plain `http:` to a host that is not loopback. `true` or `false` wins over the `K9O_ALLOW_INSECURE_HTTP`
81
+ * environment variable (`1` or `true`); left unset, the environment decides. Never stored. A platform service sets it on
82
+ * the one client that needs it, not the environment process-wide.
83
+ */
84
+ allowInsecureHttp?: boolean;
85
+ };
86
+
87
+ const refusalError = (r: RedirectRefusal): RuntimeKError =>
88
+ new RuntimeKError(r.code, r.message, r.context, r.recommendation === null ? null : { hint: r.recommendation });
89
+
66
90
  export function createTransport(
67
91
  baseUrl: string,
68
92
  pluginToken: string,
69
93
  fetchFn: FetchFn = globalThis.fetch,
94
+ transportOptions: TransportOptions = {},
70
95
  ): Transport {
96
+ // Plain http off loopback is refused when the client is built, unless the caller opts in on purpose.
97
+ const check = checkBaseUrlTransport(baseUrl, { allowInsecureHttp: transportOptions.allowInsecureHttp });
98
+ if (check.refusal !== null) {
99
+ throw new RuntimeKError(check.refusal.code, check.refusal.message, check.refusal.context, {
100
+ hint: check.refusal.recommendation,
101
+ });
102
+ }
103
+ const allowInsecureHttp = resolveInsecureHttpOptIn(transportOptions.allowInsecureHttp);
71
104
  const headers = (): Record<string, string> => ({
72
105
  Authorization: `Bearer ${pluginToken}`,
73
106
  "Content-Type": "application/json",
74
107
  Accept: "application/json",
75
108
  });
76
109
 
77
- async function requestWithStatus<T>(
110
+ /** Sends one request through the redirect policy and throws a RuntimeKError on any non-2xx answer. */
111
+ async function send(
78
112
  method: string,
79
113
  path: string,
80
- body?: unknown,
81
- extraHeaders?: Record<string, string>,
82
- ): Promise<{ status: number; body: T }> {
114
+ body: unknown,
115
+ extraHeaders: Record<string, string> | undefined,
116
+ accept?: string,
117
+ ): Promise<Response> {
83
118
  const url = `${baseUrl}${path}`;
119
+ const baseHeaders = accept === undefined ? headers() : { ...headers(), Accept: accept };
84
120
  const init: RequestInit = {
85
121
  method,
86
- headers: extraHeaders === undefined ? headers() : { ...headers(), ...extraHeaders },
122
+ headers: extraHeaders === undefined ? baseHeaders : { ...baseHeaders, ...extraHeaders },
87
123
  };
88
124
  if (body !== undefined) {
89
125
  init.body = JSON.stringify(body);
90
126
  }
91
- const res = await fetchFn(url, init);
127
+ // Redirects are followed by hand: a cross-origin hop drops the bearer token and every other credential header.
128
+ const res = await fetchWithRedirectPolicy(
129
+ fetchFn,
130
+ url,
131
+ init as Parameters<typeof fetchWithRedirectPolicy>[2],
132
+ { allowInsecureHttp, makeError: refusalError },
133
+ );
92
134
  if (!res.ok) {
93
135
  const err = (await res.json().catch(() => ({
94
136
  code: "UNKNOWN_ERROR",
@@ -98,6 +140,16 @@ export function createTransport(
98
140
  }))) as KErrorPayload;
99
141
  throw new RuntimeKError(err.code, err.message, err.context, err.recommendation);
100
142
  }
143
+ return res;
144
+ }
145
+
146
+ async function requestWithStatus<T>(
147
+ method: string,
148
+ path: string,
149
+ body?: unknown,
150
+ extraHeaders?: Record<string, string>,
151
+ ): Promise<{ status: number; body: T }> {
152
+ const res = await send(method, path, body, extraHeaders);
101
153
  if (res.status === 204) {
102
154
  return { status: 204, body: undefined as T };
103
155
  }
@@ -119,6 +171,10 @@ export function createTransport(
119
171
  request<ApiResponse<T>>("POST", path, body, extraHeaders),
120
172
  postWithStatus: <T>(path: string, body?: unknown) =>
121
173
  requestWithStatus<ApiResponse<T>>("POST", path, body),
174
+ async postBytes(path, body) {
175
+ const res = await send("POST", path, body, undefined, "application/octet-stream");
176
+ return { status: res.status, bytes: new Uint8Array(await res.arrayBuffer()), headers: res.headers };
177
+ },
122
178
  patch: <T>(path: string, body?: unknown) =>
123
179
  request<ApiResponse<T>>("PATCH", path, body),
124
180
  delete_: (path: string) => request<void>("DELETE", path),
@@ -142,11 +198,24 @@ export function createTransport(
142
198
  headers: headerRecord,
143
199
  ...encodeProxyBody(options?.body),
144
200
  };
201
+ // `redirect: "manual"`, never followed: a proxied UPSTREAM 3xx (marked below) is the caller's data and is returned as it is,
202
+ // and a 3xx the proxy endpoint itself sends is refused, so the bearer token is never sent on.
145
203
  const res = await fetchFn(`${baseUrl}${proxyPath}`, {
146
204
  method: "POST",
147
205
  headers: headers(),
148
206
  body: JSON.stringify(proxyBody),
207
+ redirect: "manual",
149
208
  });
209
+ if (res.headers.get(EGRESS_PROXIED_HEADER) !== "proxied" && ((res.status >= 300 && res.status <= 399) || res.type === "opaqueredirect")) {
210
+ const location = res.headers.get("location");
211
+ let origin: string | null = null;
212
+ try {
213
+ origin = location === null ? null : new URL(location, baseUrl).origin;
214
+ } catch {
215
+ origin = null;
216
+ }
217
+ throw refusalError(redirectRefusal(res.status, origin, "not_a_redirect"));
218
+ }
150
219
  // The proxy marks every pass-through of an UPSTREAM response with `x-k9o-egress: proxied`, so an
151
220
  // upstream 4xx/5xx (an S3 SlowDown, a vendor 500) reaches the caller with its own status, body and
152
221
  // headers. An unmarked non-2xx/3xx response was produced by the proxy itself (grant or binding
package/src/index.ts CHANGED
@@ -7,6 +7,7 @@
7
7
  * KError: thrown on any platform error; catch with `instanceof KError`.
8
8
  */
9
9
 
10
+ export type { TransportOptions } from "./http.ts";
10
11
  export { createExtensionClient, type ExtensionClient, type CreateExtensionClientOptions } from "./client.ts";
11
12
  export type { BffNamespace, BffHandler, BffRequest, BffResponse, BffOperator } from "./namespaces/bff.ts";
12
13
  export type {
@@ -67,10 +68,30 @@ export type {
67
68
  VectorsNamespace,
68
69
  VectorRow,
69
70
  VectorsUpsertResult,
71
+ VectorsDeleteQuery,
72
+ VectorsDeleteResult,
70
73
  VectorSearchQuery,
71
74
  VectorSearchResult,
72
75
  VectorSearchResultRow,
76
+ VectorsUpsertOptions,
73
77
  } from "./namespaces/vectors.ts";
78
+ export type { FilesNamespace, FilesReadOptions, FilesReadResult } from "./namespaces/files.ts";
79
+ export type {
80
+ AuthMigrationsNamespace,
81
+ AuthMigrationsCreateRunBody,
82
+ AuthMigrationsCreateUsersOptions,
83
+ AuthMigrationsCreateUsersResult,
84
+ AuthMigrationRun,
85
+ AuthMigrationSource,
86
+ AuthMigrationPasswordHandling,
87
+ AuthMigrationUser,
88
+ AuthMigrationUserResult,
89
+ } from "./namespaces/auth-migrations.ts";
90
+ export {
91
+ AUTH_MIGRATIONS_MAX_USERS_PER_CALL,
92
+ AUTH_MIGRATIONS_HASH_EXPIRY_MAX_DAYS,
93
+ AUTH_MIGRATIONS_ROLLBACK_RETENTION_MAX_DAYS,
94
+ } from "./namespaces/auth-migrations.ts";
74
95
  export { RuntimeKError as KError, RuntimeKError, QueuedWriteError } from "./kerror.ts";
75
96
  export { isKError, assertKError } from "./guards.ts";
76
97
  export type { SandboxContext } from "./types.ts";