@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,93 @@
|
|
|
1
|
+
import type { IntegrationDefinition } from '@ekanos/sdk/integration';
|
|
2
|
+
import { type MockFetchHandler, type MockIntegrationContext } from '@ekanos/sdk/testing';
|
|
3
|
+
import { type HarnessIntegration } from '../../registry.js';
|
|
4
|
+
import { type NonceStore } from './nonce-store.js';
|
|
5
|
+
/**
|
|
6
|
+
* ─────────────────────────────────────────────────────────────────────────────
|
|
7
|
+
* THE LIVE CONTEXT — one server-held `ctx` per integration
|
|
8
|
+
* ─────────────────────────────────────────────────────────────────────────────
|
|
9
|
+
*
|
|
10
|
+
* The Triggers and Activation surfaces run handlers against a mock context
|
|
11
|
+
* built in the BROWSER, per mount, from `triggerMocks` seeds. That is right
|
|
12
|
+
* for fixtures mode and useless for a real OAuth loop: the token exchange
|
|
13
|
+
* needs a server (the client secret must not reach the browser), and the
|
|
14
|
+
* tokens `onTokens` stores must outlive a page — the widgets read what the
|
|
15
|
+
* schedule wrote, minutes later, on a different route.
|
|
16
|
+
*
|
|
17
|
+
* So live mode gets ONE context per slug, held in this process:
|
|
18
|
+
*
|
|
19
|
+
* - built with `createMockContext` — the same storage-schema and egress
|
|
20
|
+
* enforcement partner tests and the host use, no new runtime;
|
|
21
|
+
* - `ctx.fetch` reaches the REAL network through a final catch-all fetch
|
|
22
|
+
* handler. The mock checks egress BEFORE it consults handlers, so an origin
|
|
23
|
+
* the definition does not declare fails here exactly as it would in
|
|
24
|
+
* production. A partner's own `triggerMocks.fetchHandlers` sit ahead of
|
|
25
|
+
* the passthrough, so an endpoint they deliberately mocked stays mocked;
|
|
26
|
+
* - admin-tier secrets come from `.ekanos/local-secrets.json`; account-tier
|
|
27
|
+
* secrets and storage are whatever the partner's own handlers wrote. No
|
|
28
|
+
* storage seeds: live means real data only.
|
|
29
|
+
*
|
|
30
|
+
* Kept on `globalThis` under a `Symbol.for` key so a dev-server recompile of
|
|
31
|
+
* the route module (which resets module scope) does not drop tokens mid-flow.
|
|
32
|
+
* NOT persisted to disk: `dumpStorage()` is lossy (no `expiresAt`), secret
|
|
33
|
+
* tiers cannot be restored, and a plaintext token file is a poor trade for
|
|
34
|
+
* saving one Connect click after a restart. The setup panel says so.
|
|
35
|
+
*
|
|
36
|
+
* Rebuilt when the declared secret VALUES change — a different client id
|
|
37
|
+
* invalidates every token issued under the old one anyway, and a stale admin
|
|
38
|
+
* tier is the kind of bug that presents as "the harness ignores my edits".
|
|
39
|
+
*/
|
|
40
|
+
export interface LiveConnection {
|
|
41
|
+
obtainedAt: string;
|
|
42
|
+
expiresAt: string | null;
|
|
43
|
+
scope: string | null;
|
|
44
|
+
}
|
|
45
|
+
export interface LiveState {
|
|
46
|
+
slug: string;
|
|
47
|
+
ctx: MockIntegrationContext;
|
|
48
|
+
connection: LiveConnection | null;
|
|
49
|
+
nonces: NonceStore;
|
|
50
|
+
/** The `local-secrets.json` fingerprint this context was built from. */
|
|
51
|
+
secretsFingerprint: string;
|
|
52
|
+
warmup: {
|
|
53
|
+
inFlight: Promise<void> | null;
|
|
54
|
+
lastStartedAt: number;
|
|
55
|
+
};
|
|
56
|
+
}
|
|
57
|
+
export declare function getLiveStore(): Map<string, LiveState>;
|
|
58
|
+
/** Test seam: forget every live context. */
|
|
59
|
+
export declare function resetLiveStore(): void;
|
|
60
|
+
/**
|
|
61
|
+
* The last fetch handler: hand the request to the fetch beneath the harness
|
|
62
|
+
* interceptor. `redirect: 'error'` for the same reason live-mode widget
|
|
63
|
+
* requests carry it — an allowlist is a promise about ONE url, and a redirect
|
|
64
|
+
* would silently make it a promise about wherever that points next.
|
|
65
|
+
*/
|
|
66
|
+
export declare function createNetworkPassthrough(networkFetch?: () => typeof globalThis.fetch): MockFetchHandler;
|
|
67
|
+
export interface LiveStateInput {
|
|
68
|
+
integration: HarnessIntegration;
|
|
69
|
+
definition: IntegrationDefinition;
|
|
70
|
+
/** Declared secret names → filled values, from `local-secrets.json`. */
|
|
71
|
+
adminSecrets: Record<string, string>;
|
|
72
|
+
secretsFingerprint: string;
|
|
73
|
+
/** Test seam for the passthrough's network fetch. */
|
|
74
|
+
networkFetch?: () => typeof globalThis.fetch;
|
|
75
|
+
/** Test seam for the nonce store. */
|
|
76
|
+
nonces?: () => NonceStore;
|
|
77
|
+
}
|
|
78
|
+
export declare function getLiveState(input: LiveStateInput): LiveState;
|
|
79
|
+
/** Between warm-ups for one slug, so a rendering burst is one invocation. */
|
|
80
|
+
export declare const WARMUP_COOLDOWN_MS = 30000;
|
|
81
|
+
/** How long the storage route waits for a warm-up before answering empty. */
|
|
82
|
+
export declare const WARMUP_BUDGET_MS = 8000;
|
|
83
|
+
/**
|
|
84
|
+
* Read-through warm-up, mirroring the host storage route: an EMPTY read runs
|
|
85
|
+
* the declared schedule handler(s) once so the first paint after Connect has
|
|
86
|
+
* data, instead of the widget staring at nothing until someone presses "Run
|
|
87
|
+
* now". One in-flight run per slug, one start per cooldown window; the
|
|
88
|
+
* caller races it against `WARMUP_BUDGET_MS` and re-reads if it finishes.
|
|
89
|
+
*
|
|
90
|
+
* Returns the in-flight promise when a run is happening, or `null` when
|
|
91
|
+
* nothing was (or could be) started.
|
|
92
|
+
*/
|
|
93
|
+
export declare function startWarmup(state: LiveState, definition: IntegrationDefinition, now?: () => number): Promise<void> | null;
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
import {
|
|
2
|
+
createMockContext,
|
|
3
|
+
invokeSchedule
|
|
4
|
+
} from "@ekanos/sdk/testing";
|
|
5
|
+
import { HARNESS_ACCOUNT_ID } from "../../registry.js";
|
|
6
|
+
import { resolveOriginalFetch } from "../lib/original-fetch.js";
|
|
7
|
+
import { createNonceStore } from "./nonce-store.js";
|
|
8
|
+
const STORE = /* @__PURE__ */ Symbol.for("ekanos.harness.live-state");
|
|
9
|
+
function getLiveStore() {
|
|
10
|
+
const carrier = globalThis;
|
|
11
|
+
carrier[STORE] ??= /* @__PURE__ */ new Map();
|
|
12
|
+
return carrier[STORE];
|
|
13
|
+
}
|
|
14
|
+
function resetLiveStore() {
|
|
15
|
+
getLiveStore().clear();
|
|
16
|
+
}
|
|
17
|
+
function createNetworkPassthrough(networkFetch = resolveOriginalFetch) {
|
|
18
|
+
return {
|
|
19
|
+
match: /^/,
|
|
20
|
+
respond: (request) => networkFetch()(request, { redirect: "error" })
|
|
21
|
+
};
|
|
22
|
+
}
|
|
23
|
+
function getLiveState(input) {
|
|
24
|
+
const store = getLiveStore();
|
|
25
|
+
const existing = store.get(input.integration.slug);
|
|
26
|
+
if (existing && existing.secretsFingerprint === input.secretsFingerprint) {
|
|
27
|
+
return existing;
|
|
28
|
+
}
|
|
29
|
+
if (existing) {
|
|
30
|
+
console.info(
|
|
31
|
+
`[harness:${input.integration.slug}] local-secrets.json changed \u2014 rebuilding the live context. Any connection is forgotten; run Connect again.`
|
|
32
|
+
);
|
|
33
|
+
}
|
|
34
|
+
const definition = input.definition;
|
|
35
|
+
const ctx = createMockContext({
|
|
36
|
+
accountId: HARNESS_ACCOUNT_ID,
|
|
37
|
+
integration: { slug: definition.slug },
|
|
38
|
+
...definition.storage ? { storageSchemas: definition.storage } : {},
|
|
39
|
+
egress: definition.egress ?? [],
|
|
40
|
+
secrets: { admin: input.adminSecrets },
|
|
41
|
+
fetchHandlers: [
|
|
42
|
+
...input.integration.triggerMocks?.fetchHandlers ?? [],
|
|
43
|
+
createNetworkPassthrough(input.networkFetch)
|
|
44
|
+
]
|
|
45
|
+
});
|
|
46
|
+
const state = {
|
|
47
|
+
slug: input.integration.slug,
|
|
48
|
+
ctx,
|
|
49
|
+
connection: null,
|
|
50
|
+
nonces: input.nonces?.() ?? createNonceStore(),
|
|
51
|
+
secretsFingerprint: input.secretsFingerprint,
|
|
52
|
+
warmup: { inFlight: null, lastStartedAt: 0 }
|
|
53
|
+
};
|
|
54
|
+
store.set(input.integration.slug, state);
|
|
55
|
+
return state;
|
|
56
|
+
}
|
|
57
|
+
const WARMUP_COOLDOWN_MS = 3e4;
|
|
58
|
+
const WARMUP_BUDGET_MS = 8e3;
|
|
59
|
+
function startWarmup(state, definition, now = Date.now) {
|
|
60
|
+
if (state.warmup.inFlight) return state.warmup.inFlight;
|
|
61
|
+
const schedules = definition.schedules ?? [];
|
|
62
|
+
if (schedules.length === 0) return null;
|
|
63
|
+
if (now() - state.warmup.lastStartedAt < WARMUP_COOLDOWN_MS) return null;
|
|
64
|
+
state.warmup.lastStartedAt = now();
|
|
65
|
+
const run = (async () => {
|
|
66
|
+
for (const schedule of schedules) {
|
|
67
|
+
try {
|
|
68
|
+
await invokeSchedule(definition, schedule.id, {
|
|
69
|
+
context: state.ctx,
|
|
70
|
+
trigger: "schedule"
|
|
71
|
+
});
|
|
72
|
+
} catch (error) {
|
|
73
|
+
console.warn(
|
|
74
|
+
`[harness:${state.slug}] read-through warm-up: schedule "${schedule.id}" threw`,
|
|
75
|
+
error
|
|
76
|
+
);
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
})().finally(() => {
|
|
80
|
+
state.warmup.inFlight = null;
|
|
81
|
+
});
|
|
82
|
+
state.warmup.inFlight = run;
|
|
83
|
+
return run;
|
|
84
|
+
}
|
|
85
|
+
export {
|
|
86
|
+
WARMUP_BUDGET_MS,
|
|
87
|
+
WARMUP_COOLDOWN_MS,
|
|
88
|
+
createNetworkPassthrough,
|
|
89
|
+
getLiveState,
|
|
90
|
+
getLiveStore,
|
|
91
|
+
resetLiveStore,
|
|
92
|
+
startWarmup
|
|
93
|
+
};
|
|
@@ -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>;
|