@ekanos/harness 0.1.5 → 0.2.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 (42) hide show
  1. package/README.md +175 -79
  2. package/dist/api.d.ts +42 -0
  3. package/dist/api.js +17 -0
  4. package/dist/internal/components/dev-toolbar.js +4 -2
  5. package/dist/internal/components/harness-providers.js +1 -0
  6. package/dist/internal/components/local-oauth-panel.d.ts +29 -0
  7. package/dist/internal/components/local-oauth-panel.js +355 -0
  8. package/dist/internal/lib/harness-fetch-interceptor.d.ts +33 -13
  9. package/dist/internal/lib/harness-fetch-interceptor.js +10 -0
  10. package/dist/internal/lib/oauth-setup-guide.d.ts +43 -0
  11. package/dist/internal/lib/oauth-setup-guide.js +28 -0
  12. package/dist/internal/lib/original-fetch.d.ts +36 -0
  13. package/dist/internal/lib/original-fetch.js +23 -0
  14. package/dist/internal/lib/run-activation-hook.d.ts +2 -8
  15. package/dist/internal/lib/toolbar-context.d.ts +7 -3
  16. package/dist/internal/lib/toolbar-context.js +10 -5
  17. package/dist/internal/lib/trigger-contract.d.ts +99 -0
  18. package/dist/internal/lib/trigger-contract.js +25 -0
  19. package/dist/internal/lib/trigger-runner.d.ts +55 -0
  20. package/dist/internal/lib/trigger-runner.js +153 -0
  21. package/dist/internal/routes/activation-page.js +42 -28
  22. package/dist/internal/routes/integration-layout.js +5 -1
  23. package/dist/internal/routes/triggers-page.js +121 -147
  24. package/dist/internal/server/api-router.d.ts +42 -0
  25. package/dist/internal/server/api-router.js +465 -0
  26. package/dist/internal/server/live-context.d.ts +93 -0
  27. package/dist/internal/server/live-context.js +93 -0
  28. package/dist/internal/server/local-secrets.d.ts +84 -0
  29. package/dist/internal/server/local-secrets.js +144 -0
  30. package/dist/internal/server/loopback-guard.d.ts +33 -0
  31. package/dist/internal/server/loopback-guard.js +38 -0
  32. package/dist/internal/server/nonce-store.d.ts +38 -0
  33. package/dist/internal/server/nonce-store.js +40 -0
  34. package/dist/internal/server/oauth-loop.d.ts +114 -0
  35. package/dist/internal/server/oauth-loop.js +141 -0
  36. package/dist/internal/server/project-root.d.ts +29 -0
  37. package/dist/internal/server/project-root.js +31 -0
  38. package/dist/internal/server/storage-read.d.ts +34 -0
  39. package/dist/internal/server/storage-read.js +53 -0
  40. package/dist/registry.d.ts +73 -1
  41. package/dist/registry.js +21 -1
  42. package/package.json +10 -3
@@ -1,18 +1,20 @@
1
1
  "use client";
2
2
  import { Fragment, jsx, jsxs } from "react/jsx-runtime";
3
- import { useState } from "react";
3
+ import { useMemo, useState } from "react";
4
4
  import { notFound } from "next/navigation";
5
5
  import { isEgressAllowed } from "@ekanos/sdk/context";
6
- import {
7
- invokeSchedule,
8
- invokeWebhook
9
- } from "@ekanos/sdk/testing";
10
6
  import { Alert, AlertDescription, AlertTitle } from "@ekanos/ui/alert";
11
7
  import { Badge } from "@ekanos/ui/badge";
12
8
  import { Button } from "@ekanos/ui/button";
13
9
  import { Textarea } from "@ekanos/ui/textarea";
10
+ import { LocalOAuthPanel } from "../components/local-oauth-panel.js";
14
11
  import { useDefinitionMockContext } from "../lib/definition-mock-context.js";
12
+ import { useHarnessDataMode } from "../lib/harness-hooks.js";
15
13
  import { useToolbar } from "../lib/toolbar-context.js";
14
+ import {
15
+ createLocalTriggerRunner,
16
+ createServerTriggerRunner
17
+ } from "../lib/trigger-runner.js";
16
18
  import { useHarnessIntegration } from "../registry-context.js";
17
19
  function OutcomePanel({ outcome }) {
18
20
  return /* @__PURE__ */ jsxs("div", { className: "flex flex-col gap-3", "data-test": "trigger-outcome", children: [
@@ -34,13 +36,9 @@ function OutcomePanel({ outcome }) {
34
36
  ] }, scope)) })
35
37
  ] });
36
38
  }
37
- function describeError(error) {
38
- return error instanceof Error ? error.message : String(error);
39
- }
40
39
  function WebhookCard({
41
- definition,
42
40
  webhook,
43
- ctx
41
+ runner
44
42
  }) {
45
43
  const [state, setState] = useState(() => ({
46
44
  payload: JSON.stringify(webhook.examplePayload ?? {}, null, 2),
@@ -49,29 +47,17 @@ function WebhookCard({
49
47
  }));
50
48
  const deliver = async () => {
51
49
  setState((s) => ({ ...s, busy: true }));
52
- const logsBefore = ctx.logs.length;
53
50
  let outcome;
54
51
  try {
55
52
  const payload = JSON.parse(state.payload);
56
- const { result } = await invokeWebhook(definition, webhook.id, payload, {
57
- context: ctx,
58
- headers: webhook.signature === "none" ? {} : { [webhook.signature.header]: "(unverified \u2014 local transport)" }
59
- });
60
- outcome = {
61
- ok: true,
62
- summary: result.status,
63
- ...result.detail ? { detail: result.detail } : {},
64
- logs: ctx.logs.slice(logsBefore),
65
- storage: ctx.dumpStorage()
66
- };
53
+ outcome = await runner.webhook(webhook.id, payload);
67
54
  } catch (error) {
68
- console.error("[harness] webhook invocation failed:", error);
69
55
  outcome = {
70
56
  ok: false,
71
57
  summary: "failed",
72
- detail: describeError(error),
73
- logs: ctx.logs.slice(logsBefore),
74
- storage: ctx.dumpStorage()
58
+ detail: error instanceof Error ? error.message : String(error),
59
+ logs: [],
60
+ storage: { account: {}, user: {} }
75
61
  };
76
62
  }
77
63
  setState((s) => ({ ...s, outcome, busy: false }));
@@ -127,36 +113,13 @@ function WebhookCard({
127
113
  );
128
114
  }
129
115
  function ScheduleCard({
130
- definition,
131
116
  schedule,
132
- ctx
117
+ runner
133
118
  }) {
134
119
  const [state, setState] = useState({ outcome: null, busy: false });
135
120
  const runNow = async () => {
136
121
  setState((s) => ({ ...s, busy: true }));
137
- const logsBefore = ctx.logs.length;
138
- let outcome;
139
- try {
140
- const { result } = await invokeSchedule(definition, schedule.id, {
141
- context: ctx
142
- });
143
- outcome = {
144
- ok: true,
145
- summary: result.status,
146
- ...result.detail ? { detail: result.detail } : {},
147
- logs: ctx.logs.slice(logsBefore),
148
- storage: ctx.dumpStorage()
149
- };
150
- } catch (error) {
151
- console.error("[harness] schedule invocation failed:", error);
152
- outcome = {
153
- ok: false,
154
- summary: "failed",
155
- detail: describeError(error),
156
- logs: ctx.logs.slice(logsBefore),
157
- storage: ctx.dumpStorage()
158
- };
159
- }
122
+ const outcome = await runner.schedule(schedule.id);
160
123
  setState({ outcome, busy: false });
161
124
  };
162
125
  return /* @__PURE__ */ jsxs(
@@ -193,7 +156,12 @@ function ScheduleCard({
193
156
  }
194
157
  );
195
158
  }
196
- function OAuthCard({ definition }) {
159
+ function OAuthCard({
160
+ integration,
161
+ definition,
162
+ mode
163
+ }) {
164
+ const { state } = useToolbar();
197
165
  const oauth = definition.oauth;
198
166
  if (!oauth) return null;
199
167
  const egress = definition.egress ?? [];
@@ -205,103 +173,103 @@ function OAuthCard({ definition }) {
205
173
  ["Client id secret", oauth.credentials.clientIdSecretName],
206
174
  ["Client secret secret", oauth.credentials.clientSecretSecretName]
207
175
  ];
208
- return /* @__PURE__ */ jsxs(
209
- "div",
210
- {
211
- className: "bg-card flex flex-col gap-5 rounded-lg border p-6",
212
- "data-test": "oauth-declaration",
213
- children: [
214
- /* @__PURE__ */ jsxs("div", { className: "flex flex-wrap items-center gap-3", children: [
215
- /* @__PURE__ */ jsx("h3", { className: "font-heading text-lg tracking-tight", children: "OAuth declaration" }),
216
- /* @__PURE__ */ jsx(Badge, { variant: "outline", children: "oauth" })
217
- ] }),
218
- /* @__PURE__ */ jsxs("dl", { className: "grid grid-cols-1 gap-x-6 gap-y-2 text-sm sm:grid-cols-[auto_1fr]", children: [
219
- rows.map(([label, value]) => /* @__PURE__ */ jsxs("div", { className: "contents", children: [
220
- /* @__PURE__ */ jsx("dt", { className: "text-muted-foreground", children: label }),
221
- /* @__PURE__ */ jsx("dd", { children: /* @__PURE__ */ jsx("code", { className: "break-all", children: value }) })
222
- ] }, label)),
223
- /* @__PURE__ */ jsxs("div", { className: "contents", children: [
224
- /* @__PURE__ */ jsx("dt", { className: "text-muted-foreground", children: "Egress coverage" }),
225
- /* @__PURE__ */ jsx("dd", { className: "flex gap-2", children: [
226
- ...new Map(
227
- [oauth.provider.authorizationUrl, oauth.provider.tokenUrl].map(
228
- (url) => [new URL(url).origin, url]
176
+ return /* @__PURE__ */ jsxs(Fragment, { children: [
177
+ /* @__PURE__ */ jsxs(
178
+ "div",
179
+ {
180
+ className: "bg-card flex flex-col gap-5 rounded-lg border p-6",
181
+ "data-test": "oauth-declaration",
182
+ children: [
183
+ /* @__PURE__ */ jsxs("div", { className: "flex flex-wrap items-center gap-3", children: [
184
+ /* @__PURE__ */ jsx("h3", { className: "font-heading text-lg tracking-tight", children: "OAuth declaration" }),
185
+ /* @__PURE__ */ jsx(Badge, { variant: "outline", children: "oauth" })
186
+ ] }),
187
+ /* @__PURE__ */ jsxs("dl", { className: "grid grid-cols-1 gap-x-6 gap-y-2 text-sm sm:grid-cols-[auto_1fr]", children: [
188
+ rows.map(([label, value]) => /* @__PURE__ */ jsxs("div", { className: "contents", children: [
189
+ /* @__PURE__ */ jsx("dt", { className: "text-muted-foreground", children: label }),
190
+ /* @__PURE__ */ jsx("dd", { children: /* @__PURE__ */ jsx("code", { className: "break-all", children: value }) })
191
+ ] }, label)),
192
+ /* @__PURE__ */ jsxs("div", { className: "contents", children: [
193
+ /* @__PURE__ */ jsx("dt", { className: "text-muted-foreground", children: "Egress coverage" }),
194
+ /* @__PURE__ */ jsx("dd", { className: "flex gap-2", children: [
195
+ ...new Map(
196
+ [
197
+ oauth.provider.authorizationUrl,
198
+ oauth.provider.tokenUrl
199
+ ].map((url) => [new URL(url).origin, url])
229
200
  )
230
- )
231
- ].map(([origin]) => {
232
- const covered = [
233
- oauth.provider.authorizationUrl,
234
- oauth.provider.tokenUrl
235
- ].filter((url) => new URL(url).origin === origin).every((url) => isEgressAllowed(url, egress));
236
- return /* @__PURE__ */ jsx(
237
- Badge,
238
- {
239
- variant: covered ? "secondary" : "destructive",
240
- children: origin
241
- },
242
- origin
243
- );
244
- }) })
245
- ] })
246
- ] }),
247
- /* @__PURE__ */ jsxs(Alert, { children: [
248
- /* @__PURE__ */ jsx(AlertTitle, { children: "Declaration only \u2014 the flow is the transport" }),
249
- /* @__PURE__ */ jsxs(AlertDescription, { children: [
250
- /* @__PURE__ */ jsxs("p", { children: [
251
- "The authorize \u2192 callback \u2192 code-exchange loop is owned by the transport, not by integration code: your package declares the endpoints and persists tokens in ",
252
- /* @__PURE__ */ jsx("code", { children: "onTokens" }),
253
- " via",
254
- " ",
255
- /* @__PURE__ */ jsx("code", { children: "ctx.secrets" }),
256
- ". This harness renders the declaration and checks its egress coverage; it does not run the flow."
257
- ] }),
258
- /* @__PURE__ */ jsxs("p", { children: [
259
- /* @__PURE__ */ jsx("strong", { children: "Redirect URI \u2014 host-derived, and not something you declare." }),
260
- " ",
261
- "The host owns the callback route and builds the URI from its own origin, so there is no field for it in",
262
- " ",
263
- /* @__PURE__ */ jsx("code", { children: "defineIntegration()" }),
264
- " and adding one would either be ignored or point the host's callback somewhere it should not go. Register this with your provider, against whichever host will run the flow:"
265
- ] }),
266
- /* @__PURE__ */ jsx("p", { children: /* @__PURE__ */ jsxs("code", { children: [
267
- "https://<your-fusion-host>/api/integrations/",
268
- definition.slug,
269
- "/oauth/callback"
270
- ] }) }),
271
- /* @__PURE__ */ jsxs("p", { children: [
272
- "The harness does not serve that route, so you cannot complete a round trip here. What you CAN check is above: that the endpoints you declared are inside your egress list. For a real round trip, run the hosted transport against a local Fusion host \u2014 register",
273
- " ",
274
- /* @__PURE__ */ jsxs("code", { children: [
275
- "http://localhost:3000/api/integrations/",
276
- definition.slug,
277
- "/oauth/callback"
201
+ ].map(([origin]) => {
202
+ const covered = [
203
+ oauth.provider.authorizationUrl,
204
+ oauth.provider.tokenUrl
205
+ ].filter((url) => new URL(url).origin === origin).every((url) => isEgressAllowed(url, egress));
206
+ return /* @__PURE__ */ jsx(
207
+ Badge,
208
+ {
209
+ variant: covered ? "secondary" : "destructive",
210
+ children: origin
211
+ },
212
+ origin
213
+ );
214
+ }) })
215
+ ] })
216
+ ] }),
217
+ /* @__PURE__ */ jsxs(Alert, { children: [
218
+ /* @__PURE__ */ jsx(AlertTitle, { children: "The flow is the transport's \u2014 and the harness has one" }),
219
+ /* @__PURE__ */ jsxs(AlertDescription, { children: [
220
+ /* @__PURE__ */ jsxs("p", { children: [
221
+ "The authorize \u2192 callback \u2192 code-exchange loop is owned by the transport, not by integration code: your package declares the endpoints and persists tokens in ",
222
+ /* @__PURE__ */ jsx("code", { children: "onTokens" }),
223
+ " via",
224
+ " ",
225
+ /* @__PURE__ */ jsx("code", { children: "ctx.secrets" }),
226
+ ". The hosted transport runs it in Fusion; in live mode the generated shell runs the same loop here, on localhost, against your own developer app \u2014 see Local OAuth below."
278
227
  ] }),
279
- " ",
280
- "with your provider and click Connect from the marketplace; the host exchanges the code through your declared egress and calls",
281
- " ",
282
- /* @__PURE__ */ jsx("code", { children: "onTokens" }),
283
- ". For unit coverage, call ",
284
- /* @__PURE__ */ jsx("code", { children: "onTokens" }),
285
- " ",
286
- "directly with ",
287
- /* @__PURE__ */ jsx("code", { children: "createMockContext()" }),
288
- " \u2014 it is an ordinary async function."
228
+ /* @__PURE__ */ jsxs("p", { children: [
229
+ /* @__PURE__ */ jsx("strong", { children: "Redirect URI \u2014 host-derived, and not something you declare." }),
230
+ " ",
231
+ "Whichever host runs the flow builds it from its own origin, so there is no field for it in ",
232
+ /* @__PURE__ */ jsx("code", { children: "defineIntegration()" }),
233
+ ". You register one per environment with your provider: the harness's (below, in live mode) and the Fusion host's,",
234
+ " ",
235
+ /* @__PURE__ */ jsxs("code", { children: [
236
+ "https://<your-fusion-host>/api/integrations/",
237
+ definition.slug,
238
+ "/oauth/callback"
239
+ ] }),
240
+ "."
241
+ ] })
289
242
  ] })
290
243
  ] })
291
- ] })
292
- ]
293
- }
294
- );
244
+ ]
245
+ }
246
+ ),
247
+ /* @__PURE__ */ jsx(
248
+ LocalOAuthPanel,
249
+ {
250
+ integration,
251
+ definition,
252
+ mode,
253
+ variant: state.variant
254
+ }
255
+ )
256
+ ] });
295
257
  }
296
258
  function TriggersPage() {
297
259
  const integration = useHarnessIntegration();
298
260
  const { state } = useToolbar();
261
+ const mode = useHarnessDataMode();
299
262
  const ctx = useDefinitionMockContext(
300
263
  integration ?? { slug: "", name: "", description: "", widgets: [] },
301
264
  state.variant
302
265
  );
266
+ const definition = integration?.definition;
267
+ const runner = useMemo(() => {
268
+ if (!integration || !definition) return null;
269
+ if (mode === "live") return createServerTriggerRunner(integration.slug);
270
+ return ctx ? createLocalTriggerRunner(definition, ctx) : null;
271
+ }, [integration, definition, mode, ctx]);
303
272
  if (!integration) notFound();
304
- const definition = integration.definition;
305
273
  const webhooks = definition?.webhooks ?? [];
306
274
  const schedules = definition?.schedules ?? [];
307
275
  const declaresAnything = webhooks.length > 0 || schedules.length > 0 || Boolean(definition?.oauth);
@@ -315,15 +283,16 @@ function TriggersPage() {
315
283
  /* @__PURE__ */ jsx(AlertTitle, { children: "The local transport for declared event surfaces" }),
316
284
  /* @__PURE__ */ jsxs(AlertDescription, { children: [
317
285
  /* @__PURE__ */ jsxs("p", { children: [
318
- "Webhooks and schedules below run their REAL handlers against one in-memory mock context (state accumulates until you leave the page). Payloads are validated against each webhook's",
319
- " ",
286
+ "Webhooks and schedules below run their REAL handlers against one context whose state accumulates like a real account's. Payloads are validated against each webhook's ",
320
287
  /* @__PURE__ */ jsx("code", { children: "payloadSchema" }),
321
288
  ", signature checks are logged as skipped, and egress is enforced from the definition \u2014 the same declarations the host's ingress, scheduler, and hosted OAuth callback bind to later."
322
289
  ] }),
290
+ /* @__PURE__ */ jsx("p", { "data-test": "triggers-mode-notice", children: mode === "live" ? "Live API: handlers run on the dev server, against the context the OAuth loop stored tokens in, with ctx.fetch reaching your vendor under the declared egress." : "Fixtures: handlers run in this browser against an in-memory context seeded from triggerMocks; ctx.fetch answers from your fixtures and never touches the network." }),
323
291
  /* @__PURE__ */ jsxs("p", { children: [
324
- "This is fixtures every time, whatever the toolbar says \u2014 nothing below reaches a real system until you publish to the dev host. A widget on this integration is different: it already reaches real vendors through ",
292
+ "Widgets on this integration reach real vendors through",
293
+ " ",
325
294
  /* @__PURE__ */ jsx("code", { children: "useIntegrationFetch()" }),
326
- " once you flip the toolbar to Live API."
295
+ " in Live API too \u2014 browser-side, with the egress check as a convenience rather than a guarantee. The host runs these same declarations, with real enforcement, after you publish."
327
296
  ] })
328
297
  ] })
329
298
  ] }),
@@ -340,25 +309,30 @@ function TriggersPage() {
340
309
  /* @__PURE__ */ jsx("code", { children: "@ekanos/sdk" }),
341
310
  " README has a worked example of each, under \u201CDeclarable surfaces\u201D."
342
311
  ] }) : /* @__PURE__ */ jsxs(Fragment, { children: [
343
- ctx ? webhooks.map((webhook) => /* @__PURE__ */ jsx(
312
+ runner ? webhooks.map((webhook) => /* @__PURE__ */ jsx(
344
313
  WebhookCard,
345
314
  {
346
- definition,
347
315
  webhook,
348
- ctx
316
+ runner
349
317
  },
350
318
  webhook.id
351
319
  )) : null,
352
- ctx ? schedules.map((schedule) => /* @__PURE__ */ jsx(
320
+ runner ? schedules.map((schedule) => /* @__PURE__ */ jsx(
353
321
  ScheduleCard,
354
322
  {
355
- definition,
356
323
  schedule,
357
- ctx
324
+ runner
358
325
  },
359
326
  schedule.id
360
327
  )) : null,
361
- /* @__PURE__ */ jsx(OAuthCard, { definition })
328
+ /* @__PURE__ */ jsx(
329
+ OAuthCard,
330
+ {
331
+ integration,
332
+ definition,
333
+ mode
334
+ }
335
+ )
362
336
  ] })
363
337
  ]
364
338
  }
@@ -0,0 +1,42 @@
1
+ import { type HarnessIntegration } from '../../registry.js';
2
+ /**
3
+ * ─────────────────────────────────────────────────────────────────────────────
4
+ * THE HARNESS API — `/api/integrations/[slug]/…`, served by the shell
5
+ * ─────────────────────────────────────────────────────────────────────────────
6
+ *
7
+ * Six routes per registered integration, behind one catch-all the CLI
8
+ * scaffolds (`app/api/integrations/[slug]/[...path]/route.ts`):
9
+ *
10
+ * GET oauth/connect start the real authorize → callback → exchange loop
11
+ * GET oauth/callback the provider redirects here; runs `onTokens`
12
+ * GET oauth/status the `ConnectionCheckResult` the activation form polls
13
+ * GET storage the SDK's generic storage bridge, over the live ctx
14
+ * POST trigger run a webhook / schedule / onActivate on the live ctx
15
+ * GET local-setup what to fill in and what to register — never values
16
+ *
17
+ * Contracts mirror the Fusion host's own partner routes — the hosted OAuth
18
+ * transport and the generic storage route — so the SDK's client
19
+ * helpers (`createPartnerConnectionCheck`, `fetchIntegrationStorage`,
20
+ * `partnerOAuthErrorParam`) work against either unchanged. Where the harness
21
+ * deliberately differs:
22
+ *
23
+ * - no session, no membership: there is one user, on one machine. The host's
24
+ * `unauthorized` code is therefore never produced here;
25
+ * - the nonce lives in memory (`nonce-store.ts`) rather than an OTP row;
26
+ * - the connection fact is a field on the live state, not a table;
27
+ * - credentials come from `.ekanos/local-secrets.json`, not the catalog.
28
+ *
29
+ * Every handler is `(Request) => Response` over Web standard types, so the
30
+ * whole router runs under vitest with `new Request(...)` and no Next.
31
+ */
32
+ export interface HarnessApiDeps {
33
+ env: Readonly<Record<string, string | undefined>>;
34
+ cwd: string;
35
+ now: () => Date;
36
+ }
37
+ export interface HarnessRouteParams {
38
+ slug: string;
39
+ path: string[];
40
+ }
41
+ export type HarnessApiRouter = (request: Request, params: HarnessRouteParams) => Promise<Response>;
42
+ export declare function createHarnessApiRouter(registry: readonly HarnessIntegration[], deps?: Partial<HarnessApiDeps>): HarnessApiRouter;