@ekanos/harness 0.1.5 → 0.3.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 +243 -79
- package/dist/api.d.ts +42 -0
- package/dist/api.js +17 -0
- package/dist/internal/components/dev-toolbar.js +4 -2
- package/dist/internal/components/harness-providers.d.ts +8 -2
- package/dist/internal/components/harness-providers.js +4 -1
- package/dist/internal/components/local-oauth-panel.d.ts +29 -0
- package/dist/internal/components/local-oauth-panel.js +355 -0
- package/dist/internal/lib/actions-transport.d.ts +30 -0
- package/dist/internal/lib/actions-transport.js +6 -0
- package/dist/internal/lib/harness-fetch-interceptor.d.ts +53 -14
- package/dist/internal/lib/harness-fetch-interceptor.js +96 -0
- package/dist/internal/lib/oauth-setup-guide.d.ts +43 -0
- package/dist/internal/lib/oauth-setup-guide.js +28 -0
- package/dist/internal/lib/original-fetch.d.ts +36 -0
- package/dist/internal/lib/original-fetch.js +23 -0
- package/dist/internal/lib/run-activation-hook.d.ts +2 -8
- package/dist/internal/lib/toolbar-context.d.ts +7 -3
- package/dist/internal/lib/toolbar-context.js +10 -5
- package/dist/internal/lib/trigger-contract.d.ts +99 -0
- package/dist/internal/lib/trigger-contract.js +25 -0
- package/dist/internal/lib/trigger-runner.d.ts +55 -0
- package/dist/internal/lib/trigger-runner.js +153 -0
- package/dist/internal/routes/activation-page.js +42 -28
- package/dist/internal/routes/integration-layout.js +6 -1
- package/dist/internal/routes/triggers-page.js +121 -147
- package/dist/internal/server/actions-fixtures-context.d.ts +57 -0
- package/dist/internal/server/actions-fixtures-context.js +52 -0
- package/dist/internal/server/api-router.d.ts +54 -0
- package/dist/internal/server/api-router.js +575 -0
- package/dist/internal/server/live-context.d.ts +93 -0
- package/dist/internal/server/live-context.js +93 -0
- package/dist/internal/server/local-secrets.d.ts +84 -0
- package/dist/internal/server/local-secrets.js +144 -0
- package/dist/internal/server/loopback-guard.d.ts +33 -0
- package/dist/internal/server/loopback-guard.js +38 -0
- package/dist/internal/server/nonce-store.d.ts +38 -0
- package/dist/internal/server/nonce-store.js +40 -0
- package/dist/internal/server/oauth-loop.d.ts +114 -0
- package/dist/internal/server/oauth-loop.js +141 -0
- package/dist/internal/server/project-root.d.ts +29 -0
- package/dist/internal/server/project-root.js +31 -0
- package/dist/internal/server/storage-read.d.ts +34 -0
- package/dist/internal/server/storage-read.js +53 -0
- package/dist/registry.d.ts +73 -1
- package/dist/registry.js +21 -1
- package/package.json +13 -7
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
import {
|
|
2
|
+
createMockContext
|
|
3
|
+
} from "@ekanos/sdk/testing";
|
|
4
|
+
import {
|
|
5
|
+
HARNESS_ACCOUNT_ID,
|
|
6
|
+
resolveEgress
|
|
7
|
+
} from "../../registry.js";
|
|
8
|
+
import { compileFixtures, fixturesToMockHandlers } from "../lib/http-fixtures.js";
|
|
9
|
+
const STORE = /* @__PURE__ */ Symbol.for("ekanos.harness.fixtures-actions-state");
|
|
10
|
+
function getStore() {
|
|
11
|
+
const carrier = globalThis;
|
|
12
|
+
carrier[STORE] ??= /* @__PURE__ */ new Map();
|
|
13
|
+
return carrier[STORE];
|
|
14
|
+
}
|
|
15
|
+
function resetFixturesActionsStore() {
|
|
16
|
+
getStore().clear();
|
|
17
|
+
}
|
|
18
|
+
function getFixturesActionsState(input) {
|
|
19
|
+
const key = `${input.integration.slug}:${input.variant}`;
|
|
20
|
+
const store = getStore();
|
|
21
|
+
const existing = store.get(key);
|
|
22
|
+
if (existing) return existing;
|
|
23
|
+
const definition = input.definition;
|
|
24
|
+
const mocks = input.integration.triggerMocks ?? {};
|
|
25
|
+
const egress = resolveEgress(input.integration);
|
|
26
|
+
const declaredFixtures = input.integration.fixtures?.[input.variant] ?? [];
|
|
27
|
+
const ctx = createMockContext({
|
|
28
|
+
accountId: HARNESS_ACCOUNT_ID,
|
|
29
|
+
integration: { slug: definition.slug },
|
|
30
|
+
...definition.storage ? { storageSchemas: definition.storage } : {},
|
|
31
|
+
egress: definition.egress ?? [],
|
|
32
|
+
...mocks.storage ? {
|
|
33
|
+
storage: mocks.storage
|
|
34
|
+
} : {},
|
|
35
|
+
...mocks.secrets ? { secrets: mocks.secrets } : {},
|
|
36
|
+
fetchHandlers: [
|
|
37
|
+
...mocks.fetchHandlers ?? [],
|
|
38
|
+
// No selfOrigin: an action handler's `ctx.fetch` calls the partner's
|
|
39
|
+
// OWN vendor, never the harness's own `/api/…` namespace, so the
|
|
40
|
+
// `/api/` host-route fixture shape (the only one that needs an
|
|
41
|
+
// origin to resolve against) never applies here.
|
|
42
|
+
...fixturesToMockHandlers(compileFixtures(declaredFixtures, egress))
|
|
43
|
+
]
|
|
44
|
+
});
|
|
45
|
+
const state = { key, ctx };
|
|
46
|
+
store.set(key, state);
|
|
47
|
+
return state;
|
|
48
|
+
}
|
|
49
|
+
export {
|
|
50
|
+
getFixturesActionsState,
|
|
51
|
+
resetFixturesActionsStore
|
|
52
|
+
};
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import { type HarnessIntegration } from '../../registry.js';
|
|
2
|
+
/**
|
|
3
|
+
* ─────────────────────────────────────────────────────────────────────────────
|
|
4
|
+
* THE HARNESS API — `/api/integrations/[slug]/…`, served by the shell
|
|
5
|
+
* ─────────────────────────────────────────────────────────────────────────────
|
|
6
|
+
*
|
|
7
|
+
* Seven 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
|
+
* POST actions/:name run a declared `actions[name]` handler — see below
|
|
17
|
+
*
|
|
18
|
+
* `actions/:name` is the one route reached in BOTH fixtures and live mode
|
|
19
|
+
* (every other route only exists for live — fixtures-mode triggers run
|
|
20
|
+
* entirely in the browser). `useIntegrationAction` always makes a real
|
|
21
|
+
* `fetch()` (the widget-actions design), so
|
|
22
|
+
* `harness-fetch-interceptor.ts` lets it through unconditionally and tags
|
|
23
|
+
* the request with the active mode/variant via two harness-only headers
|
|
24
|
+
* (`internal/lib/actions-transport.ts`) — this router reads them to decide
|
|
25
|
+
* whether to run the handler against the live ctx (`getLiveState`, same as
|
|
26
|
+
* `trigger`) or a dedicated per-variant fixtures ctx
|
|
27
|
+
* (`getFixturesActionsState`, network-free).
|
|
28
|
+
*
|
|
29
|
+
* Contracts mirror the Fusion host's own partner routes — the hosted OAuth
|
|
30
|
+
* transport and the generic storage route — so the SDK's client
|
|
31
|
+
* helpers (`createPartnerConnectionCheck`, `fetchIntegrationStorage`,
|
|
32
|
+
* `partnerOAuthErrorParam`) work against either unchanged. Where the harness
|
|
33
|
+
* deliberately differs:
|
|
34
|
+
*
|
|
35
|
+
* - no session, no membership: there is one user, on one machine. The host's
|
|
36
|
+
* `unauthorized` code is therefore never produced here;
|
|
37
|
+
* - the nonce lives in memory (`nonce-store.ts`) rather than an OTP row;
|
|
38
|
+
* - the connection fact is a field on the live state, not a table;
|
|
39
|
+
* - credentials come from `.ekanos/local-secrets.json`, not the catalog.
|
|
40
|
+
*
|
|
41
|
+
* Every handler is `(Request) => Response` over Web standard types, so the
|
|
42
|
+
* whole router runs under vitest with `new Request(...)` and no Next.
|
|
43
|
+
*/
|
|
44
|
+
export interface HarnessApiDeps {
|
|
45
|
+
env: Readonly<Record<string, string | undefined>>;
|
|
46
|
+
cwd: string;
|
|
47
|
+
now: () => Date;
|
|
48
|
+
}
|
|
49
|
+
export interface HarnessRouteParams {
|
|
50
|
+
slug: string;
|
|
51
|
+
path: string[];
|
|
52
|
+
}
|
|
53
|
+
export type HarnessApiRouter = (request: Request, params: HarnessRouteParams) => Promise<Response>;
|
|
54
|
+
export declare function createHarnessApiRouter(registry: readonly HarnessIntegration[], deps?: Partial<HarnessApiDeps>): HarnessApiRouter;
|
|
@@ -0,0 +1,575 @@
|
|
|
1
|
+
import { invokeSchedule, invokeWebhook } from "@ekanos/sdk/testing";
|
|
2
|
+
import {
|
|
3
|
+
DATA_MODES,
|
|
4
|
+
FIXTURE_VARIANTS,
|
|
5
|
+
findIntegration
|
|
6
|
+
} from "../../registry.js";
|
|
7
|
+
import {
|
|
8
|
+
HARNESS_ACTIONS_MODE_HEADER,
|
|
9
|
+
HARNESS_ACTIONS_VARIANT_HEADER
|
|
10
|
+
} from "../lib/actions-transport.js";
|
|
11
|
+
import { runOnActivateHook } from "../lib/run-activation-hook.js";
|
|
12
|
+
import {
|
|
13
|
+
isLocalSetupWriteRequest,
|
|
14
|
+
isTriggerRequest
|
|
15
|
+
} from "../lib/trigger-contract.js";
|
|
16
|
+
import { getFixturesActionsState } from "./actions-fixtures-context.js";
|
|
17
|
+
import {
|
|
18
|
+
WARMUP_BUDGET_MS,
|
|
19
|
+
getLiveState,
|
|
20
|
+
startWarmup
|
|
21
|
+
} from "./live-context.js";
|
|
22
|
+
import {
|
|
23
|
+
LOCAL_SECRETS_RELATIVE_PATH,
|
|
24
|
+
declaredSecretNames,
|
|
25
|
+
readLocalSecrets,
|
|
26
|
+
writeLocalSecrets
|
|
27
|
+
} from "./local-secrets.js";
|
|
28
|
+
import { loopbackRefusal } from "./loopback-guard.js";
|
|
29
|
+
import {
|
|
30
|
+
buildAuthorizeUrl,
|
|
31
|
+
callbackUrl,
|
|
32
|
+
errorRedirectUrl,
|
|
33
|
+
exchangeAuthorizationCode,
|
|
34
|
+
generateCodeChallenge,
|
|
35
|
+
generateCodeVerifier,
|
|
36
|
+
safeReturnPath,
|
|
37
|
+
successRedirectUrl
|
|
38
|
+
} from "./oauth-loop.js";
|
|
39
|
+
import { resolveProjectRoot } from "./project-root.js";
|
|
40
|
+
import { parseStorageQuery, readClientReadableStorage } from "./storage-read.js";
|
|
41
|
+
function json(body, init = {}) {
|
|
42
|
+
return new Response(JSON.stringify(body), {
|
|
43
|
+
...init,
|
|
44
|
+
headers: {
|
|
45
|
+
"content-type": "application/json",
|
|
46
|
+
"cache-control": "private, no-store",
|
|
47
|
+
...init.headers ?? {}
|
|
48
|
+
}
|
|
49
|
+
});
|
|
50
|
+
}
|
|
51
|
+
function redirect(target) {
|
|
52
|
+
return new Response(null, {
|
|
53
|
+
status: 302,
|
|
54
|
+
headers: { location: String(target), "cache-control": "no-store" }
|
|
55
|
+
});
|
|
56
|
+
}
|
|
57
|
+
function defaultReturnPath(slug) {
|
|
58
|
+
return `/${slug}/activation`;
|
|
59
|
+
}
|
|
60
|
+
const UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
61
|
+
const ROUTES = {
|
|
62
|
+
"oauth/connect": { methods: ["GET"], handle: oauthConnect },
|
|
63
|
+
"oauth/callback": { methods: ["GET"], handle: oauthCallback },
|
|
64
|
+
"oauth/status": { methods: ["GET"], handle: oauthStatus },
|
|
65
|
+
storage: { methods: ["GET"], handle: storage },
|
|
66
|
+
trigger: { methods: ["POST"], handle: trigger },
|
|
67
|
+
"local-setup": { methods: ["GET", "PUT"], handle: localSetup }
|
|
68
|
+
};
|
|
69
|
+
function createHarnessApiRouter(registry, deps = {}) {
|
|
70
|
+
const env = deps.env ?? process.env;
|
|
71
|
+
const cwd = deps.cwd ?? process.cwd();
|
|
72
|
+
const now = deps.now ?? (() => /* @__PURE__ */ new Date());
|
|
73
|
+
return async (request, params) => {
|
|
74
|
+
const refusal = loopbackRefusal(request, env);
|
|
75
|
+
if (refusal) return refusal;
|
|
76
|
+
const routeKey = params.path.join("/");
|
|
77
|
+
const actionName = params.path.length === 2 && params.path[0] === "actions" ? params.path[1] : void 0;
|
|
78
|
+
const route = actionName !== void 0 ? { methods: ["POST"], handle: (ctx) => actionInvoke(ctx, actionName) } : ROUTES[routeKey];
|
|
79
|
+
if (!route) {
|
|
80
|
+
if (routeKey === "connect") {
|
|
81
|
+
return json(
|
|
82
|
+
{
|
|
83
|
+
error: "not_found",
|
|
84
|
+
message: `The harness serves /api/integrations/${params.slug}/oauth/connect, not /connect. Your OAuthActivationForm is using the SDK's default \`connectPath\`, which points at a first-party route the host would not serve for a partner either.`,
|
|
85
|
+
hint: "Pass `connectPath: partnerOAuthConnectPath(slug)` from `@ekanos/sdk/hooks` in the form config."
|
|
86
|
+
},
|
|
87
|
+
{ status: 404 }
|
|
88
|
+
);
|
|
89
|
+
}
|
|
90
|
+
return json(
|
|
91
|
+
{
|
|
92
|
+
error: "not_found",
|
|
93
|
+
message: `No harness API route at /api/integrations/${params.slug}/${routeKey}.`,
|
|
94
|
+
routes: [...Object.keys(ROUTES), "actions/:actionName"]
|
|
95
|
+
},
|
|
96
|
+
{ status: 404 }
|
|
97
|
+
);
|
|
98
|
+
}
|
|
99
|
+
if (!route.methods.includes(request.method.toUpperCase())) {
|
|
100
|
+
return json(
|
|
101
|
+
{ error: "method_not_allowed", allowed: route.methods },
|
|
102
|
+
{ status: 405, headers: { allow: route.methods.join(", ") } }
|
|
103
|
+
);
|
|
104
|
+
}
|
|
105
|
+
const integration = findIntegration([...registry], params.slug);
|
|
106
|
+
if (!integration) {
|
|
107
|
+
return json(
|
|
108
|
+
{
|
|
109
|
+
error: "unknown_integration",
|
|
110
|
+
message: `"${params.slug}" is not registered in your harness config.`,
|
|
111
|
+
registered: registry.map((entry) => entry.slug)
|
|
112
|
+
},
|
|
113
|
+
{ status: 404 }
|
|
114
|
+
);
|
|
115
|
+
}
|
|
116
|
+
const definition = integration.definition;
|
|
117
|
+
if (!definition) {
|
|
118
|
+
return json(
|
|
119
|
+
{
|
|
120
|
+
error: "no_definition",
|
|
121
|
+
message: `The harness entry for "${params.slug}" does not link its defineIntegration() output, so there is nothing to run.`,
|
|
122
|
+
hint: "Add `definition: asHarnessDefinition(integration)` to the entry in your harness config."
|
|
123
|
+
},
|
|
124
|
+
{ status: 404 }
|
|
125
|
+
);
|
|
126
|
+
}
|
|
127
|
+
const root = resolveProjectRoot({ env, cwd });
|
|
128
|
+
if (!root.ok) {
|
|
129
|
+
return json(
|
|
130
|
+
{
|
|
131
|
+
error: "project_root_unresolved",
|
|
132
|
+
message: root.message,
|
|
133
|
+
hint: root.hint
|
|
134
|
+
},
|
|
135
|
+
{ status: 500 }
|
|
136
|
+
);
|
|
137
|
+
}
|
|
138
|
+
const secrets = readLocalSecrets({
|
|
139
|
+
projectRoot: root.root,
|
|
140
|
+
slug: params.slug,
|
|
141
|
+
names: declaredSecretNames(definition)
|
|
142
|
+
});
|
|
143
|
+
if (!secrets.ok) {
|
|
144
|
+
return json(
|
|
145
|
+
{ error: "local_secrets_unreadable", message: secrets.message },
|
|
146
|
+
{ status: 500 }
|
|
147
|
+
);
|
|
148
|
+
}
|
|
149
|
+
if (secrets.generated) {
|
|
150
|
+
console.info(
|
|
151
|
+
`[harness:${params.slug}] wrote ${secrets.file} \u2014 fill in the values under "` + params.slug + '" to run the OAuth loop locally.'
|
|
152
|
+
);
|
|
153
|
+
}
|
|
154
|
+
const state = getLiveState({
|
|
155
|
+
integration,
|
|
156
|
+
definition,
|
|
157
|
+
adminSecrets: secrets.values,
|
|
158
|
+
secretsFingerprint: secrets.fingerprint
|
|
159
|
+
});
|
|
160
|
+
const url = new URL(request.url);
|
|
161
|
+
return route.handle({
|
|
162
|
+
request,
|
|
163
|
+
url,
|
|
164
|
+
origin: url.origin,
|
|
165
|
+
slug: params.slug,
|
|
166
|
+
integration,
|
|
167
|
+
definition,
|
|
168
|
+
projectRoot: root.root,
|
|
169
|
+
secrets,
|
|
170
|
+
state,
|
|
171
|
+
now
|
|
172
|
+
});
|
|
173
|
+
};
|
|
174
|
+
}
|
|
175
|
+
function notDeclared() {
|
|
176
|
+
return json(
|
|
177
|
+
{ success: false, error: "This integration declares no OAuth surface" },
|
|
178
|
+
{ status: 404 }
|
|
179
|
+
);
|
|
180
|
+
}
|
|
181
|
+
function oauthError(ctx, returnPath, code) {
|
|
182
|
+
return redirect(
|
|
183
|
+
errorRedirectUrl({
|
|
184
|
+
origin: ctx.origin,
|
|
185
|
+
returnPath,
|
|
186
|
+
integrationSlug: ctx.slug,
|
|
187
|
+
code
|
|
188
|
+
})
|
|
189
|
+
);
|
|
190
|
+
}
|
|
191
|
+
function clientCredentials(ctx) {
|
|
192
|
+
const oauth = ctx.definition.oauth;
|
|
193
|
+
if (!oauth) return null;
|
|
194
|
+
const clientId = ctx.secrets.values[oauth.credentials.clientIdSecretName];
|
|
195
|
+
const clientSecret = ctx.secrets.values[oauth.credentials.clientSecretSecretName];
|
|
196
|
+
return clientId && clientSecret ? { clientId, clientSecret } : null;
|
|
197
|
+
}
|
|
198
|
+
function oauthConnect(ctx) {
|
|
199
|
+
const oauth = ctx.definition.oauth;
|
|
200
|
+
if (!oauth) return notDeclared();
|
|
201
|
+
const returnPath = safeReturnPath(
|
|
202
|
+
ctx.url.searchParams.get("returnPath"),
|
|
203
|
+
defaultReturnPath(ctx.slug)
|
|
204
|
+
);
|
|
205
|
+
const credentials = clientCredentials(ctx);
|
|
206
|
+
if (!credentials) {
|
|
207
|
+
console.error(
|
|
208
|
+
`[harness:${ctx.slug}] oauth/connect: client credentials missing in ${ctx.secrets.file} (${ctx.secrets.missing.join(", ")}).`
|
|
209
|
+
);
|
|
210
|
+
return oauthError(ctx, returnPath, "not_configured");
|
|
211
|
+
}
|
|
212
|
+
const codeVerifier = oauth.provider.pkce ? generateCodeVerifier() : void 0;
|
|
213
|
+
const nonce = ctx.state.nonces.issue({
|
|
214
|
+
returnPath,
|
|
215
|
+
...codeVerifier ? { codeVerifier } : {}
|
|
216
|
+
});
|
|
217
|
+
return redirect(
|
|
218
|
+
buildAuthorizeUrl({
|
|
219
|
+
provider: oauth.provider,
|
|
220
|
+
clientId: credentials.clientId,
|
|
221
|
+
redirectUri: callbackUrl(ctx.origin, ctx.slug),
|
|
222
|
+
state: nonce,
|
|
223
|
+
...codeVerifier ? { codeChallenge: generateCodeChallenge(codeVerifier) } : {}
|
|
224
|
+
})
|
|
225
|
+
);
|
|
226
|
+
}
|
|
227
|
+
async function oauthCallback(ctx) {
|
|
228
|
+
const oauth = ctx.definition.oauth;
|
|
229
|
+
if (!oauth) return notDeclared();
|
|
230
|
+
const params = ctx.url.searchParams;
|
|
231
|
+
const stateParam = params.get("state");
|
|
232
|
+
const consumed = stateParam ? ctx.state.nonces.consume(stateParam) : { status: "unknown" };
|
|
233
|
+
const returnPath = consumed.status === "unknown" ? defaultReturnPath(ctx.slug) : consumed.entry.returnPath;
|
|
234
|
+
if (params.get("error")) {
|
|
235
|
+
return oauthError(ctx, returnPath, "denied");
|
|
236
|
+
}
|
|
237
|
+
if (consumed.status === "unknown")
|
|
238
|
+
return oauthError(ctx, returnPath, "invalid");
|
|
239
|
+
if (consumed.status === "expired")
|
|
240
|
+
return oauthError(ctx, returnPath, "expired");
|
|
241
|
+
const code = params.get("code");
|
|
242
|
+
if (!code) return oauthError(ctx, returnPath, "invalid");
|
|
243
|
+
const credentials = clientCredentials(ctx);
|
|
244
|
+
if (!credentials) return oauthError(ctx, returnPath, "not_configured");
|
|
245
|
+
const exchange = await exchangeAuthorizationCode({
|
|
246
|
+
ctx: ctx.state.ctx,
|
|
247
|
+
provider: oauth.provider,
|
|
248
|
+
...credentials,
|
|
249
|
+
code,
|
|
250
|
+
redirectUri: callbackUrl(ctx.origin, ctx.slug),
|
|
251
|
+
...consumed.entry.codeVerifier ? { codeVerifier: consumed.entry.codeVerifier } : {},
|
|
252
|
+
now: ctx.now
|
|
253
|
+
});
|
|
254
|
+
if (!exchange.ok) {
|
|
255
|
+
console.error(
|
|
256
|
+
`[harness:${ctx.slug}] oauth/callback: code exchange failed (${exchange.reason}${exchange.reason === "http_error" ? ` ${exchange.status}` : ""}${exchange.reason === "fetch_failed" ? `: ${exchange.message}` : ""}).`
|
|
257
|
+
);
|
|
258
|
+
return oauthError(ctx, returnPath, "exchange_failed");
|
|
259
|
+
}
|
|
260
|
+
try {
|
|
261
|
+
await oauth.onTokens(ctx.state.ctx, exchange.tokens);
|
|
262
|
+
} catch (error) {
|
|
263
|
+
console.error(
|
|
264
|
+
`[harness:${ctx.slug}] oauth/callback: onTokens threw`,
|
|
265
|
+
error
|
|
266
|
+
);
|
|
267
|
+
return oauthError(ctx, returnPath, "save_failed");
|
|
268
|
+
}
|
|
269
|
+
ctx.state.connection = {
|
|
270
|
+
obtainedAt: ctx.now().toISOString(),
|
|
271
|
+
expiresAt: exchange.tokens.expiresAt ?? null,
|
|
272
|
+
scope: exchange.tokens.scope ?? null
|
|
273
|
+
};
|
|
274
|
+
return redirect(successRedirectUrl({ origin: ctx.origin, returnPath }));
|
|
275
|
+
}
|
|
276
|
+
function oauthStatus(ctx) {
|
|
277
|
+
if (!ctx.definition.oauth) return notDeclared();
|
|
278
|
+
const accountId = ctx.url.searchParams.get("accountId");
|
|
279
|
+
if (!accountId || !UUID_PATTERN.test(accountId)) {
|
|
280
|
+
return json(
|
|
281
|
+
{ success: false, error: "accountId must be a UUID" },
|
|
282
|
+
{ status: 400 }
|
|
283
|
+
);
|
|
284
|
+
}
|
|
285
|
+
const connection = ctx.state.connection;
|
|
286
|
+
return connection ? json({ success: true, data: { obtainedAt: connection.obtainedAt } }) : json({ success: false, error: "Not connected" });
|
|
287
|
+
}
|
|
288
|
+
async function storage(ctx) {
|
|
289
|
+
const query = parseStorageQuery(ctx.url);
|
|
290
|
+
if (!query.ok) return json({ error: query.error }, { status: 400 });
|
|
291
|
+
const read = () => readClientReadableStorage({
|
|
292
|
+
ctx: ctx.state.ctx,
|
|
293
|
+
definition: ctx.definition,
|
|
294
|
+
keys: query.keys
|
|
295
|
+
});
|
|
296
|
+
const first = await read();
|
|
297
|
+
if (Object.keys(first).length > 0) return json(first);
|
|
298
|
+
const warmup = startWarmup(ctx.state, ctx.definition);
|
|
299
|
+
if (!warmup) return json(first);
|
|
300
|
+
const budgetExceeded = /* @__PURE__ */ Symbol("warmup-budget-exceeded");
|
|
301
|
+
const outcome = await Promise.race([
|
|
302
|
+
warmup,
|
|
303
|
+
new Promise(
|
|
304
|
+
(resolve) => setTimeout(() => resolve(budgetExceeded), WARMUP_BUDGET_MS)
|
|
305
|
+
)
|
|
306
|
+
]);
|
|
307
|
+
if (outcome === budgetExceeded) {
|
|
308
|
+
console.info(
|
|
309
|
+
`[harness:${ctx.slug}] storage: read-through warm-up still running after ${WARMUP_BUDGET_MS}ms \u2014 answering empty; the next read gets the data.`
|
|
310
|
+
);
|
|
311
|
+
return json(first);
|
|
312
|
+
}
|
|
313
|
+
return json(await read());
|
|
314
|
+
}
|
|
315
|
+
function describeError(error) {
|
|
316
|
+
return error instanceof Error ? error.message : String(error);
|
|
317
|
+
}
|
|
318
|
+
async function trigger(ctx) {
|
|
319
|
+
let body;
|
|
320
|
+
try {
|
|
321
|
+
body = await ctx.request.json();
|
|
322
|
+
} catch {
|
|
323
|
+
return json({ error: "invalid_json" }, { status: 400 });
|
|
324
|
+
}
|
|
325
|
+
if (!isTriggerRequest(body)) {
|
|
326
|
+
return json(
|
|
327
|
+
{
|
|
328
|
+
error: "invalid_trigger",
|
|
329
|
+
hint: 'Expected { kind: "webhook", id, payload, headers? } | { kind: "schedule", id } | { kind: "activate" }.'
|
|
330
|
+
},
|
|
331
|
+
{ status: 400 }
|
|
332
|
+
);
|
|
333
|
+
}
|
|
334
|
+
const liveCtx = ctx.state.ctx;
|
|
335
|
+
const logsBefore = liveCtx.logs.length;
|
|
336
|
+
const secretNames = await liveCtx.secrets.names();
|
|
337
|
+
const finish = (request, run) => run().then((result) => ({
|
|
338
|
+
kind: request.kind,
|
|
339
|
+
outcome: {
|
|
340
|
+
ok: true,
|
|
341
|
+
summary: result.status,
|
|
342
|
+
...result.detail ? { detail: result.detail } : {},
|
|
343
|
+
logs: liveCtx.logs.slice(logsBefore),
|
|
344
|
+
storage: liveCtx.dumpStorage()
|
|
345
|
+
},
|
|
346
|
+
secretNames
|
|
347
|
+
})).catch((error) => ({
|
|
348
|
+
kind: request.kind,
|
|
349
|
+
outcome: {
|
|
350
|
+
ok: false,
|
|
351
|
+
summary: "failed",
|
|
352
|
+
detail: describeError(error),
|
|
353
|
+
logs: liveCtx.logs.slice(logsBefore),
|
|
354
|
+
storage: liveCtx.dumpStorage()
|
|
355
|
+
},
|
|
356
|
+
secretNames
|
|
357
|
+
}));
|
|
358
|
+
switch (body.kind) {
|
|
359
|
+
case "webhook": {
|
|
360
|
+
const webhook = ctx.definition.webhooks?.find((w) => w.id === body.id);
|
|
361
|
+
if (!webhook) {
|
|
362
|
+
return json({ error: "unknown_webhook", id: body.id }, { status: 400 });
|
|
363
|
+
}
|
|
364
|
+
const headers = body.headers ?? (webhook.signature === "none" ? {} : { [webhook.signature.header]: "(unverified \u2014 local transport)" });
|
|
365
|
+
return json(
|
|
366
|
+
await finish(body, async () => {
|
|
367
|
+
const { result } = await invokeWebhook(
|
|
368
|
+
ctx.definition,
|
|
369
|
+
body.id,
|
|
370
|
+
body.payload,
|
|
371
|
+
{ context: liveCtx, headers }
|
|
372
|
+
);
|
|
373
|
+
return result;
|
|
374
|
+
})
|
|
375
|
+
);
|
|
376
|
+
}
|
|
377
|
+
case "schedule": {
|
|
378
|
+
if (!ctx.definition.schedules?.some((s) => s.id === body.id)) {
|
|
379
|
+
return json(
|
|
380
|
+
{ error: "unknown_schedule", id: body.id },
|
|
381
|
+
{ status: 400 }
|
|
382
|
+
);
|
|
383
|
+
}
|
|
384
|
+
return json(
|
|
385
|
+
await finish(body, async () => {
|
|
386
|
+
const { result } = await invokeSchedule(ctx.definition, body.id, {
|
|
387
|
+
context: liveCtx
|
|
388
|
+
});
|
|
389
|
+
return result;
|
|
390
|
+
})
|
|
391
|
+
);
|
|
392
|
+
}
|
|
393
|
+
case "activate": {
|
|
394
|
+
const outcome = await runOnActivateHook(ctx.definition, liveCtx);
|
|
395
|
+
const response = {
|
|
396
|
+
kind: "activate",
|
|
397
|
+
outcome,
|
|
398
|
+
logs: liveCtx.logs.slice(logsBefore),
|
|
399
|
+
storage: liveCtx.dumpStorage(),
|
|
400
|
+
secretNames
|
|
401
|
+
};
|
|
402
|
+
return json(response);
|
|
403
|
+
}
|
|
404
|
+
}
|
|
405
|
+
}
|
|
406
|
+
function isDataMode(value) {
|
|
407
|
+
return value !== null && DATA_MODES.includes(value);
|
|
408
|
+
}
|
|
409
|
+
function isFixtureVariant(value) {
|
|
410
|
+
return value !== null && FIXTURE_VARIANTS.includes(value);
|
|
411
|
+
}
|
|
412
|
+
async function actionInvoke(ctx, actionName) {
|
|
413
|
+
const action = ctx.definition.actions?.[actionName];
|
|
414
|
+
if (!action) {
|
|
415
|
+
return json(
|
|
416
|
+
{
|
|
417
|
+
success: false,
|
|
418
|
+
error: `"${ctx.slug}" declares no action named "${actionName}".`,
|
|
419
|
+
code: "action_not_found"
|
|
420
|
+
},
|
|
421
|
+
{ status: 404 }
|
|
422
|
+
);
|
|
423
|
+
}
|
|
424
|
+
let body;
|
|
425
|
+
try {
|
|
426
|
+
body = await ctx.request.json();
|
|
427
|
+
} catch {
|
|
428
|
+
return json(
|
|
429
|
+
{
|
|
430
|
+
success: false,
|
|
431
|
+
error: "Request body must be JSON.",
|
|
432
|
+
code: "invalid_input"
|
|
433
|
+
},
|
|
434
|
+
{ status: 400 }
|
|
435
|
+
);
|
|
436
|
+
}
|
|
437
|
+
const parsed = action.input.safeParse(
|
|
438
|
+
body?.input
|
|
439
|
+
);
|
|
440
|
+
if (!parsed.success) {
|
|
441
|
+
return json(
|
|
442
|
+
{
|
|
443
|
+
success: false,
|
|
444
|
+
error: "Input failed validation.",
|
|
445
|
+
code: "invalid_input",
|
|
446
|
+
issues: parsed.error.issues
|
|
447
|
+
},
|
|
448
|
+
{ status: 400 }
|
|
449
|
+
);
|
|
450
|
+
}
|
|
451
|
+
const modeHeader = ctx.request.headers.get(HARNESS_ACTIONS_MODE_HEADER);
|
|
452
|
+
const mode = isDataMode(modeHeader) ? modeHeader : "fixtures";
|
|
453
|
+
try {
|
|
454
|
+
const executionCtx = mode === "live" ? ctx.state.ctx : getFixturesActionsState({
|
|
455
|
+
integration: ctx.integration,
|
|
456
|
+
definition: ctx.definition,
|
|
457
|
+
variant: resolveActionsVariant(ctx)
|
|
458
|
+
}).ctx;
|
|
459
|
+
const data = await action.handler(executionCtx, parsed.data);
|
|
460
|
+
if (action.output) {
|
|
461
|
+
const validated = action.output.safeParse(data);
|
|
462
|
+
if (!validated.success) {
|
|
463
|
+
console.error(
|
|
464
|
+
`[harness:${ctx.slug}] action "${actionName}" resolved a value that fails its own declared \`output\` schema:`,
|
|
465
|
+
validated.error.issues
|
|
466
|
+
);
|
|
467
|
+
return json(
|
|
468
|
+
{
|
|
469
|
+
success: false,
|
|
470
|
+
error: "Action failed.",
|
|
471
|
+
code: "handler_error",
|
|
472
|
+
devError: {
|
|
473
|
+
message: "The handler resolved successfully, but the value does not match the `output` schema declared alongside it. This is a dev-only field \u2014 production's host route never returns it.",
|
|
474
|
+
issues: validated.error.issues
|
|
475
|
+
}
|
|
476
|
+
},
|
|
477
|
+
{ status: 500 }
|
|
478
|
+
);
|
|
479
|
+
}
|
|
480
|
+
return json({ success: true, data: validated.data });
|
|
481
|
+
}
|
|
482
|
+
return json({ success: true, data });
|
|
483
|
+
} catch (error) {
|
|
484
|
+
console.error(
|
|
485
|
+
`[harness:${ctx.slug}] action "${actionName}" handler threw (mode: ${mode}):`,
|
|
486
|
+
error
|
|
487
|
+
);
|
|
488
|
+
return json(
|
|
489
|
+
{
|
|
490
|
+
success: false,
|
|
491
|
+
error: "Action failed.",
|
|
492
|
+
code: "handler_error",
|
|
493
|
+
devError: {
|
|
494
|
+
message: describeError(error),
|
|
495
|
+
stack: error instanceof Error ? error.stack : void 0
|
|
496
|
+
}
|
|
497
|
+
},
|
|
498
|
+
{ status: 500 }
|
|
499
|
+
);
|
|
500
|
+
}
|
|
501
|
+
}
|
|
502
|
+
function resolveActionsVariant(ctx) {
|
|
503
|
+
const variantHeader = ctx.request.headers.get(HARNESS_ACTIONS_VARIANT_HEADER);
|
|
504
|
+
return isFixtureVariant(variantHeader) ? variantHeader : "default";
|
|
505
|
+
}
|
|
506
|
+
function localSetupResponse(ctx, secrets, connected) {
|
|
507
|
+
const names = declaredSecretNames(ctx.definition);
|
|
508
|
+
const missing = new Set(secrets.missing);
|
|
509
|
+
return {
|
|
510
|
+
slug: ctx.slug,
|
|
511
|
+
file: LOCAL_SECRETS_RELATIVE_PATH,
|
|
512
|
+
absolutePath: secrets.file,
|
|
513
|
+
redirectUri: ctx.definition.oauth ? callbackUrl(ctx.origin, ctx.slug) : null,
|
|
514
|
+
keys: names.map((name) => ({ name, filled: !missing.has(name) })),
|
|
515
|
+
connected,
|
|
516
|
+
connection: connected ? ctx.state.connection : null,
|
|
517
|
+
volatile: true
|
|
518
|
+
};
|
|
519
|
+
}
|
|
520
|
+
async function localSetup(ctx) {
|
|
521
|
+
if (ctx.request.method.toUpperCase() === "GET") {
|
|
522
|
+
return json(
|
|
523
|
+
localSetupResponse(ctx, ctx.secrets, ctx.state.connection !== null)
|
|
524
|
+
);
|
|
525
|
+
}
|
|
526
|
+
let body;
|
|
527
|
+
try {
|
|
528
|
+
body = await ctx.request.json();
|
|
529
|
+
} catch {
|
|
530
|
+
return json({ error: "invalid_json" }, { status: 400 });
|
|
531
|
+
}
|
|
532
|
+
if (!isLocalSetupWriteRequest(body)) {
|
|
533
|
+
return json(
|
|
534
|
+
{
|
|
535
|
+
error: "invalid_local_setup",
|
|
536
|
+
hint: 'Expected { values: { "<declared secret name>": "<value>" } }.'
|
|
537
|
+
},
|
|
538
|
+
{ status: 400 }
|
|
539
|
+
);
|
|
540
|
+
}
|
|
541
|
+
const names = declaredSecretNames(ctx.definition);
|
|
542
|
+
const written = writeLocalSecrets({
|
|
543
|
+
projectRoot: ctx.projectRoot,
|
|
544
|
+
slug: ctx.slug,
|
|
545
|
+
names,
|
|
546
|
+
values: body.values
|
|
547
|
+
});
|
|
548
|
+
if (!written.ok) {
|
|
549
|
+
return json(
|
|
550
|
+
{ error: "local_secrets_rejected", message: written.message },
|
|
551
|
+
{ status: 400 }
|
|
552
|
+
);
|
|
553
|
+
}
|
|
554
|
+
const reread = readLocalSecrets({
|
|
555
|
+
projectRoot: ctx.projectRoot,
|
|
556
|
+
slug: ctx.slug,
|
|
557
|
+
names
|
|
558
|
+
});
|
|
559
|
+
if (!reread.ok) {
|
|
560
|
+
return json(
|
|
561
|
+
{ error: "local_secrets_unreadable", message: reread.message },
|
|
562
|
+
{ status: 500 }
|
|
563
|
+
);
|
|
564
|
+
}
|
|
565
|
+
const state = getLiveState({
|
|
566
|
+
integration: ctx.integration,
|
|
567
|
+
definition: ctx.definition,
|
|
568
|
+
adminSecrets: reread.values,
|
|
569
|
+
secretsFingerprint: reread.fingerprint
|
|
570
|
+
});
|
|
571
|
+
return json(localSetupResponse(ctx, reread, state.connection !== null));
|
|
572
|
+
}
|
|
573
|
+
export {
|
|
574
|
+
createHarnessApiRouter
|
|
575
|
+
};
|