@artieeez/cf-plugin-host 0.0.0-stage → 0.1.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 +14 -2
- package/dist/index.d.ts +146 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +267 -0
- package/dist/index.js.map +1 -0
- package/package.json +36 -3
- package/src/index.ts +344 -0
package/README.md
CHANGED
|
@@ -1,3 +1,15 @@
|
|
|
1
|
-
#
|
|
1
|
+
# plugin-host
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Runs plugins, as opposed to defining them (`definePlugin` in `@artieeez/cf-sdk/plugin`):
|
|
4
|
+
|
|
5
|
+
- `loadEnvInstances`: each plugin's default instance, from the env names its `configEnv`
|
|
6
|
+
declares, `CF_<PLUGIN>_INSTANCE` and `CF_<PLUGIN>_HOOK_TOKEN` (AD-089). No config file.
|
|
7
|
+
- `readOidcEnv`: people's sign-in from `CF_OIDC_*`.
|
|
8
|
+
- `resolveWorkflow`: a manifest's slots bound (dashboard, else the only instance of the
|
|
9
|
+
plugin) and its settings valued (dashboard, else the manifest default).
|
|
10
|
+
- `ingest`: verify, replay window, normalise and check a webhook against the plugin's
|
|
11
|
+
events.
|
|
12
|
+
- `wrapActions`: a slot's actions with `plugin.action.*` events and a 30 s timeout.
|
|
13
|
+
|
|
14
|
+
Embedded in the server (official ingress, settings checks) and in the worker runtime
|
|
15
|
+
(actions). See [docs/design/plugins.md](../../docs/design/plugins.md).
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
import { type Manifest } from '@artieeez/cf-core';
|
|
2
|
+
import type { NormalizedEvent, PluginActions, PluginDefinition } from '@artieeez/cf-sdk/plugin';
|
|
3
|
+
export type AnyPlugin = PluginDefinition<any, PluginActions>;
|
|
4
|
+
/** One plugin instance: a plugin wired to an account and a scope; today the default one each plugin's env makes (AD-089). */
|
|
5
|
+
export interface Instance {
|
|
6
|
+
name: string;
|
|
7
|
+
plugin: AnyPlugin;
|
|
8
|
+
config: unknown;
|
|
9
|
+
/** the URL token of `/hooks/<instance>/<token>`; none: the instance has no webhook */
|
|
10
|
+
hookToken: string | undefined;
|
|
11
|
+
/**
|
|
12
|
+
* its own secrets by their declared names, when it was set up on the dashboard (integration-setup
|
|
13
|
+
* door 1); absent: an env default instance, whose secrets are read from env by those names
|
|
14
|
+
*/
|
|
15
|
+
secrets?: Record<string, string>;
|
|
16
|
+
}
|
|
17
|
+
/** A workflow's slot bindings and setting values, as the dashboard stored them (AD-087). */
|
|
18
|
+
export interface WorkflowConfig {
|
|
19
|
+
bind: Record<string, string>;
|
|
20
|
+
settings: Record<string, string>;
|
|
21
|
+
}
|
|
22
|
+
/** How people sign in (oidc-login door 5): one OIDC issuer and how its claims map to roles, from `CF_OIDC_*` (AD-089). */
|
|
23
|
+
export interface OidcConfig {
|
|
24
|
+
issuer: string;
|
|
25
|
+
clientId: string;
|
|
26
|
+
clientSecret: string;
|
|
27
|
+
/** the ID token claim whose values are matched against `roles`; `groups` by default */
|
|
28
|
+
rolesClaim: string;
|
|
29
|
+
roles: {
|
|
30
|
+
admin: string[];
|
|
31
|
+
operator: string[];
|
|
32
|
+
viewer: string[];
|
|
33
|
+
};
|
|
34
|
+
/** emails that are admin whatever their claims */
|
|
35
|
+
bootstrapAdmins: string[];
|
|
36
|
+
}
|
|
37
|
+
/** The factory's plugin instances (AD-089): no file, each built from its plugin's env. */
|
|
38
|
+
export interface FactoryConfig {
|
|
39
|
+
instances: Record<string, Instance>;
|
|
40
|
+
}
|
|
41
|
+
export declare const EMPTY_FACTORY: FactoryConfig;
|
|
42
|
+
/** The factory's env cannot be used; the message has one line per problem, each naming its env var. */
|
|
43
|
+
export declare class FactoryConfigError extends Error {
|
|
44
|
+
name: string;
|
|
45
|
+
}
|
|
46
|
+
/** Shortest hook token (door 6). */
|
|
47
|
+
export declare const HOOK_TOKEN_MIN = 24;
|
|
48
|
+
/** `CF_<PLUGIN>`: the prefix of a plugin's own env names, its id upper-cased with dashes as underscores. */
|
|
49
|
+
export declare function pluginEnvPrefix(plugin: AnyPlugin): string;
|
|
50
|
+
/**
|
|
51
|
+
* The default instance of each plugin whose `configEnv` has any name set (AD-089): named
|
|
52
|
+
* `CF_<PLUGIN>_INSTANCE` (default its id), its config parsed from those env values, its hook token
|
|
53
|
+
* `CF_<PLUGIN>_HOOK_TOKEN` (none: no webhook). Anything wrong throws `FactoryConfigError` with one
|
|
54
|
+
* line per problem naming the env var.
|
|
55
|
+
*/
|
|
56
|
+
export declare function loadEnvInstances(env: NodeJS.ProcessEnv, plugins: readonly AnyPlugin[]): FactoryConfig;
|
|
57
|
+
/**
|
|
58
|
+
* People's sign-in from `CF_OIDC_*` (AD-089): none without `CF_OIDC_ISSUER`; with it, a missing
|
|
59
|
+
* `CF_OIDC_CLIENT_ID` or `CF_OIDC_CLIENT_SECRET` throws `FactoryConfigError` naming it.
|
|
60
|
+
*/
|
|
61
|
+
export declare function readOidcEnv(env: NodeJS.ProcessEnv): OidcConfig | undefined;
|
|
62
|
+
/** A plugin's secrets read from `env` by their declared names; the names it lacks in `missing`. */
|
|
63
|
+
export declare function readSecrets(plugin: AnyPlugin, env: NodeJS.ProcessEnv): {
|
|
64
|
+
secrets: Record<string, string>;
|
|
65
|
+
missing: string[];
|
|
66
|
+
};
|
|
67
|
+
/**
|
|
68
|
+
* An instance's secrets: its own when it carries them (a dashboard instance, integration-setup),
|
|
69
|
+
* else read from `env` by its plugin's declared names (an env default instance, AD-089).
|
|
70
|
+
*/
|
|
71
|
+
export declare function instanceSecrets(instance: Instance, env: NodeJS.ProcessEnv): {
|
|
72
|
+
secrets: Record<string, string>;
|
|
73
|
+
missing: string[];
|
|
74
|
+
};
|
|
75
|
+
/** What a unit learns of a slot (door 8): never a secret. */
|
|
76
|
+
export interface Binding {
|
|
77
|
+
instance: string;
|
|
78
|
+
plugin: string;
|
|
79
|
+
config: unknown;
|
|
80
|
+
}
|
|
81
|
+
/** Where a slot's instance came from (AD-087, AD-089): the dashboard, or the single instance of its plugin. */
|
|
82
|
+
export type BindingSource = 'dashboard' | 'auto';
|
|
83
|
+
/** Where a setting's value came from (AD-087, AD-089): the dashboard, or the manifest default. */
|
|
84
|
+
export type SettingSource = 'dashboard' | 'default';
|
|
85
|
+
/** A workflow's slots and settings as resolved here (door 8, AD-087). */
|
|
86
|
+
export interface ResolvedWorkflow {
|
|
87
|
+
/** what a unit learns of each bound slot */
|
|
88
|
+
bindings: Record<string, Binding>;
|
|
89
|
+
/**
|
|
90
|
+
* per slot with a chosen instance, where the choice came from; also when that instance is gone or
|
|
91
|
+
* of another plugin (the slot is then unbound), so the dashboard can clear a stale choice
|
|
92
|
+
*/
|
|
93
|
+
bindingSources: Record<string, BindingSource>;
|
|
94
|
+
settings: Record<string, string>;
|
|
95
|
+
/** per valued setting, where its value came from */
|
|
96
|
+
settingSources: Record<string, SettingSource>;
|
|
97
|
+
/** the declared slots bound to no instance */
|
|
98
|
+
unbound: string[];
|
|
99
|
+
/** the declared settings with no value and no default */
|
|
100
|
+
missing: string[];
|
|
101
|
+
/** one line per unbound slot or missing setting; empty when the workflow can run */
|
|
102
|
+
problems: string[];
|
|
103
|
+
}
|
|
104
|
+
/** Every instance of `plugin` on the factory, by name: what a slot of that plugin may bind to. */
|
|
105
|
+
export declare function slotChoices(factory: FactoryConfig, plugin: string): string[];
|
|
106
|
+
/**
|
|
107
|
+
* A workflow's slots bound to instances and its settings resolved (door 8, AD-087). A slot binds to
|
|
108
|
+
* its dashboard binding (`stored`), else the single instance of its plugin; a setting reads the
|
|
109
|
+
* dashboard, else the manifest default (AD-089). Keys the manifest does not declare are ignored. A
|
|
110
|
+
* binding to an instance that is gone or of another plugin binds nothing: it does not fall through
|
|
111
|
+
* to auto-bind, and keeps its source in `bindingSources`.
|
|
112
|
+
*/
|
|
113
|
+
export declare function resolveWorkflow(manifest: Manifest, factory: FactoryConfig, stored?: WorkflowConfig): ResolvedWorkflow;
|
|
114
|
+
/** The replay window of door 4. */
|
|
115
|
+
export declare const REPLAY_WINDOW_MS = 60000;
|
|
116
|
+
export type IngestResult = {
|
|
117
|
+
kind: 'rejected';
|
|
118
|
+
reason: 'signature' | 'stale';
|
|
119
|
+
} | {
|
|
120
|
+
kind: 'invalid';
|
|
121
|
+
message: string;
|
|
122
|
+
} | {
|
|
123
|
+
kind: 'ok';
|
|
124
|
+
events: NormalizedEvent[];
|
|
125
|
+
dedupKey: string | undefined;
|
|
126
|
+
};
|
|
127
|
+
/**
|
|
128
|
+
* Verifies, checks the replay window, normalises and checks each event against the plugin's
|
|
129
|
+
* schemas (plugins.md, Plugin host "Ingress"). The caller has already checked the token and size.
|
|
130
|
+
*/
|
|
131
|
+
export declare function ingest(instance: Instance, secrets: Record<string, string>, raw: {
|
|
132
|
+
headers: Record<string, string | undefined>;
|
|
133
|
+
rawBody: string;
|
|
134
|
+
}, now: number): IngestResult;
|
|
135
|
+
/** Door 10's `argsSummary`: the JSON of the args, cut to 500 chars with `…`. */
|
|
136
|
+
export declare function argsSummary(args: unknown[]): string;
|
|
137
|
+
/** How long a plugin action may run (door 10). */
|
|
138
|
+
export declare const ACTION_TIMEOUT_MS = 30000;
|
|
139
|
+
/**
|
|
140
|
+
* Runs one action with door 10's timeout: the result, or an error naming the cause (`timeout`
|
|
141
|
+
* when it ran out). Only the server calls it (AD-048); a call is never retried.
|
|
142
|
+
*/
|
|
143
|
+
export declare function callAction(fn: (...args: unknown[]) => Promise<unknown>, args: unknown[], timeoutMs?: number): Promise<unknown>;
|
|
144
|
+
/** The names of a plugin's actions, built with no secret and a fetch that refuses (the worker's proxy). */
|
|
145
|
+
export declare function actionNames(plugin: AnyPlugin, config: unknown): string[];
|
|
146
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAyB,KAAK,QAAQ,EAAE,MAAM,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AAE,OAAO,EAAE,GAAG,MAAM,CAQnD;AAED,kDAAkD;AAClD,eAAO,MAAM,iBAAiB,QAAS,CAAC;AAExC;;;GAGG;AACH,wBAAsB,UAAU,CAC9B,EAAE,EAAE,CAAC,GAAG,IAAI,EAAE,OAAO,EAAE,KAAK,OAAO,CAAC,OAAO,CAAC,EAC5C,IAAI,EAAE,OAAO,EAAE,EACf,SAAS,GAAE,MAA0B,GACpC,OAAO,CAAC,OAAO,CAAC,CAUlB;AAED,2GAA2G;AAC3G,wBAAgB,WAAW,CAAC,MAAM,EAAE,SAAS,EAAE,MAAM,EAAE,OAAO,GAAG,MAAM,EAAE,CAGxE"}
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,267 @@
|
|
|
1
|
+
import { ARGS_SUMMARY_MAX, cut } from '@artieeez/cf-core';
|
|
2
|
+
export const EMPTY_FACTORY = { instances: {} };
|
|
3
|
+
/** The factory's env cannot be used; the message has one line per problem, each naming its env var. */
|
|
4
|
+
export class FactoryConfigError extends Error {
|
|
5
|
+
name = 'FactoryConfigError';
|
|
6
|
+
}
|
|
7
|
+
/** Shortest hook token (door 6). */
|
|
8
|
+
export const HOOK_TOKEN_MIN = 24;
|
|
9
|
+
const INSTANCE = /^[a-z][a-z0-9-]*$/;
|
|
10
|
+
const fail = (what, problems) => {
|
|
11
|
+
throw new FactoryConfigError(`${what}:\n- ${problems.join('\n- ')}`);
|
|
12
|
+
};
|
|
13
|
+
/** An env value, `undefined` when unset or empty. */
|
|
14
|
+
const envOf = (env, name) => {
|
|
15
|
+
const v = env[name];
|
|
16
|
+
return v === undefined || v === '' ? undefined : v;
|
|
17
|
+
};
|
|
18
|
+
/** `CF_<PLUGIN>`: the prefix of a plugin's own env names, its id upper-cased with dashes as underscores. */
|
|
19
|
+
export function pluginEnvPrefix(plugin) {
|
|
20
|
+
return `CF_${plugin.id.toUpperCase().replace(/-/g, '_')}`;
|
|
21
|
+
}
|
|
22
|
+
/**
|
|
23
|
+
* The default instance of each plugin whose `configEnv` has any name set (AD-089): named
|
|
24
|
+
* `CF_<PLUGIN>_INSTANCE` (default its id), its config parsed from those env values, its hook token
|
|
25
|
+
* `CF_<PLUGIN>_HOOK_TOKEN` (none: no webhook). Anything wrong throws `FactoryConfigError` with one
|
|
26
|
+
* line per problem naming the env var.
|
|
27
|
+
*/
|
|
28
|
+
export function loadEnvInstances(env, plugins) {
|
|
29
|
+
const instances = {};
|
|
30
|
+
const problems = [];
|
|
31
|
+
for (const plugin of plugins) {
|
|
32
|
+
const names = Object.entries(plugin.configEnv ?? {});
|
|
33
|
+
if (!names.some(([, name]) => envOf(env, name) !== undefined))
|
|
34
|
+
continue;
|
|
35
|
+
const prefix = pluginEnvPrefix(plugin);
|
|
36
|
+
const nameVar = `${prefix}_INSTANCE`;
|
|
37
|
+
const name = envOf(env, nameVar) ?? plugin.id;
|
|
38
|
+
let ok = true;
|
|
39
|
+
if (!INSTANCE.test(name)) {
|
|
40
|
+
problems.push(`${nameVar}: instance names are lowercase slugs, got "${name}"`);
|
|
41
|
+
ok = false;
|
|
42
|
+
}
|
|
43
|
+
else if (instances[name] !== undefined) {
|
|
44
|
+
problems.push(`${nameVar}: "${name}" is already the instance of ${instances[name].plugin.id}`);
|
|
45
|
+
ok = false;
|
|
46
|
+
}
|
|
47
|
+
const raw = {};
|
|
48
|
+
const unset = new Set();
|
|
49
|
+
for (const [key, envName] of names) {
|
|
50
|
+
const v = envOf(env, envName);
|
|
51
|
+
if (v === undefined) {
|
|
52
|
+
unset.add(key);
|
|
53
|
+
problems.push(`${envName}: is not set`);
|
|
54
|
+
}
|
|
55
|
+
else
|
|
56
|
+
raw[key] = v;
|
|
57
|
+
}
|
|
58
|
+
const parsed = plugin.config.safeParse(raw);
|
|
59
|
+
if (!parsed.success) {
|
|
60
|
+
for (const issue of parsed.error.issues) {
|
|
61
|
+
const key = issue.path[0];
|
|
62
|
+
if (typeof key === 'string' && unset.has(key))
|
|
63
|
+
continue;
|
|
64
|
+
const envName = typeof key === 'string' ? plugin.configEnv?.[key] : undefined;
|
|
65
|
+
problems.push(`${envName ?? `${plugin.id} config ${issue.path.join('.') || '(root)'}`}: ${issue.message}`);
|
|
66
|
+
}
|
|
67
|
+
ok = false;
|
|
68
|
+
}
|
|
69
|
+
const tokenVar = `${prefix}_HOOK_TOKEN`;
|
|
70
|
+
const hookToken = envOf(env, tokenVar);
|
|
71
|
+
if (hookToken !== undefined && hookToken.length < HOOK_TOKEN_MIN) {
|
|
72
|
+
problems.push(`${tokenVar}: must be at least ${HOOK_TOKEN_MIN} chars`);
|
|
73
|
+
ok = false;
|
|
74
|
+
}
|
|
75
|
+
if (ok && unset.size === 0 && parsed.success)
|
|
76
|
+
instances[name] = { name, plugin, config: parsed.data, hookToken };
|
|
77
|
+
}
|
|
78
|
+
if (problems.length > 0)
|
|
79
|
+
fail('plugin env', problems);
|
|
80
|
+
return { instances };
|
|
81
|
+
}
|
|
82
|
+
/** A comma list from env: split, trimmed, empty items dropped. */
|
|
83
|
+
const listOf = (env, name) => (env[name] ?? '')
|
|
84
|
+
.split(',')
|
|
85
|
+
.map((s) => s.trim())
|
|
86
|
+
.filter((s) => s !== '');
|
|
87
|
+
/**
|
|
88
|
+
* People's sign-in from `CF_OIDC_*` (AD-089): none without `CF_OIDC_ISSUER`; with it, a missing
|
|
89
|
+
* `CF_OIDC_CLIENT_ID` or `CF_OIDC_CLIENT_SECRET` throws `FactoryConfigError` naming it.
|
|
90
|
+
*/
|
|
91
|
+
export function readOidcEnv(env) {
|
|
92
|
+
const issuer = envOf(env, 'CF_OIDC_ISSUER');
|
|
93
|
+
if (issuer === undefined)
|
|
94
|
+
return undefined;
|
|
95
|
+
const missing = ['CF_OIDC_CLIENT_ID', 'CF_OIDC_CLIENT_SECRET'].filter((n) => envOf(env, n) === undefined);
|
|
96
|
+
if (missing.length > 0)
|
|
97
|
+
fail('sign-in env (CF_OIDC_ISSUER is set)', missing.map((n) => `${n}: is not set`));
|
|
98
|
+
return {
|
|
99
|
+
issuer,
|
|
100
|
+
clientId: env['CF_OIDC_CLIENT_ID'],
|
|
101
|
+
clientSecret: env['CF_OIDC_CLIENT_SECRET'],
|
|
102
|
+
rolesClaim: envOf(env, 'CF_OIDC_ROLES_CLAIM') ?? 'groups',
|
|
103
|
+
roles: { admin: listOf(env, 'CF_OIDC_ADMIN_GROUPS'), operator: listOf(env, 'CF_OIDC_OPERATOR_GROUPS'), viewer: listOf(env, 'CF_OIDC_VIEWER_GROUPS') },
|
|
104
|
+
bootstrapAdmins: listOf(env, 'CF_OIDC_BOOTSTRAP_ADMINS'),
|
|
105
|
+
};
|
|
106
|
+
}
|
|
107
|
+
/** A plugin's secrets read from `env` by their declared names; the names it lacks in `missing`. */
|
|
108
|
+
export function readSecrets(plugin, env) {
|
|
109
|
+
const secrets = {};
|
|
110
|
+
const missing = [];
|
|
111
|
+
for (const name of plugin.secrets) {
|
|
112
|
+
const v = env[name];
|
|
113
|
+
if (v === undefined || v === '')
|
|
114
|
+
missing.push(name);
|
|
115
|
+
else
|
|
116
|
+
secrets[name] = v;
|
|
117
|
+
}
|
|
118
|
+
return { secrets, missing };
|
|
119
|
+
}
|
|
120
|
+
/**
|
|
121
|
+
* An instance's secrets: its own when it carries them (a dashboard instance, integration-setup),
|
|
122
|
+
* else read from `env` by its plugin's declared names (an env default instance, AD-089).
|
|
123
|
+
*/
|
|
124
|
+
export function instanceSecrets(instance, env) {
|
|
125
|
+
if (instance.secrets === undefined)
|
|
126
|
+
return readSecrets(instance.plugin, env);
|
|
127
|
+
const missing = instance.plugin.secrets.filter((n) => (instance.secrets[n] ?? '') === '');
|
|
128
|
+
return { secrets: { ...instance.secrets }, missing };
|
|
129
|
+
}
|
|
130
|
+
/** Every instance of `plugin` on the factory, by name: what a slot of that plugin may bind to. */
|
|
131
|
+
export function slotChoices(factory, plugin) {
|
|
132
|
+
return Object.values(factory.instances)
|
|
133
|
+
.filter((i) => i.plugin.id === plugin)
|
|
134
|
+
.map((i) => i.name)
|
|
135
|
+
.sort();
|
|
136
|
+
}
|
|
137
|
+
/**
|
|
138
|
+
* A workflow's slots bound to instances and its settings resolved (door 8, AD-087). A slot binds to
|
|
139
|
+
* its dashboard binding (`stored`), else the single instance of its plugin; a setting reads the
|
|
140
|
+
* dashboard, else the manifest default (AD-089). Keys the manifest does not declare are ignored. A
|
|
141
|
+
* binding to an instance that is gone or of another plugin binds nothing: it does not fall through
|
|
142
|
+
* to auto-bind, and keeps its source in `bindingSources`.
|
|
143
|
+
*/
|
|
144
|
+
export function resolveWorkflow(manifest, factory, stored) {
|
|
145
|
+
const where = `the dashboard (Workflows > ${manifest.id})`;
|
|
146
|
+
const out = { bindings: {}, bindingSources: {}, settings: {}, settingSources: {}, unbound: [], missing: [], problems: [] };
|
|
147
|
+
for (const [slot, { plugin }] of Object.entries(manifest.plugins ?? {})) {
|
|
148
|
+
const choices = slotChoices(factory, plugin);
|
|
149
|
+
const chosen = [
|
|
150
|
+
[stored?.bind[slot], 'dashboard'],
|
|
151
|
+
[choices.length === 1 ? choices[0] : undefined, 'auto'],
|
|
152
|
+
];
|
|
153
|
+
const found = chosen.find(([n]) => n !== undefined);
|
|
154
|
+
const instance = found === undefined ? undefined : factory.instances[found[0]];
|
|
155
|
+
if (found === undefined) {
|
|
156
|
+
out.unbound.push(slot);
|
|
157
|
+
out.problems.push(`plugins.${slot}: slot "${slot}" needs an instance of ${plugin}; bind one on ${where}`);
|
|
158
|
+
}
|
|
159
|
+
else if (instance === undefined || instance.plugin.id !== plugin) {
|
|
160
|
+
out.unbound.push(slot);
|
|
161
|
+
out.bindingSources[slot] = found[1];
|
|
162
|
+
out.problems.push(`plugins.${slot}: slot "${slot}" is bound to ${found[0]}, which is not an instance of ${plugin}; bind one on ${where}`);
|
|
163
|
+
}
|
|
164
|
+
else {
|
|
165
|
+
out.bindings[slot] = { instance: instance.name, plugin, config: instance.config };
|
|
166
|
+
out.bindingSources[slot] = found[1];
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
for (const [name, spec] of Object.entries(manifest.settings ?? {})) {
|
|
170
|
+
const chosen = [
|
|
171
|
+
[stored?.settings[name], 'dashboard'],
|
|
172
|
+
[spec.default, 'default'],
|
|
173
|
+
];
|
|
174
|
+
const found = chosen.find(([v]) => v !== undefined);
|
|
175
|
+
if (found === undefined) {
|
|
176
|
+
out.missing.push(name);
|
|
177
|
+
out.problems.push(`settings.${name}: setting "${name}" has no value and no default; set it on ${where}`);
|
|
178
|
+
}
|
|
179
|
+
else {
|
|
180
|
+
out.settings[name] = found[0];
|
|
181
|
+
out.settingSources[name] = found[1];
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
return out;
|
|
185
|
+
}
|
|
186
|
+
/** The replay window of door 4. */
|
|
187
|
+
export const REPLAY_WINDOW_MS = 60_000;
|
|
188
|
+
/**
|
|
189
|
+
* Verifies, checks the replay window, normalises and checks each event against the plugin's
|
|
190
|
+
* schemas (plugins.md, Plugin host "Ingress"). The caller has already checked the token and size.
|
|
191
|
+
*/
|
|
192
|
+
export function ingest(instance, secrets, raw, now) {
|
|
193
|
+
const { plugin } = instance;
|
|
194
|
+
let body;
|
|
195
|
+
let parsed = true;
|
|
196
|
+
try {
|
|
197
|
+
body = JSON.parse(raw.rawBody);
|
|
198
|
+
}
|
|
199
|
+
catch {
|
|
200
|
+
parsed = false;
|
|
201
|
+
}
|
|
202
|
+
const req = { headers: raw.headers, rawBody: raw.rawBody, body };
|
|
203
|
+
if (!plugin.ingress.verify(req, { secrets, config: instance.config }))
|
|
204
|
+
return { kind: 'rejected', reason: 'signature' };
|
|
205
|
+
if (!parsed)
|
|
206
|
+
return { kind: 'invalid', message: 'body is not valid JSON' };
|
|
207
|
+
const sent = plugin.ingress.timestamp?.(req);
|
|
208
|
+
if (sent !== undefined && Math.abs(now - sent) > REPLAY_WINDOW_MS)
|
|
209
|
+
return { kind: 'rejected', reason: 'stale' };
|
|
210
|
+
if (plugin.ingress.timestamp !== undefined && sent === undefined)
|
|
211
|
+
return { kind: 'rejected', reason: 'stale' };
|
|
212
|
+
let events;
|
|
213
|
+
try {
|
|
214
|
+
events = plugin.ingress.normalize(req, { config: instance.config });
|
|
215
|
+
}
|
|
216
|
+
catch (err) {
|
|
217
|
+
return { kind: 'invalid', message: `could not normalise: ${err instanceof Error ? err.message : String(err)}` };
|
|
218
|
+
}
|
|
219
|
+
for (const e of events) {
|
|
220
|
+
const schema = plugin.events[e.type];
|
|
221
|
+
if (schema === undefined)
|
|
222
|
+
return { kind: 'invalid', message: `${plugin.id} has no event "${e.type}"` };
|
|
223
|
+
const r = schema.safeParse(e.data);
|
|
224
|
+
if (!r.success) {
|
|
225
|
+
const msg = r.error.issues.map((i) => `${i.path.join('.') || '(data)'}: ${i.message}`).join('; ');
|
|
226
|
+
return { kind: 'invalid', message: `${e.type}: ${msg}` };
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
// the instance an event came from is the host's to say (plugins.md, "source.instance")
|
|
230
|
+
const stamped = events.map((e) => ({ type: e.type, data: { instance: instance.name, ...e.data } }));
|
|
231
|
+
return { kind: 'ok', events: stamped, dedupKey: plugin.ingress.dedupKey(req) };
|
|
232
|
+
}
|
|
233
|
+
/** Door 10's `argsSummary`: the JSON of the args, cut to 500 chars with `…`. */
|
|
234
|
+
export function argsSummary(args) {
|
|
235
|
+
let json;
|
|
236
|
+
try {
|
|
237
|
+
json = JSON.stringify(args) ?? '[]';
|
|
238
|
+
}
|
|
239
|
+
catch {
|
|
240
|
+
json = '[unserialisable]';
|
|
241
|
+
}
|
|
242
|
+
return cut(json, ARGS_SUMMARY_MAX);
|
|
243
|
+
}
|
|
244
|
+
/** How long a plugin action may run (door 10). */
|
|
245
|
+
export const ACTION_TIMEOUT_MS = 30_000;
|
|
246
|
+
/**
|
|
247
|
+
* Runs one action with door 10's timeout: the result, or an error naming the cause (`timeout`
|
|
248
|
+
* when it ran out). Only the server calls it (AD-048); a call is never retried.
|
|
249
|
+
*/
|
|
250
|
+
export async function callAction(fn, args, timeoutMs = ACTION_TIMEOUT_MS) {
|
|
251
|
+
let timer;
|
|
252
|
+
const timeout = new Promise((_ok, fail) => {
|
|
253
|
+
timer = setTimeout(() => fail(new Error('timeout')), timeoutMs);
|
|
254
|
+
});
|
|
255
|
+
try {
|
|
256
|
+
return await Promise.race([fn(...args), timeout]);
|
|
257
|
+
}
|
|
258
|
+
finally {
|
|
259
|
+
clearTimeout(timer);
|
|
260
|
+
}
|
|
261
|
+
}
|
|
262
|
+
/** The names of a plugin's actions, built with no secret and a fetch that refuses (the worker's proxy). */
|
|
263
|
+
export function actionNames(plugin, config) {
|
|
264
|
+
const refuse = (() => Promise.reject(new Error('actions run on the server')));
|
|
265
|
+
return Object.keys(plugin.actions({ config, secrets: {}, fetch: refuse }));
|
|
266
|
+
}
|
|
267
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,gBAAgB,EAAE,GAAG,EAAiB,MAAM,mBAAmB,CAAC;AA2CzE,MAAM,CAAC,MAAM,aAAa,GAAkB,EAAE,SAAS,EAAE,EAAE,EAAE,CAAC;AAE9D,uGAAuG;AACvG,MAAM,OAAO,kBAAmB,SAAQ,KAAK;IAClC,IAAI,GAAG,oBAAoB,CAAC;CACtC;AAED,oCAAoC;AACpC,MAAM,CAAC,MAAM,cAAc,GAAG,EAAE,CAAC;AACjC,MAAM,QAAQ,GAAG,mBAAmB,CAAC;AAErC,MAAM,IAAI,GAAG,CAAC,IAAY,EAAE,QAAkB,EAAS,EAAE;IACvD,MAAM,IAAI,kBAAkB,CAAC,GAAG,IAAI,QAAQ,QAAQ,CAAC,IAAI,CAAC,MAAM,CAAC,EAAE,CAAC,CAAC;AACvE,CAAC,CAAC;AAEF,qDAAqD;AACrD,MAAM,KAAK,GAAG,CAAC,GAAsB,EAAE,IAAY,EAAsB,EAAE;IACzE,MAAM,CAAC,GAAG,GAAG,CAAC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AAK,CAAC,CAAC;IACtB,CAAC;AACH,CAAC;AAED,2GAA2G;AAC3G,MAAM,UAAU,WAAW,CAAC,MAAiB,EAAE,MAAe;IAC5D,MAAM,MAAM,GAAG,CAAC,GAAG,EAAE,CAAC,OAAO,CAAC,MAAM,CAAC,IAAI,KAAK,CAAC,2BAA2B,CAAC,CAAC,CAAiB,CAAC;IAC9F,OAAO,MAAM,CAAC,IAAI,CAAC,MAAM,CAAC,OAAO,CAAC,EAAE,MAAM,EAAE,OAAO,EAAE,EAAE,EAAE,KAAK,EAAE,MAAM,EAAE,CAAC,CAAC,CAAC;AAC7E,CAAC"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,39 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@artieeez/cf-plugin-host",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"type": "module",
|
|
5
|
+
"exports": {
|
|
6
|
+
".": {
|
|
7
|
+
"types": "./dist/index.d.ts",
|
|
8
|
+
"default": "./dist/index.js"
|
|
9
|
+
}
|
|
10
|
+
},
|
|
11
|
+
"files": [
|
|
12
|
+
"dist",
|
|
13
|
+
"src",
|
|
14
|
+
"!dist/.tsbuildinfo"
|
|
15
|
+
],
|
|
16
|
+
"publishConfig": {
|
|
17
|
+
"access": "public"
|
|
18
|
+
},
|
|
19
|
+
"engines": {
|
|
20
|
+
"node": ">=22.18.0"
|
|
21
|
+
},
|
|
22
|
+
"repository": {
|
|
23
|
+
"type": "git",
|
|
24
|
+
"url": "git+https://github.com/artieeez/code-factory.git",
|
|
25
|
+
"directory": "packages/plugin-host"
|
|
26
|
+
},
|
|
27
|
+
"dependencies": {
|
|
28
|
+
"zod": "^4.6.7",
|
|
29
|
+
"@artieeez/cf-core": "0.1.0",
|
|
30
|
+
"@artieeez/cf-sdk": "0.1.0"
|
|
31
|
+
},
|
|
32
|
+
"devDependencies": {
|
|
33
|
+
"@artieeez/cf-plugin-linear": "0.1.0"
|
|
34
|
+
},
|
|
35
|
+
"scripts": {
|
|
36
|
+
"build": "tsc -b tsconfig.build.json",
|
|
37
|
+
"test": "vitest run --root ../.. --project unit packages/plugin-host/"
|
|
38
|
+
}
|
|
6
39
|
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,344 @@
|
|
|
1
|
+
import { ARGS_SUMMARY_MAX, cut, type Manifest } from '@artieeez/cf-core';
|
|
2
|
+
import type { IngressRequest, NormalizedEvent, PluginActions, PluginDefinition } from '@artieeez/cf-sdk/plugin';
|
|
3
|
+
|
|
4
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- a host loads plugins of any config type
|
|
5
|
+
export type AnyPlugin = PluginDefinition<any, PluginActions>;
|
|
6
|
+
|
|
7
|
+
/** One plugin instance: a plugin wired to an account and a scope; today the default one each plugin's env makes (AD-089). */
|
|
8
|
+
export interface Instance {
|
|
9
|
+
name: string;
|
|
10
|
+
plugin: AnyPlugin;
|
|
11
|
+
config: unknown;
|
|
12
|
+
/** the URL token of `/hooks/<instance>/<token>`; none: the instance has no webhook */
|
|
13
|
+
hookToken: string | undefined;
|
|
14
|
+
/**
|
|
15
|
+
* its own secrets by their declared names, when it was set up on the dashboard (integration-setup
|
|
16
|
+
* door 1); absent: an env default instance, whose secrets are read from env by those names
|
|
17
|
+
*/
|
|
18
|
+
secrets?: Record<string, string>;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/** A workflow's slot bindings and setting values, as the dashboard stored them (AD-087). */
|
|
22
|
+
export interface WorkflowConfig {
|
|
23
|
+
bind: Record<string, string>;
|
|
24
|
+
settings: Record<string, string>;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** How people sign in (oidc-login door 5): one OIDC issuer and how its claims map to roles, from `CF_OIDC_*` (AD-089). */
|
|
28
|
+
export interface OidcConfig {
|
|
29
|
+
issuer: string;
|
|
30
|
+
clientId: string;
|
|
31
|
+
clientSecret: string;
|
|
32
|
+
/** the ID token claim whose values are matched against `roles`; `groups` by default */
|
|
33
|
+
rolesClaim: string;
|
|
34
|
+
roles: { admin: string[]; operator: string[]; viewer: string[] };
|
|
35
|
+
/** emails that are admin whatever their claims */
|
|
36
|
+
bootstrapAdmins: string[];
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** The factory's plugin instances (AD-089): no file, each built from its plugin's env. */
|
|
40
|
+
export interface FactoryConfig {
|
|
41
|
+
instances: Record<string, Instance>;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export const EMPTY_FACTORY: FactoryConfig = { instances: {} };
|
|
45
|
+
|
|
46
|
+
/** The factory's env cannot be used; the message has one line per problem, each naming its env var. */
|
|
47
|
+
export class FactoryConfigError extends Error {
|
|
48
|
+
override name = 'FactoryConfigError';
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/** Shortest hook token (door 6). */
|
|
52
|
+
export const HOOK_TOKEN_MIN = 24;
|
|
53
|
+
const INSTANCE = /^[a-z][a-z0-9-]*$/;
|
|
54
|
+
|
|
55
|
+
const fail = (what: string, problems: string[]): never => {
|
|
56
|
+
throw new FactoryConfigError(`${what}:\n- ${problems.join('\n- ')}`);
|
|
57
|
+
};
|
|
58
|
+
|
|
59
|
+
/** An env value, `undefined` when unset or empty. */
|
|
60
|
+
const envOf = (env: NodeJS.ProcessEnv, name: string): string | undefined => {
|
|
61
|
+
const v = env[name];
|
|
62
|
+
return v === undefined || v === '' ? undefined : v;
|
|
63
|
+
};
|
|
64
|
+
|
|
65
|
+
/** `CF_<PLUGIN>`: the prefix of a plugin's own env names, its id upper-cased with dashes as underscores. */
|
|
66
|
+
export function pluginEnvPrefix(plugin: AnyPlugin): string {
|
|
67
|
+
return `CF_${plugin.id.toUpperCase().replace(/-/g, '_')}`;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* The default instance of each plugin whose `configEnv` has any name set (AD-089): named
|
|
72
|
+
* `CF_<PLUGIN>_INSTANCE` (default its id), its config parsed from those env values, its hook token
|
|
73
|
+
* `CF_<PLUGIN>_HOOK_TOKEN` (none: no webhook). Anything wrong throws `FactoryConfigError` with one
|
|
74
|
+
* line per problem naming the env var.
|
|
75
|
+
*/
|
|
76
|
+
export function loadEnvInstances(env: NodeJS.ProcessEnv, plugins: readonly AnyPlugin[]): FactoryConfig {
|
|
77
|
+
const instances: Record<string, Instance> = {};
|
|
78
|
+
const problems: string[] = [];
|
|
79
|
+
for (const plugin of plugins) {
|
|
80
|
+
const names = Object.entries(plugin.configEnv ?? {});
|
|
81
|
+
if (!names.some(([, name]) => envOf(env, name) !== undefined)) continue;
|
|
82
|
+
const prefix = pluginEnvPrefix(plugin);
|
|
83
|
+
const nameVar = `${prefix}_INSTANCE`;
|
|
84
|
+
const name = envOf(env, nameVar) ?? plugin.id;
|
|
85
|
+
let ok = true;
|
|
86
|
+
if (!INSTANCE.test(name)) {
|
|
87
|
+
problems.push(`${nameVar}: instance names are lowercase slugs, got "${name}"`);
|
|
88
|
+
ok = false;
|
|
89
|
+
} else if (instances[name] !== undefined) {
|
|
90
|
+
problems.push(`${nameVar}: "${name}" is already the instance of ${instances[name].plugin.id}`);
|
|
91
|
+
ok = false;
|
|
92
|
+
}
|
|
93
|
+
const raw: Record<string, string> = {};
|
|
94
|
+
const unset = new Set<string>();
|
|
95
|
+
for (const [key, envName] of names) {
|
|
96
|
+
const v = envOf(env, envName);
|
|
97
|
+
if (v === undefined) {
|
|
98
|
+
unset.add(key);
|
|
99
|
+
problems.push(`${envName}: is not set`);
|
|
100
|
+
} else raw[key] = v;
|
|
101
|
+
}
|
|
102
|
+
const parsed = plugin.config.safeParse(raw);
|
|
103
|
+
if (!parsed.success) {
|
|
104
|
+
for (const issue of parsed.error.issues) {
|
|
105
|
+
const key = issue.path[0];
|
|
106
|
+
if (typeof key === 'string' && unset.has(key)) continue;
|
|
107
|
+
const envName = typeof key === 'string' ? plugin.configEnv?.[key] : undefined;
|
|
108
|
+
problems.push(`${envName ?? `${plugin.id} config ${issue.path.join('.') || '(root)'}`}: ${issue.message}`);
|
|
109
|
+
}
|
|
110
|
+
ok = false;
|
|
111
|
+
}
|
|
112
|
+
const tokenVar = `${prefix}_HOOK_TOKEN`;
|
|
113
|
+
const hookToken = envOf(env, tokenVar);
|
|
114
|
+
if (hookToken !== undefined && hookToken.length < HOOK_TOKEN_MIN) {
|
|
115
|
+
problems.push(`${tokenVar}: must be at least ${HOOK_TOKEN_MIN} chars`);
|
|
116
|
+
ok = false;
|
|
117
|
+
}
|
|
118
|
+
if (ok && unset.size === 0 && parsed.success) instances[name] = { name, plugin, config: parsed.data, hookToken };
|
|
119
|
+
}
|
|
120
|
+
if (problems.length > 0) fail('plugin env', problems);
|
|
121
|
+
return { instances };
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/** A comma list from env: split, trimmed, empty items dropped. */
|
|
125
|
+
const listOf = (env: NodeJS.ProcessEnv, name: string): string[] =>
|
|
126
|
+
(env[name] ?? '')
|
|
127
|
+
.split(',')
|
|
128
|
+
.map((s) => s.trim())
|
|
129
|
+
.filter((s) => s !== '');
|
|
130
|
+
|
|
131
|
+
/**
|
|
132
|
+
* People's sign-in from `CF_OIDC_*` (AD-089): none without `CF_OIDC_ISSUER`; with it, a missing
|
|
133
|
+
* `CF_OIDC_CLIENT_ID` or `CF_OIDC_CLIENT_SECRET` throws `FactoryConfigError` naming it.
|
|
134
|
+
*/
|
|
135
|
+
export function readOidcEnv(env: NodeJS.ProcessEnv): OidcConfig | undefined {
|
|
136
|
+
const issuer = envOf(env, 'CF_OIDC_ISSUER');
|
|
137
|
+
if (issuer === undefined) return undefined;
|
|
138
|
+
const missing = ['CF_OIDC_CLIENT_ID', 'CF_OIDC_CLIENT_SECRET'].filter((n) => envOf(env, n) === undefined);
|
|
139
|
+
if (missing.length > 0) fail('sign-in env (CF_OIDC_ISSUER is set)', missing.map((n) => `${n}: is not set`));
|
|
140
|
+
return {
|
|
141
|
+
issuer,
|
|
142
|
+
clientId: env['CF_OIDC_CLIENT_ID']!,
|
|
143
|
+
clientSecret: env['CF_OIDC_CLIENT_SECRET']!,
|
|
144
|
+
rolesClaim: envOf(env, 'CF_OIDC_ROLES_CLAIM') ?? 'groups',
|
|
145
|
+
roles: { admin: listOf(env, 'CF_OIDC_ADMIN_GROUPS'), operator: listOf(env, 'CF_OIDC_OPERATOR_GROUPS'), viewer: listOf(env, 'CF_OIDC_VIEWER_GROUPS') },
|
|
146
|
+
bootstrapAdmins: listOf(env, 'CF_OIDC_BOOTSTRAP_ADMINS'),
|
|
147
|
+
};
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
/** A plugin's secrets read from `env` by their declared names; the names it lacks in `missing`. */
|
|
151
|
+
export function readSecrets(plugin: AnyPlugin, env: NodeJS.ProcessEnv): { secrets: Record<string, string>; missing: string[] } {
|
|
152
|
+
const secrets: Record<string, string> = {};
|
|
153
|
+
const missing: string[] = [];
|
|
154
|
+
for (const name of plugin.secrets) {
|
|
155
|
+
const v = env[name];
|
|
156
|
+
if (v === undefined || v === '') missing.push(name);
|
|
157
|
+
else secrets[name] = v;
|
|
158
|
+
}
|
|
159
|
+
return { secrets, missing };
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
/**
|
|
163
|
+
* An instance's secrets: its own when it carries them (a dashboard instance, integration-setup),
|
|
164
|
+
* else read from `env` by its plugin's declared names (an env default instance, AD-089).
|
|
165
|
+
*/
|
|
166
|
+
export function instanceSecrets(instance: Instance, env: NodeJS.ProcessEnv): { secrets: Record<string, string>; missing: string[] } {
|
|
167
|
+
if (instance.secrets === undefined) return readSecrets(instance.plugin, env);
|
|
168
|
+
const missing = instance.plugin.secrets.filter((n) => (instance.secrets![n] ?? '') === '');
|
|
169
|
+
return { secrets: { ...instance.secrets }, missing };
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
/** What a unit learns of a slot (door 8): never a secret. */
|
|
173
|
+
export interface Binding {
|
|
174
|
+
instance: string;
|
|
175
|
+
plugin: string;
|
|
176
|
+
config: unknown;
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
/** Where a slot's instance came from (AD-087, AD-089): the dashboard, or the single instance of its plugin. */
|
|
180
|
+
export type BindingSource = 'dashboard' | 'auto';
|
|
181
|
+
/** Where a setting's value came from (AD-087, AD-089): the dashboard, or the manifest default. */
|
|
182
|
+
export type SettingSource = 'dashboard' | 'default';
|
|
183
|
+
|
|
184
|
+
/** A workflow's slots and settings as resolved here (door 8, AD-087). */
|
|
185
|
+
export interface ResolvedWorkflow {
|
|
186
|
+
/** what a unit learns of each bound slot */
|
|
187
|
+
bindings: Record<string, Binding>;
|
|
188
|
+
/**
|
|
189
|
+
* per slot with a chosen instance, where the choice came from; also when that instance is gone or
|
|
190
|
+
* of another plugin (the slot is then unbound), so the dashboard can clear a stale choice
|
|
191
|
+
*/
|
|
192
|
+
bindingSources: Record<string, BindingSource>;
|
|
193
|
+
settings: Record<string, string>;
|
|
194
|
+
/** per valued setting, where its value came from */
|
|
195
|
+
settingSources: Record<string, SettingSource>;
|
|
196
|
+
/** the declared slots bound to no instance */
|
|
197
|
+
unbound: string[];
|
|
198
|
+
/** the declared settings with no value and no default */
|
|
199
|
+
missing: string[];
|
|
200
|
+
/** one line per unbound slot or missing setting; empty when the workflow can run */
|
|
201
|
+
problems: string[];
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
/** Every instance of `plugin` on the factory, by name: what a slot of that plugin may bind to. */
|
|
205
|
+
export function slotChoices(factory: FactoryConfig, plugin: string): string[] {
|
|
206
|
+
return Object.values(factory.instances)
|
|
207
|
+
.filter((i) => i.plugin.id === plugin)
|
|
208
|
+
.map((i) => i.name)
|
|
209
|
+
.sort();
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
/**
|
|
213
|
+
* A workflow's slots bound to instances and its settings resolved (door 8, AD-087). A slot binds to
|
|
214
|
+
* its dashboard binding (`stored`), else the single instance of its plugin; a setting reads the
|
|
215
|
+
* dashboard, else the manifest default (AD-089). Keys the manifest does not declare are ignored. A
|
|
216
|
+
* binding to an instance that is gone or of another plugin binds nothing: it does not fall through
|
|
217
|
+
* to auto-bind, and keeps its source in `bindingSources`.
|
|
218
|
+
*/
|
|
219
|
+
export function resolveWorkflow(manifest: Manifest, factory: FactoryConfig, stored?: WorkflowConfig): ResolvedWorkflow {
|
|
220
|
+
const where = `the dashboard (Workflows > ${manifest.id})`;
|
|
221
|
+
const out: ResolvedWorkflow = { bindings: {}, bindingSources: {}, settings: {}, settingSources: {}, unbound: [], missing: [], problems: [] };
|
|
222
|
+
for (const [slot, { plugin }] of Object.entries(manifest.plugins ?? {})) {
|
|
223
|
+
const choices = slotChoices(factory, plugin);
|
|
224
|
+
const chosen: [string | undefined, BindingSource][] = [
|
|
225
|
+
[stored?.bind[slot], 'dashboard'],
|
|
226
|
+
[choices.length === 1 ? choices[0] : undefined, 'auto'],
|
|
227
|
+
];
|
|
228
|
+
const found = chosen.find(([n]) => n !== undefined);
|
|
229
|
+
const instance = found === undefined ? undefined : factory.instances[found[0]!];
|
|
230
|
+
if (found === undefined) {
|
|
231
|
+
out.unbound.push(slot);
|
|
232
|
+
out.problems.push(`plugins.${slot}: slot "${slot}" needs an instance of ${plugin}; bind one on ${where}`);
|
|
233
|
+
} else if (instance === undefined || instance.plugin.id !== plugin) {
|
|
234
|
+
out.unbound.push(slot);
|
|
235
|
+
out.bindingSources[slot] = found[1];
|
|
236
|
+
out.problems.push(`plugins.${slot}: slot "${slot}" is bound to ${found[0]!}, which is not an instance of ${plugin}; bind one on ${where}`);
|
|
237
|
+
} else {
|
|
238
|
+
out.bindings[slot] = { instance: instance.name, plugin, config: instance.config };
|
|
239
|
+
out.bindingSources[slot] = found[1];
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
for (const [name, spec] of Object.entries(manifest.settings ?? {})) {
|
|
243
|
+
const chosen: [string | undefined, SettingSource][] = [
|
|
244
|
+
[stored?.settings[name], 'dashboard'],
|
|
245
|
+
[spec.default, 'default'],
|
|
246
|
+
];
|
|
247
|
+
const found = chosen.find(([v]) => v !== undefined);
|
|
248
|
+
if (found === undefined) {
|
|
249
|
+
out.missing.push(name);
|
|
250
|
+
out.problems.push(`settings.${name}: setting "${name}" has no value and no default; set it on ${where}`);
|
|
251
|
+
} else {
|
|
252
|
+
out.settings[name] = found[0]!;
|
|
253
|
+
out.settingSources[name] = found[1];
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
return out;
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
/** The replay window of door 4. */
|
|
260
|
+
export const REPLAY_WINDOW_MS = 60_000;
|
|
261
|
+
|
|
262
|
+
export type IngestResult =
|
|
263
|
+
| { kind: 'rejected'; reason: 'signature' | 'stale' }
|
|
264
|
+
| { kind: 'invalid'; message: string }
|
|
265
|
+
| { kind: 'ok'; events: NormalizedEvent[]; dedupKey: string | undefined };
|
|
266
|
+
|
|
267
|
+
/**
|
|
268
|
+
* Verifies, checks the replay window, normalises and checks each event against the plugin's
|
|
269
|
+
* schemas (plugins.md, Plugin host "Ingress"). The caller has already checked the token and size.
|
|
270
|
+
*/
|
|
271
|
+
export function ingest(instance: Instance, secrets: Record<string, string>, raw: { headers: Record<string, string | undefined>; rawBody: string }, now: number): IngestResult {
|
|
272
|
+
const { plugin } = instance;
|
|
273
|
+
let body: unknown;
|
|
274
|
+
let parsed = true;
|
|
275
|
+
try {
|
|
276
|
+
body = JSON.parse(raw.rawBody);
|
|
277
|
+
} catch {
|
|
278
|
+
parsed = false;
|
|
279
|
+
}
|
|
280
|
+
const req: IngressRequest = { headers: raw.headers, rawBody: raw.rawBody, body };
|
|
281
|
+
if (!plugin.ingress.verify(req, { secrets, config: instance.config })) return { kind: 'rejected', reason: 'signature' };
|
|
282
|
+
if (!parsed) return { kind: 'invalid', message: 'body is not valid JSON' };
|
|
283
|
+
const sent = plugin.ingress.timestamp?.(req);
|
|
284
|
+
if (sent !== undefined && Math.abs(now - sent) > REPLAY_WINDOW_MS) return { kind: 'rejected', reason: 'stale' };
|
|
285
|
+
if (plugin.ingress.timestamp !== undefined && sent === undefined) return { kind: 'rejected', reason: 'stale' };
|
|
286
|
+
let events: NormalizedEvent[];
|
|
287
|
+
try {
|
|
288
|
+
events = plugin.ingress.normalize(req, { config: instance.config });
|
|
289
|
+
} catch (err) {
|
|
290
|
+
return { kind: 'invalid', message: `could not normalise: ${err instanceof Error ? err.message : String(err)}` };
|
|
291
|
+
}
|
|
292
|
+
for (const e of events) {
|
|
293
|
+
const schema = plugin.events[e.type];
|
|
294
|
+
if (schema === undefined) return { kind: 'invalid', message: `${plugin.id} has no event "${e.type}"` };
|
|
295
|
+
const r = schema.safeParse(e.data);
|
|
296
|
+
if (!r.success) {
|
|
297
|
+
const msg = r.error.issues.map((i) => `${i.path.join('.') || '(data)'}: ${i.message}`).join('; ');
|
|
298
|
+
return { kind: 'invalid', message: `${e.type}: ${msg}` };
|
|
299
|
+
}
|
|
300
|
+
}
|
|
301
|
+
// the instance an event came from is the host's to say (plugins.md, "source.instance")
|
|
302
|
+
const stamped = events.map((e) => ({ type: e.type, data: { instance: instance.name, ...e.data } }));
|
|
303
|
+
return { kind: 'ok', events: stamped, dedupKey: plugin.ingress.dedupKey(req) };
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
/** Door 10's `argsSummary`: the JSON of the args, cut to 500 chars with `…`. */
|
|
307
|
+
export function argsSummary(args: unknown[]): string {
|
|
308
|
+
let json: string;
|
|
309
|
+
try {
|
|
310
|
+
json = JSON.stringify(args) ?? '[]';
|
|
311
|
+
} catch {
|
|
312
|
+
json = '[unserialisable]';
|
|
313
|
+
}
|
|
314
|
+
return cut(json, ARGS_SUMMARY_MAX);
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
/** How long a plugin action may run (door 10). */
|
|
318
|
+
export const ACTION_TIMEOUT_MS = 30_000;
|
|
319
|
+
|
|
320
|
+
/**
|
|
321
|
+
* Runs one action with door 10's timeout: the result, or an error naming the cause (`timeout`
|
|
322
|
+
* when it ran out). Only the server calls it (AD-048); a call is never retried.
|
|
323
|
+
*/
|
|
324
|
+
export async function callAction(
|
|
325
|
+
fn: (...args: unknown[]) => Promise<unknown>,
|
|
326
|
+
args: unknown[],
|
|
327
|
+
timeoutMs: number = ACTION_TIMEOUT_MS,
|
|
328
|
+
): Promise<unknown> {
|
|
329
|
+
let timer: NodeJS.Timeout | undefined;
|
|
330
|
+
const timeout = new Promise<never>((_ok, fail) => {
|
|
331
|
+
timer = setTimeout(() => fail(new Error('timeout')), timeoutMs);
|
|
332
|
+
});
|
|
333
|
+
try {
|
|
334
|
+
return await Promise.race([fn(...args), timeout]);
|
|
335
|
+
} finally {
|
|
336
|
+
clearTimeout(timer);
|
|
337
|
+
}
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
/** The names of a plugin's actions, built with no secret and a fetch that refuses (the worker's proxy). */
|
|
341
|
+
export function actionNames(plugin: AnyPlugin, config: unknown): string[] {
|
|
342
|
+
const refuse = (() => Promise.reject(new Error('actions run on the server'))) as typeof fetch;
|
|
343
|
+
return Object.keys(plugin.actions({ config, secrets: {}, fetch: refuse }));
|
|
344
|
+
}
|