@protobase/workflows 0.68.5 → 0.69.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.
@@ -4,17 +4,19 @@ import { TriggerCheck } from "./check-trigger.js";
4
4
  /**
5
5
  * What a definition is checked against beside the language: the step types (Task resources) the app has, the
6
6
  * arguments each needs (`required`, by step type), its trigger types, each with the check of its input, and why the
7
- * app cannot run a type it knows (`unavailable`, by step or trigger type).
7
+ * app cannot run a type it knows (`unavailable`, by step or trigger type), and the connection `<plugin>:<connection>`
8
+ * each type that signs in uses (`connections`, by step or trigger type); without it the bindings are not checked.
8
9
  */
9
10
  export type CheckOptions = {
10
11
  resources: readonly string[];
11
12
  required?: Readonly<Record<string, readonly string[]>>;
12
13
  triggers: Readonly<Record<string, TriggerCheck>>;
13
14
  unavailable?: Readonly<Record<string, string>>;
15
+ connections?: Readonly<Record<string, string>>;
14
16
  };
15
17
  /**
16
18
  * Why a definition cannot be saved, as it is checked on every save: its size and nesting, its shape against `definitionSchema`, its
17
- * trigger, then each edge, each Task's step type and what each expression reads, in the named-reads profile. Empty when
19
+ * trigger and the connections it binds, then each edge, each Task's step type and what each expression reads, in the named-reads profile. Empty when
18
20
  * it can be saved.
19
21
  */
20
22
  export declare const checkDefinition: (definition: unknown, options: CheckOptions) => Problem[];
@@ -7,6 +7,7 @@ import { edges, reachable } from "./graph.js";
7
7
  import { reservedVariables } from "./names.js";
8
8
  import { builtInFunctions } from "./reads.js";
9
9
  import { readProblems } from "./check-reads.js";
10
+ import { connectionProblems } from "./used-connections.js";
10
11
  import { visibleVariables } from "./visible.js";
11
12
  import { nestingDepth } from "../nesting.js";
12
13
  //#region src/definition/check-definition.ts
@@ -104,7 +105,7 @@ const wholeProblems = (definition) => {
104
105
  };
105
106
  /**
106
107
  * Why a definition cannot be saved, as it is checked on every save: its size and nesting, its shape against `definitionSchema`, its
107
- * trigger, then each edge, each Task's step type and what each expression reads, in the named-reads profile. Empty when
108
+ * trigger and the connections it binds, then each edge, each Task's step type and what each expression reads, in the named-reads profile. Empty when
108
109
  * it can be saved.
109
110
  */
110
111
  const checkDefinition = (definition, options) => {
@@ -116,6 +117,7 @@ const checkDefinition = (definition, options) => {
116
117
  const document = definition;
117
118
  return [
118
119
  ...triggerProblems(document.trigger, options.triggers, options.unavailable),
120
+ ...options.connections ? connectionProblems(document, options.connections) : [],
119
121
  ...wholeProblems(document),
120
122
  ...machineProblems(document.stateMachine, {
121
123
  path: [],
@@ -45,6 +45,20 @@ export declare const definitionSchema: {
45
45
  readonly stateMachine: {
46
46
  readonly $ref: "#/definitions/stateMachine";
47
47
  };
48
+ readonly connections: {
49
+ readonly $ref: "#/definitions/connections";
50
+ };
51
+ };
52
+ };
53
+ readonly connections: {
54
+ readonly type: "object";
55
+ readonly propertyNames: {
56
+ readonly pattern: "^[a-z][a-z0-9_]*:[a-z][a-z0-9_]*$";
57
+ };
58
+ readonly additionalProperties: {
59
+ readonly type: "string";
60
+ readonly minLength: 1;
61
+ readonly maxLength: 255;
48
62
  };
49
63
  };
50
64
  readonly trigger: {
@@ -126,7 +126,17 @@ const definitionSchema = {
126
126
  required: ["trigger", "stateMachine"],
127
127
  properties: {
128
128
  trigger: { $ref: "#/definitions/trigger" },
129
- stateMachine: { $ref: "#/definitions/stateMachine" }
129
+ stateMachine: { $ref: "#/definitions/stateMachine" },
130
+ connections: { $ref: "#/definitions/connections" }
131
+ }
132
+ },
133
+ connections: {
134
+ type: "object",
135
+ propertyNames: { pattern: "^[a-z][a-z0-9_]*:[a-z][a-z0-9_]*$" },
136
+ additionalProperties: {
137
+ type: "string",
138
+ minLength: 1,
139
+ maxLength: 255
130
140
  }
131
141
  },
132
142
  trigger: {
@@ -84,9 +84,13 @@ export type Trigger = {
84
84
  manual?: Record<string, unknown>;
85
85
  [type: `${string}:${string}`]: Record<string, unknown>;
86
86
  };
87
- /** A workflow definition: its trigger, and the state machine a run runs from `StartAt`. */
87
+ /**
88
+ * A workflow definition: its trigger, the state machine a run runs from `StartAt`, and the connected account each
89
+ * connection `<plugin>:<connection>` of its types signs in with, by the account's id.
90
+ */
88
91
  export type Definition = {
89
92
  trigger: Trigger;
90
93
  stateMachine: StateMachine;
94
+ connections?: Record<string, string>;
91
95
  };
92
96
  //#endregion
@@ -0,0 +1,8 @@
1
+ import { Definition } from "./types.js";
2
+ //#region src/definition/used-connections.d.ts
3
+ /**
4
+ * The connections `<plugin>:<connection>` a definition's trigger and steps sign in with, given the connection each
5
+ * type uses by its id (`connectionOf`).
6
+ */
7
+ export declare const usedConnections: (definition: Definition, connectionOf: Readonly<Record<string, string>>) => Set<string>;
8
+ //#endregion
@@ -0,0 +1,20 @@
1
+ //#region src/definition/used-connections.ts
2
+ const resources = (machine) => Object.values(machine.States).flatMap((state) => state.Type === "Task" ? [state.Resource] : state.Type === "Map" ? resources(state.ItemProcessor) : []);
3
+ /**
4
+ * The connections `<plugin>:<connection>` a definition's trigger and steps sign in with, given the connection each
5
+ * type uses by its id (`connectionOf`).
6
+ */
7
+ const usedConnections = (definition, connectionOf) => {
8
+ const types = [Object.keys(definition.trigger)[0], ...resources(definition.stateMachine)];
9
+ return new Set(types.flatMap((type) => Object.hasOwn(connectionOf, type) ? [connectionOf[type]] : []));
10
+ };
11
+ /** A binding in `connections` that none of the definition's types signs in with. */
12
+ const connectionProblems = (definition, connectionOf) => {
13
+ const used = usedConnections(definition, connectionOf);
14
+ return Object.keys(definition.connections ?? {}).filter((key) => !used.has(key)).map((key) => ({
15
+ field: `connections.${key}`,
16
+ message: `no trigger or step of this workflow signs in with "${key}"; remove it`
17
+ }));
18
+ };
19
+ //#endregion
20
+ export { connectionProblems, usedConnections };
package/dist/index.d.ts CHANGED
@@ -3,6 +3,7 @@ import { Catcher, ChoiceRule, ChoiceState, Definition, Machine, MapState, Retrie
3
3
  import { TriggerCheck } from "./definition/check-trigger.js";
4
4
  import { CheckOptions, checkDefinition } from "./definition/check-definition.js";
5
5
  import { definitionSchema } from "./definition/schema.js";
6
+ import { usedConnections } from "./definition/used-connections.js";
6
7
  import { limits } from "./limits.js";
7
8
  import { nestingDepth } from "./nesting.js";
8
9
  import { ErrorOutput, StepError } from "./run/errors.js";
@@ -15,5 +16,6 @@ import { LoadedPlugin, loadPlugins } from "./plugin/load-plugins.js";
15
16
  import { StepWiring, stepHandlers } from "./plugin/step-handlers.js";
16
17
  import { triggerChecks } from "./plugin/trigger-checks.js";
17
18
  import { TypeEntry, Unavailable, typeList } from "./plugin/type-list.js";
19
+ import { ConnectionSupport, connectionUnavailable } from "./plugin/connection-availability.js";
18
20
  import { CatalogEntry, TypeCatalog, typeCatalog } from "./plugin/type-catalog.js";
19
- export { type CatalogEntry, type Catcher, type CheckOptions, type ChoiceRule, type ChoiceState, type Definition, type EarlierStep, type ErrorOutput, type LoadedPlugin, type LoadedRun, type Machine, type MapState, type Problem, type Redactor, type Retrier, type RunChange, type RunStatus, type RunStore, type Runner, type RunnerPort, type SavedStep, type SegmentInput, type SegmentQueue, type State, type StateMachine, StepError, type StepLog, type StepRecord, type StepStatus, type StepWiring, type TaskContext, type TaskHandler, type TaskHandlers, type TaskState, type Trigger, type TriggerCheck, type TypeCatalog, type TypeEntry, type Unavailable, checkDefinition, createRunner, definitionSchema, limits, loadPlugins, nestingDepth, problemText, redacted, rerunSteps, runSegment, secretRedactor, shortestSecret, stepHandlers, triggerChecks, typeCatalog, typeList };
21
+ export { type CatalogEntry, type Catcher, type CheckOptions, type ChoiceRule, type ChoiceState, type ConnectionSupport, type Definition, type EarlierStep, type ErrorOutput, type LoadedPlugin, type LoadedRun, type Machine, type MapState, type Problem, type Redactor, type Retrier, type RunChange, type RunStatus, type RunStore, type Runner, type RunnerPort, type SavedStep, type SegmentInput, type SegmentQueue, type State, type StateMachine, StepError, type StepLog, type StepRecord, type StepStatus, type StepWiring, type TaskContext, type TaskHandler, type TaskHandlers, type TaskState, type Trigger, type TriggerCheck, type TypeCatalog, type TypeEntry, type Unavailable, checkDefinition, connectionUnavailable, createRunner, definitionSchema, limits, loadPlugins, nestingDepth, problemText, redacted, rerunSteps, runSegment, secretRedactor, shortestSecret, stepHandlers, triggerChecks, typeCatalog, typeList, usedConnections };
package/dist/index.js CHANGED
@@ -1,6 +1,7 @@
1
1
  import { limits } from "./limits.js";
2
2
  import { definitionSchema } from "./definition/schema.js";
3
3
  import { problemText } from "./definition/problem.js";
4
+ import { usedConnections } from "./definition/used-connections.js";
4
5
  import { nestingDepth } from "./nesting.js";
5
6
  import { checkDefinition } from "./definition/check-definition.js";
6
7
  import { StepError } from "./run/errors.js";
@@ -12,5 +13,6 @@ import { loadPlugins } from "./plugin/load-plugins.js";
12
13
  import { stepHandlers } from "./plugin/step-handlers.js";
13
14
  import { triggerChecks } from "./plugin/trigger-checks.js";
14
15
  import { typeList } from "./plugin/type-list.js";
16
+ import { connectionUnavailable } from "./plugin/connection-availability.js";
15
17
  import { typeCatalog } from "./plugin/type-catalog.js";
16
- export { StepError, checkDefinition, createRunner, definitionSchema, limits, loadPlugins, nestingDepth, problemText, redacted, rerunSteps, runSegment, secretRedactor, shortestSecret, stepHandlers, triggerChecks, typeCatalog, typeList };
18
+ export { StepError, checkDefinition, connectionUnavailable, createRunner, definitionSchema, limits, loadPlugins, nestingDepth, problemText, redacted, rerunSteps, runSegment, secretRedactor, shortestSecret, stepHandlers, triggerChecks, typeCatalog, typeList, usedConnections };
@@ -0,0 +1,14 @@
1
+ import { Unavailable } from "./type-list.js";
2
+ //#region src/plugin/connection-availability.d.ts
3
+ /**
4
+ * What an app can connect accounts with: none without sign-in; otherwise whether it stores OAuth tokens encrypted,
5
+ * its sign-in providers, and the connections `<plugin>:<connection>` whose OAuth client its owner set.
6
+ */
7
+ export type ConnectionSupport = {
8
+ encrypted: boolean;
9
+ signInProviders: readonly string[];
10
+ clients: readonly string[];
11
+ } | undefined;
12
+ /** A type that signs in is unavailable only while the app cannot make its connection, saying why. */
13
+ export declare const connectionUnavailable: (support: ConnectionSupport) => Unavailable;
14
+ //#endregion
@@ -0,0 +1,17 @@
1
+ //#region src/plugin/connection-availability.ts
2
+ /** A type that signs in is unavailable only while the app cannot make its connection, saying why. */
3
+ const connectionUnavailable = (support) => (type) => {
4
+ const connection = type.connection;
5
+ if (!connection) return;
6
+ if (!support) return "It signs in through a connection, and this app has no sign-in to connect an account with";
7
+ if (!support.encrypted) return "It signs in through a connection, whose tokens this app would store in plain text; turn on auth.encryptOAuthTokens";
8
+ if ("signIn" in connection) {
9
+ if (support.signInProviders.includes(connection.signIn)) return;
10
+ return `It signs in through "${connection.signIn}", which is not one of this app's sign-in providers (auth.socialProviders)`;
11
+ }
12
+ const key = `${type.plugin}:${connection.name}`;
13
+ if (support.clients.includes(key)) return;
14
+ return `It signs in through ${key}, whose OAuth client this app does not set in auth.connections`;
15
+ };
16
+ //#endregion
17
+ export { connectionUnavailable };
@@ -95,5 +95,10 @@ export type StepContext<Input = Record<string, unknown>> = PluginServices & {
95
95
  redact: (text: string) => string;
96
96
  /** Undefined unless the step declares a `connection`. */
97
97
  connection: PluginConnection | undefined;
98
+ /**
99
+ * Sends from the own mailbox of the person who turned on the version this run runs, signed in as themselves, while
100
+ * they may still change the workflow; undefined when the app links no mailboxes (`auth.personalMail`).
101
+ */
102
+ mailbox: PluginMail | undefined;
98
103
  };
99
104
  //#endregion
@@ -3,6 +3,27 @@
3
3
  const pluginApi = 1;
4
4
  const pluginName = /^[a-z][a-z0-9_]*$/;
5
5
  const typeKey = /^[a-z][a-z0-9_]*(\.[a-z][a-z0-9_]*)*$/;
6
+ const connectionName = /^[a-z][a-z0-9_]*$/;
7
+ const localHosts = [
8
+ "localhost",
9
+ "127.0.0.1",
10
+ "[::1]"
11
+ ];
12
+ const endpointProblem = (value) => {
13
+ if (typeof value !== "string" || !URL.canParse(value)) return "is not a URL";
14
+ const url = new URL(value);
15
+ if (url.protocol === "https:" || url.protocol === "http:" && localHosts.includes(url.hostname)) return;
16
+ return "must be an https URL";
17
+ };
18
+ const checkConnection = (where, name, connection) => {
19
+ if (!connectionName.test(name)) throw new Error(`${where}: "${name}" is not a connection name; use lowercase letters, digits and "_"`);
20
+ const urls = "oauth" in connection ? { ...connection.oauth } : { revocation_url: connection.revocation_url };
21
+ for (const [field, value] of Object.entries(urls)) {
22
+ if (field === "pkce" || value === void 0) continue;
23
+ const problem = endpointProblem(value);
24
+ if (problem) throw new Error(`${where}: the connection "${name}"'s ${field} ${problem}`);
25
+ }
26
+ };
6
27
  /** Throws when `plugin` breaks a naming rule, each error starting with `where`. */
7
28
  const checkPlugin = (plugin, where = `Workflow plugin "${plugin.name}"`) => {
8
29
  if (!pluginName.test(plugin.name)) throw new Error(`${where}: a plugin's name is lowercase letters, digits and "_"`);
@@ -11,7 +32,7 @@ const checkPlugin = (plugin, where = `Workflow plugin "${plugin.name}"`) => {
11
32
  const shared = Object.keys(plugin.steps ?? {}).find((key) => Object.hasOwn(plugin.triggers ?? {}, key));
12
33
  if (shared !== void 0) throw new Error(`${where}: "${shared}" is both a step and a trigger; give each type its own key`);
13
34
  const connections = Object.keys(plugin.connections ?? {});
14
- if (connections.includes("")) throw new Error(`${where}: a connection's name is not empty`);
35
+ for (const [name, connection] of Object.entries(plugin.connections ?? {})) checkConnection(where, name, connection);
15
36
  for (const [key, type] of [...Object.entries(plugin.triggers ?? {}), ...Object.entries(plugin.steps ?? {})]) if (type.connection !== void 0 && !connections.includes(type.connection)) throw new Error(`${where}: ${key} uses the connection "${type.connection}", which the plugin does not declare`);
16
37
  };
17
38
  /** Declares a workflow plugin, checking its names: a type is `<name>:<key>`, such as `app:http` or `acme:new_order`. */
@@ -1,8 +1,9 @@
1
1
  import { StepError } from "../run/errors.js";
2
2
  import { FileValue, JsonSchema, PluginConnection, PluginFetch, PluginFetchInit, PluginFiles, PluginMail, PluginMailMessage, PluginRecords, PluginServices, StepContext } from "./context.js";
3
- import { ConnectionDeclaration, Plugin, PollingTrigger, ReadyTrigger, StepType, TriggerContext, TriggerItem, TriggerType, WebhookTrigger } from "./types.js";
3
+ import { ConnectionDeclaration, OAuthEndpoints, Plugin, PollEvery, PollingTrigger, ReadyTrigger, StepType, TriggerContext, TriggerItem, TriggerType, WebhookEvent, WebhookItem, WebhookTrigger } from "./types.js";
4
4
  import { ConnectionError } from "./connection-error.js";
5
5
  import { definePlugin, pluginApi } from "./define-plugin.js";
6
6
  import { AddressRefusedError, ResponseTooLargeError, fetchMaxBytes } from "./fetch-errors.js";
7
7
  import { isFileValue } from "./file-value.js";
8
- export { AddressRefusedError, type ConnectionDeclaration, ConnectionError, type FileValue, type JsonSchema, type Plugin, type PluginConnection, type PluginFetch, type PluginFetchInit, type PluginFiles, type PluginMail, type PluginMailMessage, type PluginRecords, type PluginServices, type PollingTrigger, type ReadyTrigger, ResponseTooLargeError, type StepContext, StepError, type StepType, type TriggerContext, type TriggerItem, type TriggerType, type WebhookTrigger, definePlugin, fetchMaxBytes, isFileValue, pluginApi };
8
+ import { webhookBodyCeiling, webhookBodyDefault, webhookInputCheck, webhookInputProperties } from "./webhook-input.js";
9
+ export { AddressRefusedError, type ConnectionDeclaration, ConnectionError, type FileValue, type JsonSchema, type OAuthEndpoints, type Plugin, type PluginConnection, type PluginFetch, type PluginFetchInit, type PluginFiles, type PluginMail, type PluginMailMessage, type PluginRecords, type PluginServices, type PollEvery, type PollingTrigger, type ReadyTrigger, ResponseTooLargeError, type StepContext, StepError, type StepType, type TriggerContext, type TriggerItem, type TriggerType, type WebhookEvent, type WebhookItem, type WebhookTrigger, definePlugin, fetchMaxBytes, isFileValue, pluginApi, webhookBodyCeiling, webhookBodyDefault, webhookInputCheck, webhookInputProperties };
@@ -3,4 +3,5 @@ import { definePlugin, pluginApi } from "./define-plugin.js";
3
3
  import { ConnectionError } from "./connection-error.js";
4
4
  import { AddressRefusedError, ResponseTooLargeError, fetchMaxBytes } from "./fetch-errors.js";
5
5
  import { isFileValue } from "./file-value.js";
6
- export { AddressRefusedError, ConnectionError, ResponseTooLargeError, StepError, definePlugin, fetchMaxBytes, isFileValue, pluginApi };
6
+ import { webhookBodyCeiling, webhookBodyDefault, webhookInputCheck, webhookInputProperties } from "./webhook-input.js";
7
+ export { AddressRefusedError, ConnectionError, ResponseTooLargeError, StepError, definePlugin, fetchMaxBytes, isFileValue, pluginApi, webhookBodyCeiling, webhookBodyDefault, webhookInputCheck, webhookInputProperties };
@@ -1,11 +1,13 @@
1
1
  import { TaskContext, TaskHandlers } from "../run/port.js";
2
- import { PluginConnection, PluginServices } from "./context.js";
2
+ import { PluginConnection, PluginMail, PluginServices } from "./context.js";
3
3
  import { Plugin } from "./types.js";
4
4
  //#region src/plugin/step-handlers.d.ts
5
5
  /** What the app gives each step: its services for this run, and the connection a step declared. */
6
6
  export type StepWiring = {
7
7
  services: (task: TaskContext) => PluginServices;
8
8
  connection: (stepId: string, name: string, task: TaskContext) => PluginConnection;
9
+ /** The mailbox of the person who turned the run's version on; none when the app links no mailboxes. */
10
+ mailbox?: (task: TaskContext) => PluginMail | undefined;
9
11
  };
10
12
  /** The runner's step types from the plugins' steps, each checking its input against its schema before it runs. */
11
13
  export declare const stepHandlers: (plugins: readonly Plugin[], wiring: StepWiring) => TaskHandlers;
@@ -23,7 +23,8 @@ const handler = (id, type, wiring) => {
23
23
  signal,
24
24
  log,
25
25
  redact,
26
- connection
26
+ connection,
27
+ mailbox: wiring.mailbox?.(task)
27
28
  });
28
29
  };
29
30
  };
@@ -20,7 +20,7 @@ const manual = {
20
20
  const typeCatalog = (types) => ({
21
21
  step_types: types.filter((type) => type.kind === "step").map(entry),
22
22
  triggers: [manual, ...types.filter((type) => type.kind !== "step").map(entry)],
23
- note: "A definition holds its trigger as { \"<id>\": <input> }, such as { \"app:record\": { \"resource\": \"orders\" } }. A type with available false cannot be saved here; its reason says why. A trigger other than manual starts runs only while its workflow is enabled, its enabled_version set; run_workflow starts a run of any workflow, enabled or not, so a manual workflow needs no enabled_version."
23
+ note: "A definition holds its trigger as { \"<id>\": <input> }, such as { \"app:record\": { \"resource\": \"orders\" } }. A type with available false cannot be saved here; its reason says why. A trigger other than manual starts runs only while its workflow is enabled, its enabled_version set, as enable_workflow sets it; run_workflow starts a run of any workflow, enabled or not, so a manual workflow needs no enabled_version."
24
24
  });
25
25
  //#endregion
26
26
  export { typeCatalog };
@@ -51,34 +51,57 @@ export type TriggerItem = {
51
51
  key: string;
52
52
  data: unknown;
53
53
  };
54
+ /** How often a polling trigger polls: a duration such as `1 minute`, or a cron in an IANA time zone (default UTC). */
55
+ export type PollEvery = string | {
56
+ cron: string;
57
+ timezone?: string;
58
+ };
54
59
  /** A trigger that asks a service for new items on a schedule. */
55
60
  export type PollingTrigger = TriggerBase & {
56
61
  kind: 'polling';
57
- /** A duration such as `1 minute`, or a cron in an IANA time zone. */
58
- every: string | {
59
- cron: string;
60
- timezone?: string;
61
- };
62
+ /** How often it polls, or how often for a given input, such as a schedule's own cron. */
63
+ every: PollEvery | ((input: Record<string, unknown>) => PollEvery);
62
64
  /** The most items one poll returns, at most 100. */
63
65
  limit?: number;
66
+ /** Called once, when the trigger has no cursor yet: its first cursor, such as the newest item's id. */
64
67
  start: (context: TriggerContext) => Promise<unknown>;
65
- /** Items after `cursor`, and the next cursor, which must move forward. */
68
+ /** Items after `cursor`, and the next cursor, which must move forward. `due` is the time this poll was queued for. */
66
69
  poll: (context: TriggerContext & {
67
70
  cursor: unknown;
68
71
  store: unknown;
69
72
  limit: number;
73
+ due: Date;
70
74
  }) => Promise<{
71
75
  items: TriggerItem[];
72
76
  cursor: unknown;
73
77
  store?: unknown;
74
78
  }>;
75
79
  };
80
+ /**
81
+ * A webhook call as the run sees it, once the route checked its signature: the method, the query, the headers without
82
+ * any credential (`authorization`, `cookie`, `webhook-*`, the signature header, `x-forwarded-*`), the body as JSON, form
83
+ * fields or text, or as a file of the run when the call would be over 1 MiB as JSON, and when it came. The address is left out: it holds
84
+ * the key.
85
+ */
86
+ export type WebhookEvent = {
87
+ method: string;
88
+ query: Record<string, string>;
89
+ headers: Record<string, string>;
90
+ body: unknown;
91
+ received_at: string;
92
+ };
93
+ /** One run a webhook call starts: `key` starts it once per workflow, such as the sender's message id. */
94
+ export type WebhookItem = {
95
+ key?: string;
96
+ data: unknown;
97
+ };
76
98
  /** A trigger that the app's webhook URL starts, after the route checked the call's signature. */
77
99
  export type WebhookTrigger = TriggerBase & {
78
100
  kind: 'webhook';
79
- /** Registers the URL with the service, returning what `unsubscribe` and `renew` need. */
101
+ /** Registers the URL and its secret with the service, returning what `unsubscribe` and `renew` need. */
80
102
  subscribe?: (context: TriggerContext & {
81
103
  url: string;
104
+ secret: string;
82
105
  }) => Promise<unknown>;
83
106
  unsubscribe?: (context: TriggerContext & {
84
107
  state: unknown;
@@ -87,29 +110,46 @@ export type WebhookTrigger = TriggerBase & {
87
110
  state: unknown;
88
111
  }) => Promise<unknown>;
89
112
  renewEvery?: string;
113
+ /**
114
+ * The runs a call starts, at most 100: `event` is the call as above, `request` the same call with its bytes, and
115
+ * `idempotencyKey` the signed `webhook-id` or the configured idempotency header, when the call has one.
116
+ */
90
117
  receive: (context: {
91
118
  request: Request;
119
+ event: WebhookEvent;
120
+ idempotencyKey: string | undefined;
92
121
  input: Record<string, unknown>;
93
122
  }) => Promise<{
94
- items: TriggerItem[];
123
+ items: WebhookItem[];
95
124
  response?: Response;
96
125
  }>;
97
126
  };
98
127
  export type TriggerType = ReadyTrigger | PollingTrigger | WebhookTrigger;
99
- /** A sign-in a plugin's types use: one of the app's sign-in providers, or an OAuth provider of its own. */
128
+ /** The endpoints of an OAuth 2.0 provider a connection signs in with that is not one of the app's sign-in providers. */
129
+ export type OAuthEndpoints = {
130
+ authorization_url: string;
131
+ token_url: string;
132
+ /** Answers the account's `sub` or `id`, and its `email` and `name` when it has them, for the access token. */
133
+ user_info_url: string;
134
+ /** Where disconnecting revokes the token (RFC 7009); without it, disconnecting only deletes it. */
135
+ revocation_url?: string;
136
+ /** Sends a PKCE challenge (S256); default true. */
137
+ pkce?: boolean;
138
+ };
139
+ /**
140
+ * A sign-in a plugin's types use: one of the app's sign-in providers (`signIn`, such as `google`), or an OAuth provider
141
+ * of its own (`oauth`), whose client id and secret the app's owner gives in `auth.connections`. Connecting asks for
142
+ * `scopes` with `link_params`, such as those that ask for a refresh token.
143
+ */
100
144
  export type ConnectionDeclaration = {
101
145
  label: string;
102
146
  scopes?: string[];
147
+ link_params?: Record<string, string>;
103
148
  } & ({
104
149
  signIn: string;
150
+ revocation_url?: string;
105
151
  } | {
106
- oauth: {
107
- authorization_url: string;
108
- token_url: string;
109
- user_info_url?: string;
110
- revocation_url?: string;
111
- pkce?: boolean;
112
- };
152
+ oauth: OAuthEndpoints;
113
153
  });
114
154
  /** A workflow plugin: the trigger and step types it adds, and the sign-ins they use. */
115
155
  export type Plugin = {
@@ -0,0 +1,18 @@
1
+ import { JsonSchema } from "./context.js";
2
+ //#region src/plugin/webhook-input.d.ts
3
+ /** The largest body a webhook call may have, whatever its trigger's `body_limit` says: 10 MiB. */
4
+ export declare const webhookBodyCeiling: number;
5
+ /** The body a webhook call may have when its trigger names no `body_limit`: 1 MiB. */
6
+ export declare const webhookBodyDefault: number;
7
+ /**
8
+ * What the route reads of every webhook trigger's input, before any plugin code sees the call: how a call proves it
9
+ * comes from the sender (`auth`), its largest body, how many calls a minute start runs, and the header that keys a run
10
+ * when the sender signs no `webhook-id`. A webhook type spreads these into its own input schema.
11
+ */
12
+ export declare const webhookInputProperties: Record<string, JsonSchema>;
13
+ /** What `hmac` needs beyond its mode: the header. */
14
+ export declare const webhookInputCheck: (input: Record<string, unknown>) => {
15
+ field: string;
16
+ message: string;
17
+ }[];
18
+ //#endregion
@@ -0,0 +1,80 @@
1
+ //#region src/plugin/webhook-input.ts
2
+ /** The largest body a webhook call may have, whatever its trigger's `body_limit` says: 10 MiB. */
3
+ const webhookBodyCeiling = 10485760;
4
+ /** The body a webhook call may have when its trigger names no `body_limit`: 1 MiB. */
5
+ const webhookBodyDefault = 1048576;
6
+ /**
7
+ * What the route reads of every webhook trigger's input, before any plugin code sees the call: how a call proves it
8
+ * comes from the sender (`auth`), its largest body, how many calls a minute start runs, and the header that keys a run
9
+ * when the sender signs no `webhook-id`. A webhook type spreads these into its own input schema.
10
+ */
11
+ const webhookInputProperties = {
12
+ auth: {
13
+ type: "object",
14
+ additionalProperties: false,
15
+ required: ["mode"],
16
+ description: "how a call proves it comes from the sender; default { \"mode\": \"standard_webhooks\" }",
17
+ properties: {
18
+ mode: {
19
+ enum: [
20
+ "standard_webhooks",
21
+ "hmac",
22
+ "bearer"
23
+ ],
24
+ description: "standard_webhooks: webhook-id, webhook-timestamp and webhook-signature headers; hmac: an HMAC of the body in header; bearer: Authorization: Bearer <secret>"
25
+ },
26
+ header: {
27
+ type: "string",
28
+ minLength: 1,
29
+ maxLength: 100,
30
+ description: "hmac: the header that carries the signature, such as x-hub-signature-256"
31
+ },
32
+ prefix: {
33
+ type: "string",
34
+ maxLength: 50,
35
+ description: "hmac: text before the signature, such as sha256="
36
+ },
37
+ encoding: {
38
+ enum: ["hex", "base64"],
39
+ description: "hmac: how the signature is written; default hex"
40
+ },
41
+ hash: {
42
+ enum: [
43
+ "SHA-1",
44
+ "SHA-256",
45
+ "SHA-512"
46
+ ],
47
+ description: "hmac: default SHA-256"
48
+ }
49
+ }
50
+ },
51
+ body_limit: {
52
+ type: "integer",
53
+ minimum: 1,
54
+ maximum: webhookBodyCeiling,
55
+ description: "the largest body in bytes; default 1048576 (1 MiB), at most 10485760 (10 MiB)"
56
+ },
57
+ per_minute: {
58
+ type: "integer",
59
+ minimum: 1,
60
+ maximum: 600,
61
+ description: "calls a minute that start runs; default 60"
62
+ },
63
+ idempotency_header: {
64
+ type: "string",
65
+ minLength: 1,
66
+ maxLength: 100,
67
+ description: "a header whose value starts one run per value, when the sender signs no webhook-id"
68
+ }
69
+ };
70
+ /** What `hmac` needs beyond its mode: the header. */
71
+ const webhookInputCheck = (input) => {
72
+ const auth = input.auth;
73
+ if (auth?.mode === "hmac" && !auth.header) return [{
74
+ field: "auth.header",
75
+ message: "is missing: hmac reads its signature from this header"
76
+ }];
77
+ return [];
78
+ };
79
+ //#endregion
80
+ export { webhookBodyCeiling, webhookBodyDefault, webhookInputCheck, webhookInputProperties };
@@ -51,6 +51,8 @@ export type TaskContext = {
51
51
  * text short, such as an answer's body in an error, blanks it first, so the cut leaves no part of a secret.
52
52
  */
53
53
  redact: (text: string) => string;
54
+ /** Blanks `value` out of all this step and the rest of its segment record, such as an access token it was given. */
55
+ secret: (value: string) => void;
54
56
  };
55
57
  /**
56
58
  * A step type, which a Task names as its `Resource`: it takes the Task's evaluated `Arguments` and returns its result.
@@ -3,10 +3,14 @@
3
3
  export declare const redacted: (value: unknown) => unknown;
4
4
  /** Secret values shorter than this are refused, so blanking them never blanks ordinary text. */
5
5
  export declare const shortestSecret = 8;
6
- /** Replaces every secret value inside a text, and inside every text of a value, by `[redacted]`. */
6
+ /**
7
+ * Replaces every secret value inside a text, and inside every text of a value, by `[redacted]`; `add` blanks one more
8
+ * from then on, such as an access token a step was given, for as long as this redactor lives.
9
+ */
7
10
  export type Redactor = {
8
11
  text: (text: string) => string;
9
12
  value: <T>(value: T) => T;
13
+ add: (secret: string) => void;
10
14
  };
11
15
  /**
12
16
  * The redactor of the app's secret values, wherever they appear inside a text, such as `Bearer <token>` or a token in
@@ -8,6 +8,14 @@ const redacted = (value) => {
8
8
  };
9
9
  /** Secret values shorter than this are refused, so blanking them never blanks ordinary text. */
10
10
  const shortestSecret = 8;
11
+ const urlEncoded = (text) => {
12
+ try {
13
+ return encodeURIComponent(text);
14
+ } catch (error) {
15
+ if (error instanceof URIError) return;
16
+ throw error;
17
+ }
18
+ };
11
19
  /**
12
20
  * The redactor of the app's secret values, wherever they appear inside a text, such as `Bearer <token>` or a token in
13
21
  * a URL's query; the longest first, so a secret inside another is blanked whole.
@@ -15,6 +23,11 @@ const shortestSecret = 8;
15
23
  const secretRedactor = (secrets) => {
16
24
  if (secrets.find((secret) => secret.length < 8) !== void 0) throw new Error(`A secret workflows read is shorter than 8 characters, too short to blank out of what runs record`);
17
25
  const ordered = [...new Set(secrets)].sort((a, b) => b.length - a.length);
26
+ const add = (secret) => {
27
+ if (secret.length < 8) return;
28
+ for (const form of [secret, urlEncoded(secret)]) if (form !== void 0 && !ordered.includes(form)) ordered.push(form);
29
+ ordered.sort((a, b) => b.length - a.length);
30
+ };
18
31
  const text = (input) => ordered.reduce((result, secret) => result.replaceAll(secret, "[redacted]"), input);
19
32
  const value = (input) => {
20
33
  if (ordered.length === 0) return input;
@@ -32,7 +45,8 @@ const secretRedactor = (secrets) => {
32
45
  };
33
46
  return {
34
47
  text,
35
- value
48
+ value,
49
+ add
36
50
  };
37
51
  };
38
52
  //#endregion
@@ -8,7 +8,7 @@ const ended = /* @__PURE__ */ new Set(["succeeded", "failed"]);
8
8
  * transaction, so the run starts when it commits; `segment` is what the queue's job runs.
9
9
  */
10
10
  const createRunner = ({ store, queue, tasks, secrets = {}, now = () => /* @__PURE__ */ new Date(), budgetMs = limits.segmentMs, maxSteps = limits.runSteps }) => {
11
- const redactor = secretRedactor(Object.values(secrets));
11
+ secretRedactor(Object.values(secrets));
12
12
  return {
13
13
  start: (db, runId) => queue.schedule(db, runId),
14
14
  /**
@@ -19,6 +19,7 @@ const createRunner = ({ store, queue, tasks, secrets = {}, now = () => /* @__PUR
19
19
  const run = await store.load(db, runId);
20
20
  if (!run || ended.has(run.status)) return;
21
21
  await store.update(db, runId, { status: "running" });
22
+ const redactor = secretRedactor(Object.values(secrets));
22
23
  const segment = {
23
24
  runId,
24
25
  definition: run.definition,
package/dist/run/task.js CHANGED
@@ -26,7 +26,8 @@ const runTask = async (context, state, args, idempotencyKey, logs) => {
26
26
  signal,
27
27
  idempotencyKey,
28
28
  log,
29
- redact: context.redactor.text
29
+ redact: context.redactor.text,
30
+ secret: context.redactor.add
30
31
  }), aborted(signal)]);
31
32
  } catch (error) {
32
33
  if (context.signal.aborted || error instanceof SupersededError) throw error;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@protobase/workflows",
3
- "version": "0.68.5",
3
+ "version": "0.69.0",
4
4
  "description": "Workflows as state machines with JSONata expressions: their check, a runner that saves every step, and the plugin interface for trigger and step types.",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {