@k9o/extension-runtime 0.0.0-stage → 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.
Files changed (40) hide show
  1. package/LICENSE +201 -0
  2. package/NOTICE +4 -0
  3. package/README.md +166 -2
  4. package/package.json +30 -4
  5. package/src/base64.ts +11 -0
  6. package/src/bff-hook-discriminator.ts +72 -0
  7. package/src/client.ts +148 -0
  8. package/src/context.ts +70 -0
  9. package/src/dispatch-context.ts +58 -0
  10. package/src/guards.ts +35 -0
  11. package/src/http.ts +233 -0
  12. package/src/index.ts +163 -0
  13. package/src/insecure-http.ts +575 -0
  14. package/src/invoke-server.ts +150 -0
  15. package/src/kerror.ts +45 -0
  16. package/src/namespaces/ai-agent-runtime.ts +170 -0
  17. package/src/namespaces/ai.ts +56 -0
  18. package/src/namespaces/analytics.ts +122 -0
  19. package/src/namespaces/attributes.ts +34 -0
  20. package/src/namespaces/audit.ts +92 -0
  21. package/src/namespaces/auth-migrations.ts +176 -0
  22. package/src/namespaces/bff.ts +140 -0
  23. package/src/namespaces/collections.ts +104 -0
  24. package/src/namespaces/compliance.ts +48 -0
  25. package/src/namespaces/credentials.ts +85 -0
  26. package/src/namespaces/documents.ts +128 -0
  27. package/src/namespaces/egress.ts +31 -0
  28. package/src/namespaces/files.ts +96 -0
  29. package/src/namespaces/functions.ts +91 -0
  30. package/src/namespaces/hooks.ts +186 -0
  31. package/src/namespaces/identity.ts +97 -0
  32. package/src/namespaces/kibo.ts +60 -0
  33. package/src/namespaces/policy.ts +50 -0
  34. package/src/namespaces/streaming.ts +80 -0
  35. package/src/namespaces/tables.ts +166 -0
  36. package/src/namespaces/vectors.ts +243 -0
  37. package/src/namespaces/webhook-ingress.ts +98 -0
  38. package/src/namespaces/workflow.ts +65 -0
  39. package/src/types.ts +143 -0
  40. package/src/warden.ts +320 -0
@@ -0,0 +1,128 @@
1
+ /**
2
+ * k9o.documents — data access namespace + ch04 data pillar.
3
+ *
4
+ * Composed against manifest-declared permission scope triples
5
+ * EXTENSION_PERMISSION_DENIED (403) is thrown by RuntimeKError if the manifest
6
+ * did not grant the required (documents, action, qualifier) triple.
7
+ *
8
+ * Endpoint paths: the gateway's data-plane record routes, `/@<project>/data/<collection>`.
9
+ * That is the surface the extension grant gate classifies (`classifyForGrant`: `/data/<col>` GET is
10
+ * `(documents, read, <col>)`, POST/PUT/PATCH is write, DELETE is delete) and the one the callback bridge
11
+ * allow-lists. The earlier `/collections/<c>/documents` path has no gateway route.
12
+ */
13
+
14
+ import type { Transport } from "../http.ts";
15
+ import { QueuedWriteError } from "../kerror.ts";
16
+ import type { ApiResponse, Document, DocumentFilter } from "../types.ts";
17
+
18
+ export type DocumentsNamespace = {
19
+ read(
20
+ collection: string,
21
+ filter?: DocumentFilter,
22
+ ): Promise<ApiResponse<Document[]>>;
23
+ /** Throws `QueuedWriteError` when a project approval policy queued the write instead of applying it. */
24
+ write(collection: string, data: Document): Promise<ApiResponse<Document>>;
25
+ /**
26
+ * Insert-or-ignore create with a caller-supplied row `id`, so a retry after a lost reply stores one row.
27
+ * `created` is true when this call stored the row (201) and false when the id already existed (200): the
28
+ * stored row comes back and `data` is NOT applied. A gateway that does not yet reject a replay whose columns differ
29
+ * from the stored row (409, no row returned) answers 200 there too, so a differing replay keeps the first values
30
+ * silently; on a gateway that does, that call throws `KError` with the 409. Do not rely on retry being safe against
31
+ * a gateway without the 409. An older gateway also answers 200 for a new row, so `created` is meaningful only
32
+ * against a gateway that answers 201 for one.
33
+ * Throws `QueuedWriteError` when a project approval policy queued the write; a retry may queue a second case.
34
+ */
35
+ insert(collection: string, data: Document & { id: string }): Promise<ApiResponse<Document> & { created: boolean }>;
36
+ /** Throws `QueuedWriteError` when a project approval policy queued the delete instead of applying it. */
37
+ delete(collection: string, id: string): Promise<void>;
38
+ };
39
+
40
+ /** The gateway's reserved list-query keys: a filter column with one of these names would be read as a control. */
41
+ const RESERVED_QUERY_KEYS = new Set([
42
+ "limit", "cursor", "count", "select", "order", "single", "range", "or", "aggregate", "embed",
43
+ "textSearch", "textSearchLanguage", "textSearchType", "vectorSearch", "vectorMetric", "vectorLimit",
44
+ "reveal", "revealPurpose", "deleted",
45
+ ]);
46
+ const COLUMN = /^[a-zA-Z_][a-zA-Z0-9_]{0,62}$/;
47
+ /** Compared case-insensitively: whether the gateway matches a reserved key exactly is not something the SDK relies on. */
48
+ const RESERVED_LOWER = new Set([...RESERVED_QUERY_KEYS].map((k) => k.toLowerCase()));
49
+
50
+ /** `eq` map to the gateway's `?<col>=<op>.<value>` filter grammar. Refuses what it cannot say exactly. */
51
+ function filterParams(eq: Record<string, unknown>): [string, string][] {
52
+ const out: [string, string][] = [];
53
+ for (const [col, v] of Object.entries(eq)) {
54
+ if (!COLUMN.test(col)) throw new TypeError(`documents.read: filter column "${col}" is not a valid column name`);
55
+ if (RESERVED_LOWER.has(col.toLowerCase())) throw new TypeError(`documents.read: filter column "${col}" collides with a reserved list parameter`);
56
+ if (v === null) out.push([col, "is.null"]);
57
+ else if (typeof v === "number" && !Number.isFinite(v)) throw new TypeError(`documents.read: filter value for "${col}" must be a finite number`);
58
+ else if (typeof v === "string" || typeof v === "number" || typeof v === "boolean") out.push([col, `eq.${String(v)}`]);
59
+ else throw new TypeError(`documents.read: filter value for "${col}" must be a string, number, boolean or null`);
60
+ }
61
+ return out;
62
+ }
63
+
64
+ /** A path segment must name something: `.`, `..` and the empty string are path operators or nothing, never a collection or id. */
65
+ export function segment(what: "collection" | "id", v: unknown): string {
66
+ if (typeof v !== "string" || v === "" || v === "." || v === "..") {
67
+ throw new TypeError(`documents: ${what} must be a non-empty name, not "." or ".."`);
68
+ }
69
+ return encodeURIComponent(v);
70
+ }
71
+
72
+ /** A direct write the gateway queued answers 202 `{ data: { id, status: "pending_approval" } }` (`gateSingleRecordWrite`). */
73
+ function refuseQueued(operation: string, collection: string, res: unknown): void {
74
+ const data = (res as { data?: { id?: unknown; status?: unknown } } | undefined)?.data;
75
+ if (data?.status === "pending_approval") {
76
+ throw new QueuedWriteError(operation, collection, typeof data.id === "string" ? data.id : null);
77
+ }
78
+ }
79
+
80
+ export function makeDocuments(
81
+ transport: Transport,
82
+ projectSlug: string,
83
+ ): DocumentsNamespace {
84
+ const base = (collection: string) => `/@${projectSlug}/data/${segment("collection", collection)}`;
85
+
86
+ return {
87
+ async read(collection, filter) {
88
+ const params = new URLSearchParams();
89
+ if (filter?.limit) params.set("limit", String(filter.limit));
90
+ if (filter?.cursor) params.set("cursor", filter.cursor);
91
+ if (filter?.eq) for (const [k, v] of filterParams(filter.eq)) params.append(k, v);
92
+ const qs = params.size > 0 ? `?${params.toString()}` : "";
93
+ return transport.get<Document[]>(`${base(collection)}${qs}`);
94
+ },
95
+
96
+ async write(collection, data) {
97
+ const { id, ...rest } = data as Document & { id?: unknown };
98
+ // A present non-string id must not fall through to a create: an intended update would insert a row.
99
+ if (id !== undefined && typeof id !== "string") {
100
+ throw new TypeError("documents.write: id must be a string when present");
101
+ }
102
+ if (typeof id === "string") {
103
+ // The id is the path; the body carries only the fields to change.
104
+ const res = await transport.patch<Document>(`${base(collection)}/${segment("id", id)}`, rest);
105
+ refuseQueued("write", collection, res);
106
+ return res;
107
+ }
108
+ const res = await transport.post<Document>(base(collection), data);
109
+ refuseQueued("write", collection, res);
110
+ return res;
111
+ },
112
+
113
+ async insert(collection, data) {
114
+ const id = (data as { id?: unknown } | null)?.id;
115
+ if (typeof id !== "string") throw new TypeError("documents.insert: id must be a string");
116
+ segment("id", id);
117
+ const { status, body } = await transport.postWithStatus<Document>(`${base(collection)}?onConflict=ignore`, data);
118
+ refuseQueued("insert", collection, body);
119
+ return { ...body, created: status === 201 };
120
+ },
121
+
122
+ async delete(collection, id) {
123
+ // The transport types a DELETE as void, but the gateway answers a queued delete with a 202 body.
124
+ const res: unknown = await transport.delete_(`${base(collection)}/${segment("id", id)}`);
125
+ refuseQueued("delete", collection, res);
126
+ },
127
+ };
128
+ }
@@ -0,0 +1,31 @@
1
+ /**
2
+ * k9o.fetch — manifest-declared egress dependencies.
3
+ *
4
+ * Extensions CANNOT call arbitrary URLs directly; the sandbox network is
5
+ * restricted. All outbound HTTP goes through the platform's egress proxy
6
+ * which enforces the manifest's per-extension allowlist.
7
+ *
8
+ * Callers use k9o.fetch exactly like globalThis.fetch; the proxy returns
9
+ * the upstream Response, status and headers included (marked `x-k9o-egress: proxied`).
10
+ * A failure produced by the proxy itself (not granted, not bound, blocked target, size
11
+ * cap, timeout) carries no such marker and is thrown as a RuntimeKError.
12
+ *
13
+ * Named `egress` internally to avoid collision with the `fetch` keyword;
14
+ * exported to the k9o client object as `k9o.fetch`.
15
+ */
16
+
17
+ import type { Transport } from "../http.ts";
18
+
19
+ export type EgressNamespace = {
20
+ fetch(url: string, options?: RequestInit): Promise<Response>;
21
+ };
22
+
23
+ export function makeEgress(
24
+ transport: Transport,
25
+ projectSlug: string,
26
+ extensionSlug: string,
27
+ ): EgressNamespace {
28
+ return {
29
+ fetch: (url, options) => transport.proxyFetch(projectSlug, extensionSlug, url, options),
30
+ };
31
+ }
@@ -0,0 +1,96 @@
1
+ /**
2
+ * k9o.files — read the bytes of an object in a project storage bucket.
3
+ *
4
+ * Needs the manifest's `files read` grant on the bucket; nothing else in the manifest changes. The gateway returns at most
5
+ * 8 MiB per read: read a larger object in ranges with `offset` and `length`. Every read is recorded in the project's audit
6
+ * log before any byte is sent, and the read's id (`readId`) is what `vectors.upsert(..., { fromRead })` takes when the
7
+ * rows were derived from these bytes.
8
+ *
9
+ * An extension reads only an object whose data subject the platform recorded at upload; any other object is refused with
10
+ * `K9O_OBJECT_SUBJECT_UNRESOLVED`. Other refusals reach the caller as the route gave them (`K9O_RATE_LIMITED` with
11
+ * `context.retryAfter` when reads come too fast, `K9O_INVALID_FIELD_VALUE` for an offset past the end of the object,
12
+ * `K9O_EXTENSION_PERMISSION_DENIED` without the grant or for a system bucket, a not-found error for a missing object).
13
+ *
14
+ * Gateway route:
15
+ * POST /@{projectSlug}/storage/buckets/{bucket}/objects/content body { path, offset?, length? }, raw bytes back
16
+ */
17
+
18
+ import type { Transport } from "../http.ts";
19
+ import { RuntimeKError } from "../kerror.ts";
20
+
21
+ /** The most bytes one read returns: 8 MiB. */
22
+ export const FILES_READ_MAX_LENGTH = 8 * 1024 * 1024;
23
+
24
+ export type FilesReadOptions = {
25
+ /** The object's path in the bucket, 1 to 1024 characters. */
26
+ path: string;
27
+ /** The first byte to return, from 0 (default 0). */
28
+ offset?: number;
29
+ /** How many bytes to return, 1 to 8388608 (default: to the end of the object, at most 8 MiB). */
30
+ length?: number;
31
+ };
32
+
33
+ export type FilesReadResult = {
34
+ /** The bytes from `offset`, at most `length` of them. */
35
+ bytes: Uint8Array;
36
+ /** The id of this read's audit event (`evt_...`); pass it as `fromRead` when writing vectors derived from these bytes. */
37
+ readId: string;
38
+ /** The object's whole size in bytes, not the size of this range; `null` when the platform could not tell. */
39
+ size: number | null;
40
+ /** The object's content type as uploaded, or an empty string when none was recorded. */
41
+ contentType: string;
42
+ };
43
+
44
+ export type FilesNamespace = {
45
+ read(bucket: string, options: FilesReadOptions): Promise<FilesReadResult>;
46
+ };
47
+
48
+ const invalidField = (field: string, message: string, extra: Record<string, unknown> = {}): RuntimeKError =>
49
+ new RuntimeKError("K9O_INVALID_FIELD_VALUE", message, { field, ...extra });
50
+
51
+ const invalidResponse = (header: string, message: string): RuntimeKError =>
52
+ new RuntimeKError("K9O_INVALID_RESPONSE", message, { header });
53
+
54
+ export function makeFiles(transport: Transport, projectSlug: string): FilesNamespace {
55
+ return {
56
+ async read(bucket, options) {
57
+ if (typeof bucket !== "string" || bucket.length === 0) throw invalidField("bucket", "bucket must be a non-empty string");
58
+ const { path, offset, length } = options;
59
+ if (typeof path !== "string" || path.length === 0) throw invalidField("path", "path must be a non-empty string");
60
+ if (offset !== undefined && (!Number.isInteger(offset) || offset < 0)) {
61
+ throw invalidField("offset", "offset must be a whole number of bytes, 0 or more");
62
+ }
63
+ if (length !== undefined) {
64
+ if (!Number.isInteger(length) || length < 1) {
65
+ throw invalidField("length", "length must be a whole number of bytes, 1 or more");
66
+ }
67
+ if (length > FILES_READ_MAX_LENGTH) {
68
+ throw invalidField("length", `length is at most ${FILES_READ_MAX_LENGTH} bytes; read a larger object in ranges`, {
69
+ max: FILES_READ_MAX_LENGTH,
70
+ });
71
+ }
72
+ }
73
+ const body: { path: string; offset?: number; length?: number } = { path };
74
+ if (offset !== undefined) body.offset = offset;
75
+ if (length !== undefined) body.length = length;
76
+ const res = await transport.postBytes(
77
+ `/@${projectSlug}/storage/buckets/${encodeURIComponent(bucket)}/objects/content`,
78
+ body,
79
+ );
80
+ const readId = res.headers.get("K9O-Read-Id");
81
+ if (readId === null || readId.length === 0) {
82
+ throw invalidResponse("K9O-Read-Id", "The object read came back without a K9O-Read-Id header");
83
+ }
84
+ const sizeHeader = res.headers.get("K9O-Object-Size");
85
+ if (sizeHeader === null || (sizeHeader !== "" && !/^\d+$/.test(sizeHeader))) {
86
+ throw invalidResponse("K9O-Object-Size", "The object read came back without a usable K9O-Object-Size header");
87
+ }
88
+ return {
89
+ bytes: res.bytes,
90
+ readId,
91
+ size: sizeHeader === "" ? null : Number(sizeHeader),
92
+ contentType: res.headers.get("K9O-Object-Content-Type") ?? "",
93
+ };
94
+ },
95
+ };
96
+ }
@@ -0,0 +1,91 @@
1
+ /**
2
+ * k9o.functions — Platform-tier function handler registration namespace.
3
+ *
4
+ * Extension authors register function handlers via `k9o.functions.handle(name, handler)`.
5
+ * This is the SDK counterpart to k9o-init's `:8081` reverse-proxy target
6
+ * (`invoke-server.ts` wires this
7
+ * namespace's `dispatch()` to an actual HTTP listener).
8
+ *
9
+ * `name` matches the manifest's `background_logic.functions[].name` (ch09
10
+ * `FunctionDescriptor`) for Path A (`runtime_tier: "container"`)
11
+ * extensions — the extension's own persistent process serves invocations
12
+ * for however many function names it registers.
13
+ *
14
+ * Handler ergonomics are RPC-style (Lambda-like): return the result value on
15
+ * success, throw on failure. `dispatch()` catches thrown errors and maps them
16
+ * to the runtime-error status (500) — extension authors never
17
+ * construct HTTP status codes themselves.
18
+ */
19
+
20
+ export type FunctionInvocationRequest = {
21
+ /** Matches the manifest-declared function name being invoked. */
22
+ functionName: string;
23
+ /** Caller-supplied payload — the function's argument. */
24
+ payload: unknown;
25
+ /** Unique per-invocation id, minted by the gateway. */
26
+ invocationId: string;
27
+ /** Function version, when the platform tracks per-function versioning. */
28
+ version?: unknown;
29
+ /**
30
+ * inject-locus — the plugin-token context (when the invocation
31
+ * carries an extension-scoped token for gateway callbacks).
32
+ */
33
+ context?: unknown;
34
+ };
35
+
36
+ export type FunctionHandler = (
37
+ req: FunctionInvocationRequest,
38
+ ) => Promise<unknown> | unknown;
39
+
40
+ export type FunctionDispatchResult = {
41
+ /** 200 on success; 500 when the handler threw; 400 when `functionName` has no registered handler. */
42
+ status: number;
43
+ body: unknown;
44
+ };
45
+
46
+ export type FunctionsNamespace = {
47
+ /**
48
+ * Register a handler for a function name.
49
+ * Registering the same name twice overwrites the first handler (last-write-wins).
50
+ */
51
+ handle(name: string, handler: FunctionHandler): void;
52
+ /**
53
+ * Invoke the registered handler for a function invocation request.
54
+ * Used by `startInvokeServer()` to serve k9o-init's `:8081` reverse-proxy target.
55
+ * Returns `{ status: 400, body: { error: "..." } }` when no handler is registered.
56
+ */
57
+ dispatch(req: FunctionInvocationRequest): Promise<FunctionDispatchResult>;
58
+ /** Inspect the set of names that have a registered handler. Frozen snapshot. */
59
+ registeredNames(): readonly string[];
60
+ };
61
+
62
+ export function makeFunctions(): FunctionsNamespace {
63
+ const registry = new Map<string, FunctionHandler>();
64
+
65
+ return {
66
+ handle(name, handler) {
67
+ registry.set(name, handler);
68
+ },
69
+
70
+ async dispatch(req) {
71
+ const handler = registry.get(req.functionName);
72
+ if (!handler) {
73
+ return {
74
+ status: 400,
75
+ body: { error: `No function handler registered for: ${req.functionName}` },
76
+ };
77
+ }
78
+ try {
79
+ const result = await handler(req);
80
+ return { status: 200, body: result ?? null };
81
+ } catch (e) {
82
+ const message = e instanceof Error ? e.message : String(e);
83
+ return { status: 500, body: { error: message } };
84
+ }
85
+ },
86
+
87
+ registeredNames() {
88
+ return Object.freeze([...registry.keys()]);
89
+ },
90
+ };
91
+ }
@@ -0,0 +1,186 @@
1
+ /**
2
+ * k9o.hooks — lifecycle-hook handler registration ("Hook delivery").
3
+ *
4
+ * An extension declares which hooks it serves in `manifest.hooks` (`{ enable: "POST /hooks/enable" }`)
5
+ * and registers the implementation here: `k9o.hooks.handle("enable", (payload, ctx) => { ... })`.
6
+ *
7
+ * Delivery inside the sandbox: the gateway sends the hook through the same dispatcher as a request,
8
+ * with the platform as actor, and sets the frame `context.kind = "hook"` plus `context.hookName` (the
9
+ * event name, one of `HOOK_EVENTS`). The discriminator routes to this namespace ONLY on that
10
+ * gateway-set field; the declared path is not a route here and the payload cannot select a hook.
11
+ * Delivery inside the sandbox needs no HMAC (`hookSecret` applies only to a delivery that crosses to
12
+ * an external host, none is specified for v2).
13
+ *
14
+ * Delivery is at-least-once: `purge` fires before teardown and a stranded-purge sweep may deliver it
15
+ * again, and critical hooks are retried, so every handler MUST be idempotent.
16
+ *
17
+ * `call_decided` is not a lifecycle event: it carries the outcome of a call the Warden held for approval, sent only to
18
+ * the install that made the call, once the call has ended. Serve it with `onCallDecided`, which validates the payload
19
+ * and hands the handler a typed {@link CallDecided}. A delivery the handler acknowledges collects the result: the
20
+ * platform deletes it. Throw `HookRejectedError` to refuse it without a retry (the result then stays readable at
21
+ * `GET /@<project>/mcp/calls/:callId` until it expires); throw anything else and it is retried.
22
+ *
23
+ * Failure semantics follow: a handler that throws is a 5xx (the gateway retries critical
24
+ * hooks); a handler that wants to refuse throws `HookRejectedError` with a 4xx status (application-level
25
+ * rejection, no retry). A hook the manifest declares but no handler serves fails loudly (5xx), never a
26
+ * silent success.
27
+ */
28
+
29
+ import type { HookEvent } from "@k9o/extension-manifest";
30
+ import type { DispatchContext } from "../dispatch-context.ts";
31
+
32
+ export type { HookEvent };
33
+
34
+ /** The closed v2 hook-event enum, and `call_decided`. */
35
+ export const HOOK_EVENTS = ["enable", "configure", "activate", "deactivate", "purge", "monitor", "data_export", "call_decided"] as const satisfies readonly HookEvent[];
36
+
37
+ /** How a held call ended. `done` carries the tool's result; the others ran nothing, or nothing that answered. */
38
+ export type CallDecidedOutcome = "done" | "refused" | "rejected" | "expired";
39
+ const CALL_DECIDED_OUTCOMES: readonly CallDecidedOutcome[] = ["done", "refused", "rejected", "expired"];
40
+
41
+ /** The `call_decided` payload, as the gateway builds it. */
42
+ export type CallDecided = {
43
+ event: "call_decided";
44
+ extensionId: string;
45
+ projectId: string;
46
+ /** The id the held answer named (the approval id). */
47
+ callId: string;
48
+ outcome: CallDecidedOutcome;
49
+ /** A fixed reason word (for example `token_revoked`, `approval_window_closed`, `tool_error`), or null. */
50
+ reason: string | null;
51
+ /** ISO 8601. */
52
+ endedAt: string | null;
53
+ /** The tool's answer when `outcome` is `done`, else null. */
54
+ result: unknown;
55
+ };
56
+
57
+ export type CallDecidedHandler = (call: CallDecided, ctx: DispatchContext) => Promise<unknown> | unknown;
58
+
59
+ /** A `call_decided` body this SDK can type, or null. */
60
+ function asCallDecided(body: Record<string, unknown>): CallDecided | null {
61
+ const str = (v: unknown): v is string => typeof v === "string" && v.length > 0;
62
+ const nullableStr = (v: unknown): v is string | null => v === null || typeof v === "string";
63
+ const outcome = body["outcome"];
64
+ if (!str(body["callId"]) || !str(body["extensionId"]) || !str(body["projectId"])) return null;
65
+ if (typeof outcome !== "string" || !(CALL_DECIDED_OUTCOMES as readonly string[]).includes(outcome)) return null;
66
+ if (!nullableStr(body["reason"] ?? null) || !nullableStr(body["endedAt"] ?? null)) return null;
67
+ return {
68
+ event: "call_decided",
69
+ extensionId: body["extensionId"],
70
+ projectId: body["projectId"],
71
+ callId: body["callId"],
72
+ outcome: outcome as CallDecidedOutcome,
73
+ reason: (body["reason"] as string | null | undefined) ?? null,
74
+ endedAt: (body["endedAt"] as string | null | undefined) ?? null,
75
+ result: outcome === "done" ? (body["result"] ?? null) : null,
76
+ };
77
+ }
78
+
79
+ /**
80
+ * The canonical hook body, as the gateway builds it. Lifecycle hooks carry the delivery
81
+ * fields; `monitor` carries only ids and correlation ids and no customer data. The gateway is
82
+ * authoritative for the field set; unknown extra fields are passed through untouched.
83
+ */
84
+ export type HookPayload = {
85
+ event: HookEvent;
86
+ extensionId: string;
87
+ projectId: string;
88
+ orgId?: string;
89
+ deliveryId?: string;
90
+ timestamp?: string;
91
+ manifestVersion?: string;
92
+ /** The grants just bound (enable) or in force. */
93
+ permissionGrants?: unknown[];
94
+ /** Current per-project configuration; empty on first enable. */
95
+ config?: Record<string, unknown>;
96
+ /** `monitor` correlation ids. */
97
+ requestId?: string;
98
+ traceId?: string;
99
+ [extra: string]: unknown;
100
+ };
101
+
102
+ /** `monitor` must return this closed shape. */
103
+ export type MonitorResult = { healthy: boolean; message?: string; details?: Record<string, unknown> };
104
+
105
+ export type HookHandler = (payload: HookPayload, ctx: DispatchContext) => Promise<unknown> | unknown;
106
+
107
+ /** Throw from a handler to reject a delivery at application level: a 4xx is not retried. */
108
+ export class HookRejectedError extends Error {
109
+ readonly status: number;
110
+ constructor(message: string, status = 400) {
111
+ super(message);
112
+ this.name = "HookRejectedError";
113
+ if (!Number.isInteger(status) || status < 400 || status > 499) {
114
+ throw new RangeError("HookRejectedError status must be a 4xx integer");
115
+ }
116
+ this.status = status;
117
+ }
118
+ }
119
+
120
+ export type HooksNamespace = {
121
+ /** Register the handler for one hook event. Registering the same event twice overwrites (last write wins). */
122
+ handle(event: HookEvent, handler: HookHandler): void;
123
+ /**
124
+ * Serve `call_decided`: the outcome of a call this install made that the Warden held for approval. Declare
125
+ * `hooks.call_decided` (`"POST /hooks/call-decided"`) in the manifest, or nothing is sent. Same as
126
+ * `handle("call_decided", …)` with the payload checked and typed; a malformed one is a 4xx rejection.
127
+ */
128
+ onCallDecided(handler: CallDecidedHandler): void;
129
+ /**
130
+ * Deliver a hook to its handler. Used by the invoke server for `context.kind === "hook"` frames.
131
+ * Rejects with `HookRejectedError` (4xx) for an unknown event or a payload whose own `event` disagrees
132
+ * with the frame's, and with a plain `Error` (5xx) when no handler is registered or `monitor` returns
133
+ * the wrong shape.
134
+ */
135
+ dispatch(event: string, payload: unknown, ctx: DispatchContext): Promise<unknown>;
136
+ /** Events that have a handler. Frozen snapshot. */
137
+ registeredEvents(): readonly HookEvent[];
138
+ };
139
+
140
+ function isHookEvent(v: string): v is HookEvent {
141
+ return (HOOK_EVENTS as readonly string[]).includes(v);
142
+ }
143
+
144
+ export function makeHooks(): HooksNamespace {
145
+ const registry = new Map<HookEvent, HookHandler>();
146
+
147
+ return {
148
+ handle(event, handler) {
149
+ if (!isHookEvent(event)) throw new RangeError(`unknown hook event: ${String(event)}`);
150
+ registry.set(event, handler);
151
+ },
152
+
153
+ onCallDecided(handler) {
154
+ registry.set("call_decided", (payload, ctx) => {
155
+ const call = asCallDecided(payload as Record<string, unknown>);
156
+ if (call === null) throw new HookRejectedError("call_decided payload is malformed", 400);
157
+ return handler(call, ctx);
158
+ });
159
+ },
160
+
161
+ async dispatch(event, payload, ctx) {
162
+ if (!isHookEvent(event)) throw new HookRejectedError("unknown hook event", 400);
163
+ if (payload === null || typeof payload !== "object" || Array.isArray(payload)) {
164
+ throw new HookRejectedError("hook payload must be an object", 400);
165
+ }
166
+ const body = payload as Record<string, unknown>;
167
+ if (body["event"] !== undefined && body["event"] !== event) {
168
+ throw new HookRejectedError("hook payload event does not match the delivered hook", 400);
169
+ }
170
+ const handler = registry.get(event);
171
+ if (handler === undefined) throw new Error(`no handler is registered for the "${event}" hook`);
172
+ const result = await handler({ ...body, event } as HookPayload, ctx);
173
+ if (event === "monitor") {
174
+ const r = result as Record<string, unknown> | null | undefined;
175
+ if (r === null || typeof r !== "object" || typeof r["healthy"] !== "boolean") {
176
+ throw new Error('the "monitor" hook must return { healthy: boolean, message?, details? }');
177
+ }
178
+ }
179
+ return result ?? null;
180
+ },
181
+
182
+ registeredEvents() {
183
+ return Object.freeze(HOOK_EVENTS.filter((e) => registry.has(e)));
184
+ },
185
+ };
186
+ }
@@ -0,0 +1,97 @@
1
+ /**
2
+ * k9o.identity — the calling user's JWT claims, and the project's identity providers (read only).
3
+ *
4
+ * `current()`: the platform propagates the end-user's JWT claims into the sandbox context
5
+ * so extensions can personalise responses and attribute actions. The claims
6
+ * reflect the user who triggered the extension invocation (hook caller or
7
+ * runtime API caller), not the extension itself.
8
+ *
9
+ * Per — extension tokens carry actor: "extension" + extensionId;
10
+ * the user context is forwarded as a separate propagated claim.
11
+ *
12
+ * `providers.list()`: the project's configured end-user identity providers, so an extension can LIST
13
+ * and PICK one (Gate Studio's flow editor). **Read only by ruling**:
14
+ * create, edit, test and directory sync stay in the Console under the operator's own scope, so this
15
+ * namespace has no write call and the type below carries no secret field. Requires the
16
+ * `identities.read` grant (qualifier `"*"`); the gateway rejects an extension token on every other
17
+ * identity-provider route.
18
+ */
19
+
20
+ import type { Transport } from "../http.ts";
21
+ import type { ApiResponse, IdentityClaims } from "../types.ts";
22
+
23
+ /**
24
+ * One configured project identity provider, exactly the gateway's read shape (`shapeIdpConfig`).
25
+ * Secrets are write-only on the platform: a read carries only the presence boolean `clientSecretSet`,
26
+ * never the secret, its handle, or a directory-sync service-account key.
27
+ */
28
+ export type IdentityProviderConfig = {
29
+ id: string;
30
+ projectId: string;
31
+ /** The gateway's closed provider set (for example `google`, `microsoft`, `ldap`); kept a string so a new provider is not a breaking change here. */
32
+ idpProvider: string;
33
+ displayName: string;
34
+ clientId: string;
35
+ /** Whether a client secret is stored. The secret itself is never returned. */
36
+ clientSecretSet: boolean;
37
+ redirectUri: string;
38
+ metadataUrl: string | null;
39
+ attributeMap: Record<string, unknown>;
40
+ tierGating: string;
41
+ enabled: boolean;
42
+ allowedRedirectUris: string[];
43
+ directoryPullEnabled: boolean;
44
+ directorySyncSubject: string | null;
45
+ directorySyncIntervalMins: number | null;
46
+ directorySyncLastRunAt: string | null;
47
+ directorySyncLastStatus: string | null;
48
+ createdAt: string;
49
+ updatedAt: string | null;
50
+ };
51
+
52
+ // Compile-time pin (the package's tsc does not compile the tests, so this lives here): the read type must never gain
53
+ // a write-only secret field. Adding one makes `_noSecretFields` fail to typecheck.
54
+ type WriteOnlySecretFields = "clientSecretRef" | "clientSecret" | "serviceAccountKey";
55
+ type NoSecretFields = [Extract<keyof IdentityProviderConfig, WriteOnlySecretFields>] extends [never] ? true : never;
56
+ const _noSecretFields: NoSecretFields = true;
57
+ void _noSecretFields;
58
+
59
+ export type ListIdentityProvidersOptions = {
60
+ /** Opaque cursor from the previous page's `meta.cursor.next`. */
61
+ cursor?: string;
62
+ /** Page size, a positive integer; the gateway applies its own maximum. */
63
+ limit?: number;
64
+ };
65
+
66
+ export type IdentityProvidersNamespace = {
67
+ /**
68
+ * List the project's identity providers, newest first. Returns the platform envelope: rows in `data`,
69
+ * the next page's cursor in `meta.cursor.next` (null on the last page).
70
+ */
71
+ list(options?: ListIdentityProvidersOptions): Promise<ApiResponse<IdentityProviderConfig[]>>;
72
+ };
73
+
74
+ export type IdentityNamespace = {
75
+ current(): Promise<ApiResponse<IdentityClaims>>;
76
+ providers: IdentityProvidersNamespace;
77
+ };
78
+
79
+ export function makeIdentity(transport: Transport, projectSlug: string): IdentityNamespace {
80
+ return {
81
+ current: () => transport.get<IdentityClaims>("/identity/me"),
82
+ providers: {
83
+ list: (options) => {
84
+ const params = new URLSearchParams();
85
+ if (options?.limit !== undefined) {
86
+ if (!Number.isInteger(options.limit) || options.limit < 1) {
87
+ throw new RangeError("identity.providers.list: limit must be a positive integer");
88
+ }
89
+ params.set("limit", String(options.limit));
90
+ }
91
+ if (options?.cursor !== undefined && options.cursor !== "") params.set("cursor", options.cursor);
92
+ const qs = params.size > 0 ? `?${params.toString()}` : "";
93
+ return transport.get<IdentityProviderConfig[]>(`/@${encodeURIComponent(projectSlug)}/identity-providers${qs}`);
94
+ },
95
+ },
96
+ };
97
+ }