@ekanos/harness 0.1.4 → 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 +286 -174
  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 +5 -2
  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 +51 -28
  22. package/dist/internal/routes/integration-layout.js +5 -1
  23. package/dist/internal/routes/triggers-page.js +130 -149
  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 +103 -13
  41. package/dist/registry.js +21 -1
  42. package/package.json +13 -7
@@ -0,0 +1,84 @@
1
+ import type { IntegrationDefinition } from '@ekanos/sdk/integration';
2
+ /**
3
+ * ─────────────────────────────────────────────────────────────────────────────
4
+ * `.ekanos/local-secrets.json` — the harness's admin-tier credential source
5
+ * ─────────────────────────────────────────────────────────────────────────────
6
+ *
7
+ * On the host, a partner's OAuth client id/secret and webhook signing keys are
8
+ * admin-issued credentials the operator enters in the Product Catalog; they
9
+ * reach handlers as `ctx.secrets.get('<declared name>')`. Locally there is no
10
+ * catalog, so this file stands in for it: one JSON object, one block per
11
+ * integration slug, one key per DECLARED secret name.
12
+ *
13
+ * The harness GENERATES the skeleton — it has the definition loaded, so it
14
+ * knows exactly which names are declared — and the partner fills the values.
15
+ * Two rules keep it the partner's file:
16
+ *
17
+ * - create-if-missing only. An existing value is never overwritten, and an
18
+ * existing slug block is never rewritten; a newly registered integration
19
+ * gets its block added beside the others.
20
+ * - values never leave the server. Every route that describes this file
21
+ * reports WHICH keys are filled, never what they hold.
22
+ *
23
+ * It lives under `.ekanos/`, which `ekanos dev` gitignores in full and which
24
+ * `ekanos publish` never packs (dotfiles are excluded), so it cannot reach a
25
+ * commit or a submission by accident.
26
+ */
27
+ export declare const LOCAL_SECRETS_RELATIVE_PATH: string;
28
+ /**
29
+ * The only secret names a definition declares statically. Activation-form
30
+ * fields become account-tier secrets at runtime, but those are the user's to
31
+ * type, not the operator's to issue — so they are not part of this file.
32
+ */
33
+ export declare function declaredSecretNames(definition: Pick<IntegrationDefinition, 'oauth' | 'webhooks'>): string[];
34
+ export type LocalSecretsRead = {
35
+ ok: true;
36
+ /** Absolute path of the file. */
37
+ file: string;
38
+ /** Declared names → filled value. Unfilled names are absent. */
39
+ values: Record<string, string>;
40
+ /** Declared names with no non-empty value. */
41
+ missing: string[];
42
+ /** Changes when any declared VALUE changes — the live-context rebuild key. */
43
+ fingerprint: string;
44
+ /** True when this call created the file or added the slug's block. */
45
+ generated: boolean;
46
+ } | {
47
+ ok: false;
48
+ file: string;
49
+ message: string;
50
+ };
51
+ /**
52
+ * Read `slug`'s declared secrets, generating the file / the slug's block when
53
+ * absent. Never overwrites a value that is already there.
54
+ *
55
+ * A file that exists but is not a JSON object is reported, not replaced — the
56
+ * partner may have half-typed an edit, and clobbering it would destroy values
57
+ * they entered by hand.
58
+ */
59
+ export declare function readLocalSecrets(args: {
60
+ projectRoot: string;
61
+ slug: string;
62
+ names: readonly string[];
63
+ }): LocalSecretsRead;
64
+ export type LocalSecretsWrite = {
65
+ ok: true;
66
+ } | {
67
+ ok: false;
68
+ message: string;
69
+ };
70
+ /**
71
+ * Write values for `slug`'s DECLARED secret names — the Local OAuth panel's
72
+ * Save. Only declared names are accepted (an undeclared one is a typo in the
73
+ * panel, never a new secret), values are trimmed (a pasted key with a trailing
74
+ * newline is the most common way a correct credential fails), and an empty
75
+ * string clears the key. Everything else in the file — other slugs, other
76
+ * keys, the help line — is preserved. Refuses a file that is not a JSON
77
+ * object for the same reason the read does.
78
+ */
79
+ export declare function writeLocalSecrets(args: {
80
+ projectRoot: string;
81
+ slug: string;
82
+ names: readonly string[];
83
+ values: Record<string, string>;
84
+ }): LocalSecretsWrite;
@@ -0,0 +1,144 @@
1
+ import { createHash } from "node:crypto";
2
+ import * as fs from "node:fs";
3
+ import * as path from "node:path";
4
+ const LOCAL_SECRETS_RELATIVE_PATH = path.join(
5
+ ".ekanos",
6
+ "local-secrets.json"
7
+ );
8
+ const HELP = 'Local dev credentials for `ekanos dev` live mode \u2014 one block per integration slug, one key per secret name the definition declares. Fill the values from your provider\u2019s DEVELOPER app. Never commit this file (.ekanos/ is gitignored). The redirect URI to register is shown on the harness Activation page under "Local OAuth".';
9
+ function declaredSecretNames(definition) {
10
+ const names = /* @__PURE__ */ new Set();
11
+ if (definition.oauth) {
12
+ names.add(definition.oauth.credentials.clientIdSecretName);
13
+ names.add(definition.oauth.credentials.clientSecretSecretName);
14
+ }
15
+ for (const webhook of definition.webhooks ?? []) {
16
+ if (webhook.signature !== "none") {
17
+ names.add(webhook.signature.secretName);
18
+ }
19
+ }
20
+ return [...names];
21
+ }
22
+ function readDocument(file) {
23
+ let raw;
24
+ try {
25
+ raw = fs.readFileSync(file, "utf8");
26
+ } catch (error) {
27
+ if (error.code === "ENOENT") {
28
+ return { kind: "missing" };
29
+ }
30
+ throw error;
31
+ }
32
+ try {
33
+ const parsed = JSON.parse(raw);
34
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
35
+ return { kind: "corrupt" };
36
+ }
37
+ return { kind: "ok", doc: parsed };
38
+ } catch {
39
+ return { kind: "corrupt" };
40
+ }
41
+ }
42
+ function writeDocument(file, doc) {
43
+ fs.mkdirSync(path.dirname(file), { recursive: true });
44
+ fs.writeFileSync(file, `${JSON.stringify(doc, null, 2)}
45
+ `, {
46
+ encoding: "utf8",
47
+ mode: 384
48
+ });
49
+ }
50
+ function fingerprintOf(values) {
51
+ const hash = createHash("sha256");
52
+ for (const name of Object.keys(values).sort()) {
53
+ hash.update(name);
54
+ hash.update("\0");
55
+ hash.update(values[name] ?? "");
56
+ hash.update("\0");
57
+ }
58
+ return hash.digest("hex").slice(0, 16);
59
+ }
60
+ function readLocalSecrets(args) {
61
+ const file = path.join(args.projectRoot, LOCAL_SECRETS_RELATIVE_PATH);
62
+ const existing = readDocument(file);
63
+ if (existing.kind === "corrupt") {
64
+ return {
65
+ ok: false,
66
+ file,
67
+ message: `${file} is not a JSON object. Fix it by hand (or delete it and the harness will regenerate an empty skeleton).`
68
+ };
69
+ }
70
+ const doc = existing.kind === "ok" ? { ...existing.doc } : { "//": HELP };
71
+ let generated = existing.kind === "missing";
72
+ const currentBlock = doc[args.slug];
73
+ const block = typeof currentBlock === "object" && currentBlock !== null && !Array.isArray(currentBlock) ? { ...currentBlock } : {};
74
+ if (currentBlock === void 0) {
75
+ generated = true;
76
+ }
77
+ let blockChanged = currentBlock === void 0;
78
+ for (const name of args.names) {
79
+ if (!(name in block)) {
80
+ block[name] = "";
81
+ blockChanged = true;
82
+ }
83
+ }
84
+ if (blockChanged) {
85
+ doc[args.slug] = block;
86
+ writeDocument(file, doc);
87
+ }
88
+ const values = {};
89
+ const missing = [];
90
+ for (const name of args.names) {
91
+ const value = block[name];
92
+ if (typeof value === "string" && value.trim().length > 0) {
93
+ values[name] = value;
94
+ } else {
95
+ missing.push(name);
96
+ }
97
+ }
98
+ return {
99
+ ok: true,
100
+ file,
101
+ values,
102
+ missing,
103
+ fingerprint: fingerprintOf(values),
104
+ generated
105
+ };
106
+ }
107
+ function writeLocalSecrets(args) {
108
+ const file = path.join(args.projectRoot, LOCAL_SECRETS_RELATIVE_PATH);
109
+ const declared = new Set(args.names);
110
+ const unknown = Object.keys(args.values).filter(
111
+ (name) => !declared.has(name)
112
+ );
113
+ if (unknown.length > 0) {
114
+ return {
115
+ ok: false,
116
+ message: `Not declared by this integration: ${unknown.join(", ")}. Only the secret names the definition declares can be set here (${[...declared].join(", ") || "none"}).`
117
+ };
118
+ }
119
+ const existing = readDocument(file);
120
+ if (existing.kind === "corrupt") {
121
+ return {
122
+ ok: false,
123
+ message: `${file} is not a JSON object; fix or delete it by hand first.`
124
+ };
125
+ }
126
+ const doc = existing.kind === "ok" ? { ...existing.doc } : { "//": HELP };
127
+ const currentBlock = doc[args.slug];
128
+ const block = typeof currentBlock === "object" && currentBlock !== null && !Array.isArray(currentBlock) ? { ...currentBlock } : {};
129
+ for (const name of args.names) {
130
+ if (!(name in block)) block[name] = "";
131
+ }
132
+ for (const [name, value] of Object.entries(args.values)) {
133
+ block[name] = value.trim();
134
+ }
135
+ doc[args.slug] = block;
136
+ writeDocument(file, doc);
137
+ return { ok: true };
138
+ }
139
+ export {
140
+ LOCAL_SECRETS_RELATIVE_PATH,
141
+ declaredSecretNames,
142
+ readLocalSecrets,
143
+ writeLocalSecrets
144
+ };
@@ -0,0 +1,33 @@
1
+ /**
2
+ * ─────────────────────────────────────────────────────────────────────────────
3
+ * THE API ROUTES ANSWER LOOPBACK ONLY, UNLESS TOLD OTHERWISE
4
+ * ─────────────────────────────────────────────────────────────────────────────
5
+ *
6
+ * The page routes render fixtures. The API routes are different in kind: they
7
+ * hold the partner's real client secret, the tokens `onTokens` stored, and
8
+ * `POST trigger` executes handler code on request. `ekanos dev` already binds
9
+ * loopback by default and warns on `--host`, but that warning is advisory —
10
+ * a partner who starts Next by hand gets Next's own `0.0.0.0` default and no
11
+ * warning at all.
12
+ *
13
+ * So the routes check the `Host` header themselves and refuse anything that
14
+ * is not loopback, unless `EKANOS_HARNESS_EXPOSED=1` says the exposure was a
15
+ * decision. `ekanos dev --host <non-loopback>` sets that variable after
16
+ * printing its warning; nothing else does.
17
+ *
18
+ * `Host` is the header the browser sends for the URL it typed, so a request
19
+ * that reached this process through `http://192.168.1.20:3100` carries that
20
+ * address, not `localhost`. It is not a security boundary against a hostile
21
+ * peer on the same network who rewrites headers — it is the fence that makes
22
+ * accidental exposure fail closed.
23
+ */
24
+ export declare const EXPOSED_ENV = "EKANOS_HARNESS_EXPOSED";
25
+ /** `127.0.0.0/8`, `::1`, `localhost` — with or without a port. */
26
+ export declare function isLoopbackHost(hostHeader: string | null | undefined): boolean;
27
+ export declare function isExposureAllowed(env: Readonly<Record<string, string | undefined>>): boolean;
28
+ /**
29
+ * The 403 to answer with, or `null` when the request may proceed. JSON, and
30
+ * it names the variable — a partner meeting this deliberately should be told
31
+ * exactly how to opt in.
32
+ */
33
+ export declare function loopbackRefusal(request: Request, env: Readonly<Record<string, string | undefined>>): Response | null;
@@ -0,0 +1,38 @@
1
+ const EXPOSED_ENV = "EKANOS_HARNESS_EXPOSED";
2
+ function isLoopbackHost(hostHeader) {
3
+ if (!hostHeader) return false;
4
+ const trimmed = hostHeader.trim().toLowerCase();
5
+ if (trimmed === "::1") return true;
6
+ if (trimmed.startsWith("[")) {
7
+ const close = trimmed.indexOf("]");
8
+ if (close === -1) return false;
9
+ const address = trimmed.slice(1, close);
10
+ return address === "::1" || address === "::ffff:127.0.0.1";
11
+ }
12
+ const host = trimmed.split(":")[0] ?? "";
13
+ if (host === "localhost") return true;
14
+ const octets = host.split(".");
15
+ return octets.length === 4 && octets[0] === "127" && octets.every((octet) => /^\d{1,3}$/.test(octet) && Number(octet) <= 255);
16
+ }
17
+ function isExposureAllowed(env) {
18
+ return env[EXPOSED_ENV] === "1";
19
+ }
20
+ function loopbackRefusal(request, env) {
21
+ if (isExposureAllowed(env)) return null;
22
+ const host = request.headers.get("host");
23
+ if (isLoopbackHost(host)) return null;
24
+ return new Response(
25
+ JSON.stringify({
26
+ error: "not_loopback",
27
+ message: `The harness API answers loopback requests only; this one arrived for Host "${host ?? "(none)"}". These routes hold your local OAuth credentials and run your handlers, so exposure has to be explicit.`,
28
+ hint: `Open the harness at http://localhost:<port> instead, or start it with "ekanos dev --host <address>" (which sets ${EXPOSED_ENV}=1 after warning you).`
29
+ }),
30
+ { status: 403, headers: { "content-type": "application/json" } }
31
+ );
32
+ }
33
+ export {
34
+ EXPOSED_ENV,
35
+ isExposureAllowed,
36
+ isLoopbackHost,
37
+ loopbackRefusal
38
+ };
@@ -0,0 +1,38 @@
1
+ /**
2
+ * The server-side half of the OAuth `state` parameter.
3
+ *
4
+ * `state` travels through the browser and the provider, so nothing in it is
5
+ * trusted: it is a bare nonce, and everything the callback needs — the PKCE
6
+ * verifier and where to send the user afterwards — lives here, keyed by it.
7
+ * The host keeps the same shape in a Supabase OTP row; the harness keeps it
8
+ * in memory, because the whole harness is one process on one machine.
9
+ *
10
+ * Single-use and time-limited, as on the host (`PARTNER_OAUTH_NONCE_TTL_SECONDS`
11
+ * = 600). A consumed or expired nonce is gone, so a replayed callback fails
12
+ * verification rather than running `onTokens` twice.
13
+ */
14
+ export interface PendingAuthorization {
15
+ returnPath: string;
16
+ codeVerifier?: string;
17
+ }
18
+ export type ConsumeResult = {
19
+ status: 'ok';
20
+ entry: PendingAuthorization;
21
+ } | {
22
+ status: 'expired';
23
+ entry: PendingAuthorization;
24
+ } | {
25
+ status: 'unknown';
26
+ };
27
+ export interface NonceStore {
28
+ issue(entry: PendingAuthorization): string;
29
+ consume(nonce: string): ConsumeResult;
30
+ /** Pending, unexpired entries — for tests and the setup panel. */
31
+ size(): number;
32
+ }
33
+ export declare const NONCE_TTL_MS = 600000;
34
+ export declare function createNonceStore(options?: {
35
+ ttlMs?: number;
36
+ now?: () => number;
37
+ generate?: () => string;
38
+ }): NonceStore;
@@ -0,0 +1,40 @@
1
+ import { generateNonce } from "./oauth-loop.js";
2
+ const NONCE_TTL_MS = 6e5;
3
+ function createNonceStore(options = {}) {
4
+ const ttlMs = options.ttlMs ?? NONCE_TTL_MS;
5
+ const now = options.now ?? Date.now;
6
+ const generate = options.generate ?? generateNonce;
7
+ const pending = /* @__PURE__ */ new Map();
8
+ const sweep = () => {
9
+ const cutoff = now() - ttlMs;
10
+ for (const [nonce, entry] of pending) {
11
+ if (entry.issuedAt <= cutoff) pending.delete(nonce);
12
+ }
13
+ };
14
+ return {
15
+ issue(entry) {
16
+ sweep();
17
+ const nonce = generate();
18
+ pending.set(nonce, { ...entry, issuedAt: now() });
19
+ return nonce;
20
+ },
21
+ consume(nonce) {
22
+ const entry = pending.get(nonce);
23
+ if (!entry) return { status: "unknown" };
24
+ pending.delete(nonce);
25
+ const { issuedAt, ...rest } = entry;
26
+ if (issuedAt <= now() - ttlMs) {
27
+ return { status: "expired", entry: rest };
28
+ }
29
+ return { status: "ok", entry: rest };
30
+ },
31
+ size() {
32
+ sweep();
33
+ return pending.size;
34
+ }
35
+ };
36
+ }
37
+ export {
38
+ NONCE_TTL_MS,
39
+ createNonceStore
40
+ };
@@ -0,0 +1,114 @@
1
+ import type { IntegrationContext } from '@ekanos/sdk';
2
+ import type { OAuthProviderDeclaration, OAuthTokens } from '@ekanos/sdk/integration';
3
+ /**
4
+ * ─────────────────────────────────────────────────────────────────────────────
5
+ * THE LOCALHOST OAUTH LOOP — pure helpers
6
+ * ─────────────────────────────────────────────────────────────────────────────
7
+ *
8
+ * The REFERENCE implementation is the Fusion host's hosted OAuth transport
9
+ * (its `oauth-transport` module). These helpers mirror its pure half — PKCE, the authorize URL, the return-path check, the
10
+ * code exchange and its token mapping — so a flow that works here works
11
+ * there. They are duplicated rather than shared because that module is host
12
+ * code (`server-only`, Next, the host logger) and this package is published
13
+ * to npm with only `@ekanos/*` and public dependencies. Keep the two in step.
14
+ *
15
+ * Deliberately zod-free: zod is only a devDependency here, and the token
16
+ * response has five fields.
17
+ *
18
+ * What differs from the host, and why, is in `api-router.ts`: the nonce is
19
+ * held in server memory rather than a Supabase OTP row; there is no session
20
+ * user to bind it to; the connection fact is a field on the live state rather
21
+ * than a table row.
22
+ */
23
+ /**
24
+ * The transport's error vocabulary — appended as `<slug>_oauth_error=<code>`.
25
+ * Identical to the host's, because `partnerOAuthErrorParam()` in `@ekanos/sdk`
26
+ * maps exactly these codes to user-facing copy.
27
+ */
28
+ export type PartnerOAuthErrorCode = 'denied' | 'expired' | 'invalid' | 'unauthorized' | 'not_configured' | 'exchange_failed' | 'save_failed';
29
+ /** RFC 7636 code verifier: 32 random bytes, base64url (43 chars). */
30
+ export declare function generateCodeVerifier(): string;
31
+ /** RFC 7636 S256 challenge: base64url(sha256(verifier)). */
32
+ export declare function generateCodeChallenge(verifier: string): string;
33
+ /** The `state` value: high-entropy, single-use, meaningless to the provider. */
34
+ export declare function generateNonce(): string;
35
+ /** The `redirect_uri` for `slug` on the origin the browser reached us at. */
36
+ export declare function callbackUrl(origin: string, integrationSlug: string): string;
37
+ /**
38
+ * Reduce an untrusted return path to a same-origin path, or the fallback.
39
+ * Rejects anything not starting with a single `/`, protocol-relative `//`,
40
+ * and the backslash trick (`/\evil.com`), then re-asserts the origin after
41
+ * parsing. Same rules as the host.
42
+ */
43
+ export declare function safeReturnPath(raw: string | null | undefined, fallback: string): string;
44
+ /** Back into the harness with `<slug>_oauth_error=<code>`. */
45
+ export declare function errorRedirectUrl(args: {
46
+ origin: string;
47
+ returnPath: string;
48
+ integrationSlug: string;
49
+ code: PartnerOAuthErrorCode;
50
+ }): URL;
51
+ /**
52
+ * Back into the harness with `oauth_success=true` — the param
53
+ * `useOAuthConnectionStatus` strips and turns into a status re-fetch, and the
54
+ * one `OAuthActivationForm` gates its auto-activation on.
55
+ */
56
+ export declare function successRedirectUrl(args: {
57
+ origin: string;
58
+ returnPath: string;
59
+ }): URL;
60
+ export interface BuildAuthorizeUrlInput {
61
+ provider: OAuthProviderDeclaration;
62
+ clientId: string;
63
+ redirectUri: string;
64
+ state: string;
65
+ /** Present iff `provider.pkce`. */
66
+ codeChallenge?: string;
67
+ }
68
+ /** The provider's authorize URL with the standard code-flow parameters. */
69
+ export declare function buildAuthorizeUrl(input: BuildAuthorizeUrlInput): string;
70
+ /**
71
+ * Map a token endpoint's JSON to `OAuthTokens`, or `null` when it is not a
72
+ * token response. Extra fields pass through into `raw` untouched — that is
73
+ * what `raw` is for.
74
+ */
75
+ export declare function parseTokenResponse(payload: unknown, now: Date): OAuthTokens | null;
76
+ export interface ExchangeAuthorizationCodeInput {
77
+ ctx: Pick<IntegrationContext, 'fetch'>;
78
+ provider: OAuthProviderDeclaration;
79
+ clientId: string;
80
+ clientSecret: string;
81
+ code: string;
82
+ /** Must byte-match the `redirect_uri` sent at /connect. */
83
+ redirectUri: string;
84
+ codeVerifier?: string;
85
+ now?: () => Date;
86
+ }
87
+ export type ExchangeAuthorizationCodeResult = {
88
+ ok: true;
89
+ tokens: OAuthTokens;
90
+ }
91
+ /** The endpoint answered non-2xx. `status` is safe to log; the body is not. */
92
+ | {
93
+ ok: false;
94
+ reason: 'http_error';
95
+ status: number;
96
+ }
97
+ /** 2xx, but not JSON or not a token response. */
98
+ | {
99
+ ok: false;
100
+ reason: 'invalid_response';
101
+ }
102
+ /** `ctx.fetch` itself threw — egress denied, DNS, network. */
103
+ | {
104
+ ok: false;
105
+ reason: 'fetch_failed';
106
+ message: string;
107
+ };
108
+ /**
109
+ * POST the declared `tokenUrl` through **`ctx.fetch`** — so the exchange is
110
+ * subject to the definition's own egress list exactly as it is on the host.
111
+ * Client authentication is HTTP Basic, as on the host. The response body is
112
+ * NEVER logged, on any path — it is the credential.
113
+ */
114
+ export declare function exchangeAuthorizationCode(input: ExchangeAuthorizationCodeInput): Promise<ExchangeAuthorizationCodeResult>;
@@ -0,0 +1,141 @@
1
+ import { createHash, randomBytes } from "node:crypto";
2
+ function generateCodeVerifier() {
3
+ return randomBytes(32).toString("base64url");
4
+ }
5
+ function generateCodeChallenge(verifier) {
6
+ return createHash("sha256").update(verifier).digest("base64url");
7
+ }
8
+ function generateNonce() {
9
+ return randomBytes(24).toString("base64url");
10
+ }
11
+ function callbackUrl(origin, integrationSlug) {
12
+ return `${origin}/api/integrations/${integrationSlug}/oauth/callback`;
13
+ }
14
+ function safeReturnPath(raw, fallback) {
15
+ const candidatePath = raw?.trim() || fallback;
16
+ if (!candidatePath.startsWith("/") || candidatePath.startsWith("//") || candidatePath.includes("\\")) {
17
+ return fallback;
18
+ }
19
+ try {
20
+ const probeOrigin = "https://return-path.invalid";
21
+ const candidate = new URL(candidatePath, probeOrigin);
22
+ if (candidate.origin !== probeOrigin) return fallback;
23
+ return candidate.pathname + candidate.search;
24
+ } catch {
25
+ return fallback;
26
+ }
27
+ }
28
+ function errorRedirectUrl(args) {
29
+ const url = new URL(args.returnPath, args.origin);
30
+ url.searchParams.set(`${args.integrationSlug}_oauth_error`, args.code);
31
+ return url;
32
+ }
33
+ function successRedirectUrl(args) {
34
+ const url = new URL(args.returnPath, args.origin);
35
+ url.searchParams.set("oauth_success", "true");
36
+ return url;
37
+ }
38
+ function buildAuthorizeUrl(input) {
39
+ const url = new URL(input.provider.authorizationUrl);
40
+ url.searchParams.set("response_type", "code");
41
+ url.searchParams.set("client_id", input.clientId);
42
+ url.searchParams.set("redirect_uri", input.redirectUri);
43
+ url.searchParams.set("scope", input.provider.scopes.join(" "));
44
+ url.searchParams.set("state", input.state);
45
+ if (input.codeChallenge) {
46
+ url.searchParams.set("code_challenge", input.codeChallenge);
47
+ url.searchParams.set("code_challenge_method", "S256");
48
+ }
49
+ return url.toString();
50
+ }
51
+ function optionalString(value) {
52
+ return typeof value === "string" && value.length > 0 ? value : void 0;
53
+ }
54
+ function optionalPositiveNumber(value) {
55
+ if (value === void 0 || value === null || value === "") return void 0;
56
+ const parsed = typeof value === "number" ? value : Number(value);
57
+ return Number.isFinite(parsed) && parsed > 0 ? parsed : void 0;
58
+ }
59
+ function parseTokenResponse(payload, now) {
60
+ if (typeof payload !== "object" || payload === null || Array.isArray(payload)) {
61
+ return null;
62
+ }
63
+ const record = payload;
64
+ const accessToken = optionalString(record.access_token);
65
+ if (!accessToken) return null;
66
+ const refreshToken = optionalString(record.refresh_token);
67
+ const expiresIn = optionalPositiveNumber(record.expires_in);
68
+ const scope = optionalString(record.scope);
69
+ const tokenType = optionalString(record.token_type);
70
+ return {
71
+ accessToken,
72
+ ...refreshToken ? { refreshToken } : {},
73
+ ...expiresIn !== void 0 ? {
74
+ expiresAt: new Date(
75
+ now.getTime() + Math.floor(expiresIn * 1e3)
76
+ ).toISOString()
77
+ } : {},
78
+ ...scope ? { scope } : {},
79
+ ...tokenType ? { tokenType } : {},
80
+ // Parsed JSON is JSON by construction; the cast records that.
81
+ raw: record
82
+ };
83
+ }
84
+ async function exchangeAuthorizationCode(input) {
85
+ const body = new URLSearchParams({
86
+ grant_type: "authorization_code",
87
+ code: input.code,
88
+ redirect_uri: input.redirectUri
89
+ });
90
+ if (input.codeVerifier) {
91
+ body.set("code_verifier", input.codeVerifier);
92
+ }
93
+ const basic = Buffer.from(
94
+ `${input.clientId}:${input.clientSecret}`,
95
+ "utf8"
96
+ ).toString("base64");
97
+ let response;
98
+ try {
99
+ response = await input.ctx.fetch(input.provider.tokenUrl, {
100
+ method: "POST",
101
+ headers: {
102
+ Accept: "application/json",
103
+ "Content-Type": "application/x-www-form-urlencoded",
104
+ Authorization: `Basic ${basic}`
105
+ },
106
+ body: body.toString()
107
+ });
108
+ } catch (error) {
109
+ return {
110
+ ok: false,
111
+ reason: "fetch_failed",
112
+ message: error instanceof Error ? error.message : String(error)
113
+ };
114
+ }
115
+ if (!response.ok) {
116
+ return { ok: false, reason: "http_error", status: response.status };
117
+ }
118
+ let payload;
119
+ try {
120
+ payload = await response.json();
121
+ } catch {
122
+ return { ok: false, reason: "invalid_response" };
123
+ }
124
+ const tokens = parseTokenResponse(payload, input.now?.() ?? /* @__PURE__ */ new Date());
125
+ if (!tokens) {
126
+ return { ok: false, reason: "invalid_response" };
127
+ }
128
+ return { ok: true, tokens };
129
+ }
130
+ export {
131
+ buildAuthorizeUrl,
132
+ callbackUrl,
133
+ errorRedirectUrl,
134
+ exchangeAuthorizationCode,
135
+ generateCodeChallenge,
136
+ generateCodeVerifier,
137
+ generateNonce,
138
+ parseTokenResponse,
139
+ safeReturnPath,
140
+ successRedirectUrl
141
+ };
@@ -0,0 +1,29 @@
1
+ /**
2
+ * Where the partner's project is, seen from inside the generated shell.
3
+ *
4
+ * `ekanos dev` spawns `next dev` with cwd `<project>/.ekanos/harness`, so the
5
+ * project root is two directories up — and `ekanos.json` is the one file that
6
+ * proves a directory IS the project root rather than merely a parent. An
7
+ * explicit `EKANOS_PROJECT_ROOT` wins when set, for a partner who starts Next
8
+ * some other way, and is held to the same proof.
9
+ *
10
+ * Refuses rather than guesses: a wrong root would put the local-secrets file
11
+ * somewhere the partner never looks, which reads as "the harness lost my
12
+ * credentials".
13
+ */
14
+ export declare const PROJECT_ROOT_ENV = "EKANOS_PROJECT_ROOT";
15
+ export type ProjectRootResolution = {
16
+ ok: true;
17
+ root: string;
18
+ source: 'env' | 'cwd';
19
+ } | {
20
+ ok: false;
21
+ message: string;
22
+ hint: string;
23
+ };
24
+ export declare function resolveProjectRoot(args: {
25
+ env: Readonly<Record<string, string | undefined>>;
26
+ cwd: string;
27
+ /** Test seam. Defaults to a real `fs.existsSync`. */
28
+ exists?: (candidate: string) => boolean;
29
+ }): ProjectRootResolution;