@abyss-project/runtime 1.0.0 → 2.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (104) hide show
  1. package/README.md +6 -3
  2. package/dist/cost/execution-cost.d.ts +45 -0
  3. package/dist/cost/execution-cost.js +114 -0
  4. package/dist/cost/execution-cost.js.map +1 -0
  5. package/dist/definition/definition.limits.d.ts +4 -0
  6. package/dist/definition/definition.limits.js +8 -0
  7. package/dist/definition/definition.limits.js.map +1 -0
  8. package/dist/definition/definition.schema.d.ts +2 -2
  9. package/dist/definition/definition.schema.js +20 -4
  10. package/dist/definition/definition.schema.js.map +1 -1
  11. package/dist/definition/definition.types.d.ts +20 -1
  12. package/dist/definition/definition.types.js +9 -1
  13. package/dist/definition/definition.types.js.map +1 -1
  14. package/dist/engine/engine-entry.d.ts +1 -0
  15. package/dist/engine/engine-entry.js +6 -0
  16. package/dist/engine/engine-entry.js.map +1 -0
  17. package/dist/engine/engine-global.d.ts +1 -0
  18. package/dist/engine/engine-global.js +5 -0
  19. package/dist/engine/engine-global.js.map +1 -0
  20. package/dist/engine/engine-source.d.ts +2 -0
  21. package/dist/engine/engine-source.js +3 -0
  22. package/dist/engine/run-in-isolate.d.ts +34 -0
  23. package/dist/engine/run-in-isolate.js +267 -0
  24. package/dist/engine/run-in-isolate.js.map +1 -0
  25. package/dist/errors/runtime-error-code.enum.d.ts +2 -2
  26. package/dist/errors/runtime-error-code.enum.js +1 -1
  27. package/dist/errors/runtime-error-code.enum.js.map +1 -1
  28. package/dist/index.d.ts +8 -2
  29. package/dist/index.js +13 -4
  30. package/dist/index.js.map +1 -1
  31. package/dist/interpreter/interpreter.d.ts +27 -1
  32. package/dist/interpreter/interpreter.js +114 -42
  33. package/dist/interpreter/interpreter.js.map +1 -1
  34. package/dist/interpreter/interpreter.types.d.ts +35 -4
  35. package/dist/interpreter/interpreter.types.js +7 -1
  36. package/dist/interpreter/interpreter.types.js.map +1 -1
  37. package/dist/interpreter/test-host.d.ts +4 -2
  38. package/dist/interpreter/test-host.js +6 -0
  39. package/dist/interpreter/test-host.js.map +1 -1
  40. package/dist/runner-protocol/evaluation.types.d.ts +20 -0
  41. package/dist/runner-protocol/evaluation.types.js +10 -0
  42. package/dist/runner-protocol/evaluation.types.js.map +1 -0
  43. package/dist/runner-protocol/execution-protocol.types.d.ts +132 -0
  44. package/dist/runner-protocol/execution-protocol.types.js +48 -0
  45. package/dist/runner-protocol/execution-protocol.types.js.map +1 -0
  46. package/dist/server/code-runner-session.d.ts +28 -0
  47. package/dist/server/code-runner-session.js +208 -0
  48. package/dist/server/code-runner-session.js.map +1 -0
  49. package/dist/server/index.d.ts +2 -2
  50. package/dist/server/index.js +5 -3
  51. package/dist/server/index.js.map +1 -1
  52. package/dist/steps/execute-step.d.ts +12 -2
  53. package/dist/steps/execute-step.js +37 -0
  54. package/dist/steps/execute-step.js.map +1 -1
  55. package/dist/steps/global-references.d.ts +2 -0
  56. package/dist/steps/global-references.js +28 -0
  57. package/dist/steps/global-references.js.map +1 -0
  58. package/dist/steps/step-fields.d.ts +1 -1
  59. package/dist/steps/step-fields.js +10 -2
  60. package/dist/steps/step-fields.js.map +1 -1
  61. package/dist/steps/value-source.d.ts +1 -1
  62. package/dist/steps/value-source.js +3 -3
  63. package/dist/steps/value-source.js.map +1 -1
  64. package/package.json +10 -2
  65. package/scripts/build-engine.cjs +70 -0
  66. package/src/__tests__/engine-bundle.test.ts +121 -0
  67. package/src/cost/__tests__/execution-cost.test.ts +200 -0
  68. package/src/cost/execution-cost.ts +192 -0
  69. package/src/definition/__tests__/validate-definition.test.ts +354 -303
  70. package/src/definition/definition.limits.ts +9 -0
  71. package/src/definition/definition.schema.ts +172 -139
  72. package/src/definition/definition.types.ts +171 -143
  73. package/src/engine/__tests__/run-in-isolate.test.ts +468 -0
  74. package/src/engine/engine-entry.ts +3 -0
  75. package/src/engine/engine-global.ts +2 -0
  76. package/src/engine/run-in-isolate.ts +404 -0
  77. package/src/errors/runtime-error-code.enum.ts +37 -37
  78. package/src/index.ts +30 -18
  79. package/src/interpreter/__tests__/interpreter.test.ts +854 -854
  80. package/src/interpreter/__tests__/log-respond-resume.test.ts +223 -0
  81. package/src/interpreter/interpreter.ts +461 -342
  82. package/src/interpreter/interpreter.types.ts +192 -140
  83. package/src/interpreter/test-host.ts +85 -74
  84. package/src/runner-protocol/evaluation.types.ts +21 -0
  85. package/src/runner-protocol/execution-protocol.types.ts +221 -0
  86. package/src/server/__tests__/code-runner-session.test.ts +311 -0
  87. package/src/server/code-runner-error.ts +12 -12
  88. package/src/server/code-runner-session.ts +310 -0
  89. package/src/server/index.ts +11 -4
  90. package/src/steps/__tests__/global-references.test.ts +113 -0
  91. package/src/steps/execute-step.ts +186 -132
  92. package/src/steps/global-references.ts +48 -0
  93. package/src/steps/step-access.ts +56 -56
  94. package/src/steps/step-fields.ts +87 -79
  95. package/src/steps/value-source.ts +69 -69
  96. package/dist/runner-protocol/runner-protocol.types.d.ts +0 -92
  97. package/dist/runner-protocol/runner-protocol.types.js +0 -26
  98. package/dist/runner-protocol/runner-protocol.types.js.map +0 -1
  99. package/dist/server/code-runner-client.d.ts +0 -13
  100. package/dist/server/code-runner-client.js +0 -155
  101. package/dist/server/code-runner-client.js.map +0 -1
  102. package/src/runner-protocol/runner-protocol.types.ts +0 -117
  103. package/src/server/__tests__/code-runner-client.test.ts +0 -262
  104. package/src/server/code-runner-client.ts +0 -201
@@ -1,132 +1,186 @@
1
- import { RuntimeErrorCode } from '../errors/runtime-error-code.enum';
2
- import type { RuntimeErrorDetail } from '../errors/runtime-error-code.enum';
3
- import { StepType } from '../definition/definition.types';
4
- import type { Step, StopStatus, WaitStep } from '../definition/definition.types';
5
- import type { HttpRequest } from '../interpreter/interpreter.types';
6
- import { propertyPath } from './value-source';
7
- import type { ResolvedFields } from './step-fields';
8
-
9
- export enum StepActionKind {
10
- /** The step finished without any effect. */
11
- DONE = 'DONE',
12
- STOP = 'STOP',
13
- WAIT = 'WAIT',
14
- HTTP = 'HTTP',
15
- HOST = 'HOST',
16
- FAIL = 'FAIL',
17
- }
18
-
19
- export type StepAction =
20
- | {
21
- kind: StepActionKind.DONE;
22
- output: unknown;
23
- variable?: { name: string; value: unknown };
24
- /** Sequence to enter, relative to the step: `then`, `else`, `cases[2].steps`, `default`. */
25
- branch?: string;
26
- }
27
- | { kind: StepActionKind.STOP; status: StopStatus; output: unknown }
28
- | { kind: StepActionKind.WAIT; durationMs?: number; until?: string }
29
- | { kind: StepActionKind.HTTP; request: HttpRequest }
30
- | { kind: StepActionKind.HOST; action: string; input: Record<string, unknown> }
31
- | { kind: StepActionKind.FAIL; error: RuntimeErrorDetail };
32
-
33
- const fail = (message: string): StepAction => ({
34
- kind: StepActionKind.FAIL,
35
- error: { code: RuntimeErrorCode.EXPRESSION_ERROR, message },
36
- });
37
-
38
- const headerValue = (value: unknown): string =>
39
- typeof value === 'string' ? value : JSON.stringify(value) ?? '';
40
-
41
- const resolvedRecord = (
42
- base: string,
43
- keys: string[],
44
- fields: ResolvedFields,
45
- ): Record<string, unknown> =>
46
- Object.fromEntries(keys.map((key) => [key, fields.get(propertyPath(base, key))]));
47
-
48
- const executeWait = (step: WaitStep, fields: ResolvedFields): StepAction => {
49
- if (step.durationMs !== undefined) {
50
- const durationMs = fields.get('durationMs');
51
- if (typeof durationMs !== 'number' || !Number.isInteger(durationMs) || durationMs < 0) {
52
- return fail('Wait duration must resolve to a non-negative integer number of milliseconds');
53
- }
54
- return { kind: StepActionKind.WAIT, durationMs };
55
- }
56
- const until = fields.get('until');
57
- if (typeof until !== 'string' || Number.isNaN(Date.parse(until))) {
58
- return fail('Wait date must resolve to an ISO 8601 date');
59
- }
60
- return { kind: StepActionKind.WAIT, until };
61
- };
62
-
63
- /**
64
- * Decides what a step does once its values are resolved. Pure: the access and schema checks of
65
- * HTTP and HOST effects belong to the caller.
66
- */
67
- export const executeStep = (step: Step, fields: ResolvedFields): StepAction => {
68
- switch (step.type) {
69
- case StepType.CONDITION: {
70
- if (fields.get('if')) {
71
- return { kind: StepActionKind.DONE, output: 'then', branch: 'then' };
72
- }
73
- return step.else
74
- ? { kind: StepActionKind.DONE, output: 'else', branch: 'else' }
75
- : { kind: StepActionKind.DONE, output: 'else' };
76
- }
77
- case StepType.SWITCH: {
78
- const value = fields.get('value');
79
- const index = step.cases.findIndex(
80
- (_, caseIndex) => fields.get(`cases[${caseIndex}].match`) === value,
81
- );
82
- if (index >= 0) {
83
- const branch = `cases[${index}].steps`;
84
- return { kind: StepActionKind.DONE, output: `cases[${index}]`, branch };
85
- }
86
- return step.default
87
- ? { kind: StepActionKind.DONE, output: 'default', branch: 'default' }
88
- : { kind: StepActionKind.DONE, output: null };
89
- }
90
- case StepType.WAIT:
91
- return executeWait(step, fields);
92
- case StepType.SET: {
93
- const value = fields.get('value');
94
- return {
95
- kind: StepActionKind.DONE,
96
- output: value,
97
- variable: { name: step.variable, value },
98
- };
99
- }
100
- case StepType.CODE:
101
- return { kind: StepActionKind.DONE, output: fields.get('source') };
102
- case StepType.HTTP: {
103
- const url = fields.get('url');
104
- if (typeof url !== 'string') {
105
- return fail('HTTP url must resolve to a string');
106
- }
107
- const headers = resolvedRecord('headers', Object.keys(step.headers ?? {}), fields);
108
- const request: HttpRequest = {
109
- method: step.method,
110
- url,
111
- headers: Object.fromEntries(
112
- Object.entries(headers).map(([key, value]) => [key, headerValue(value)]),
113
- ),
114
- };
115
- if (step.body !== undefined) {
116
- request.body = fields.get('body');
117
- }
118
- if (step.timeoutMs !== undefined) {
119
- request.timeoutMs = step.timeoutMs;
120
- }
121
- return { kind: StepActionKind.HTTP, request };
122
- }
123
- case StepType.HOST:
124
- return {
125
- kind: StepActionKind.HOST,
126
- action: step.action,
127
- input: resolvedRecord('input', Object.keys(step.input), fields),
128
- };
129
- case StepType.STOP:
130
- return { kind: StepActionKind.STOP, status: step.status, output: fields.get('output') };
131
- }
132
- };
1
+ import { RuntimeErrorCode } from '../errors/runtime-error-code.enum';
2
+ import type { RuntimeErrorDetail } from '../errors/runtime-error-code.enum';
3
+ import { MAX_RESPONSE_STATUS, MIN_RESPONSE_STATUS } from '../definition/definition.limits';
4
+ import { StepType } from '../definition/definition.types';
5
+ import type {
6
+ LogLevel,
7
+ LogStep,
8
+ RespondStep,
9
+ Step,
10
+ StopStatus,
11
+ WaitStep,
12
+ } from '../definition/definition.types';
13
+ import type { HttpRequest, HttpResponseToSend } from '../interpreter/interpreter.types';
14
+ import { propertyPath } from './value-source';
15
+ import type { ResolvedFields } from './step-fields';
16
+
17
+ export enum StepActionKind {
18
+ /** The step finished without any effect. */
19
+ DONE = 'DONE',
20
+ STOP = 'STOP',
21
+ WAIT = 'WAIT',
22
+ HTTP = 'HTTP',
23
+ HOST = 'HOST',
24
+ LOG = 'LOG',
25
+ RESPOND = 'RESPOND',
26
+ FAIL = 'FAIL',
27
+ }
28
+
29
+ export type StepAction =
30
+ | {
31
+ kind: StepActionKind.DONE;
32
+ output: unknown;
33
+ variable?: { name: string; value: unknown };
34
+ /** Sequence to enter, relative to the step: `then`, `else`, `cases[2].steps`, `default`. */
35
+ branch?: string;
36
+ }
37
+ | { kind: StepActionKind.STOP; status: StopStatus; output: unknown }
38
+ | { kind: StepActionKind.WAIT; durationMs?: number; until?: string }
39
+ | { kind: StepActionKind.HTTP; request: HttpRequest }
40
+ | { kind: StepActionKind.HOST; action: string; input: Record<string, unknown> }
41
+ | { kind: StepActionKind.LOG; level: LogLevel; message: string; data?: unknown }
42
+ | { kind: StepActionKind.RESPOND; response: HttpResponseToSend }
43
+ | { kind: StepActionKind.FAIL; error: RuntimeErrorDetail };
44
+
45
+ const fail = (message: string): StepAction => ({
46
+ kind: StepActionKind.FAIL,
47
+ error: { code: RuntimeErrorCode.EXPRESSION_ERROR, message },
48
+ });
49
+
50
+ const headerValue = (value: unknown): string =>
51
+ typeof value === 'string' ? value : JSON.stringify(value) ?? '';
52
+
53
+ const resolvedRecord = (
54
+ base: string,
55
+ keys: string[],
56
+ fields: ResolvedFields,
57
+ ): Record<string, unknown> =>
58
+ Object.fromEntries(keys.map((key) => [key, fields.get(propertyPath(base, key))]));
59
+
60
+ const executeWait = (step: WaitStep, fields: ResolvedFields): StepAction => {
61
+ if (step.durationMs !== undefined) {
62
+ const durationMs = fields.get('durationMs');
63
+ if (typeof durationMs !== 'number' || !Number.isInteger(durationMs) || durationMs < 0) {
64
+ return fail('Wait duration must resolve to a non-negative integer number of milliseconds');
65
+ }
66
+ return { kind: StepActionKind.WAIT, durationMs };
67
+ }
68
+ const until = fields.get('until');
69
+ if (typeof until !== 'string' || Number.isNaN(Date.parse(until))) {
70
+ return fail('Wait date must resolve to an ISO 8601 date');
71
+ }
72
+ return { kind: StepActionKind.WAIT, until };
73
+ };
74
+
75
+ const executeLog = (step: LogStep, fields: ResolvedFields): StepAction => {
76
+ const message = fields.get('message');
77
+ const action: Extract<StepAction, { kind: StepActionKind.LOG }> = {
78
+ kind: StepActionKind.LOG,
79
+ level: step.level,
80
+ message: typeof message === 'string' ? message : JSON.stringify(message) ?? '',
81
+ };
82
+ if (step.data !== undefined) {
83
+ action.data = fields.get('data');
84
+ }
85
+ return action;
86
+ };
87
+
88
+ const executeRespond = (step: RespondStep, fields: ResolvedFields): StepAction => {
89
+ const status = fields.get('status');
90
+ if (
91
+ typeof status !== 'number' ||
92
+ !Number.isInteger(status) ||
93
+ status < MIN_RESPONSE_STATUS ||
94
+ status > MAX_RESPONSE_STATUS
95
+ ) {
96
+ return fail(
97
+ `Response status must resolve to an integer from ${MIN_RESPONSE_STATUS} to ${MAX_RESPONSE_STATUS}`,
98
+ );
99
+ }
100
+ const headers = resolvedRecord('headers', Object.keys(step.headers ?? {}), fields);
101
+ const response: HttpResponseToSend = {
102
+ status,
103
+ headers: Object.fromEntries(
104
+ Object.entries(headers).map(([key, value]) => [key, headerValue(value)]),
105
+ ),
106
+ };
107
+ if (step.body !== undefined) {
108
+ response.body = fields.get('body');
109
+ }
110
+ return { kind: StepActionKind.RESPOND, response };
111
+ };
112
+
113
+ /**
114
+ * Decides what a step does once its values are resolved. Pure: the access and schema checks of
115
+ * HTTP and HOST effects belong to the caller.
116
+ */
117
+ export const executeStep = (step: Step, fields: ResolvedFields): StepAction => {
118
+ switch (step.type) {
119
+ case StepType.CONDITION: {
120
+ if (fields.get('if')) {
121
+ return { kind: StepActionKind.DONE, output: 'then', branch: 'then' };
122
+ }
123
+ return step.else
124
+ ? { kind: StepActionKind.DONE, output: 'else', branch: 'else' }
125
+ : { kind: StepActionKind.DONE, output: 'else' };
126
+ }
127
+ case StepType.SWITCH: {
128
+ const value = fields.get('value');
129
+ const index = step.cases.findIndex(
130
+ (_, caseIndex) => fields.get(`cases[${caseIndex}].match`) === value,
131
+ );
132
+ if (index >= 0) {
133
+ const branch = `cases[${index}].steps`;
134
+ return { kind: StepActionKind.DONE, output: `cases[${index}]`, branch };
135
+ }
136
+ return step.default
137
+ ? { kind: StepActionKind.DONE, output: 'default', branch: 'default' }
138
+ : { kind: StepActionKind.DONE, output: null };
139
+ }
140
+ case StepType.WAIT:
141
+ return executeWait(step, fields);
142
+ case StepType.SET: {
143
+ const value = fields.get('value');
144
+ return {
145
+ kind: StepActionKind.DONE,
146
+ output: value,
147
+ variable: { name: step.variable, value },
148
+ };
149
+ }
150
+ case StepType.CODE:
151
+ return { kind: StepActionKind.DONE, output: fields.get('source') };
152
+ case StepType.HTTP: {
153
+ const url = fields.get('url');
154
+ if (typeof url !== 'string') {
155
+ return fail('HTTP url must resolve to a string');
156
+ }
157
+ const headers = resolvedRecord('headers', Object.keys(step.headers ?? {}), fields);
158
+ const request: HttpRequest = {
159
+ method: step.method,
160
+ url,
161
+ headers: Object.fromEntries(
162
+ Object.entries(headers).map(([key, value]) => [key, headerValue(value)]),
163
+ ),
164
+ };
165
+ if (step.body !== undefined) {
166
+ request.body = fields.get('body');
167
+ }
168
+ if (step.timeoutMs !== undefined) {
169
+ request.timeoutMs = step.timeoutMs;
170
+ }
171
+ return { kind: StepActionKind.HTTP, request };
172
+ }
173
+ case StepType.HOST:
174
+ return {
175
+ kind: StepActionKind.HOST,
176
+ action: step.action,
177
+ input: resolvedRecord('input', Object.keys(step.input), fields),
178
+ };
179
+ case StepType.LOG:
180
+ return executeLog(step, fields);
181
+ case StepType.RESPOND:
182
+ return executeRespond(step, fields);
183
+ case StepType.STOP:
184
+ return { kind: StepActionKind.STOP, status: step.status, output: fields.get('output') };
185
+ }
186
+ };
@@ -0,0 +1,48 @@
1
+ import { EvaluationKind } from '../runner-protocol/evaluation.types';
2
+ import type { RuntimeDefinition } from '../definition/definition.types';
3
+ import { walkSteps } from '../definition/walk-steps';
4
+ import { collectStepItems } from './step-fields';
5
+
6
+ const PLACEHOLDER = /\{\{([\s\S]*?)\}\}/g;
7
+
8
+ const escapeRegExp = (text: string): string => text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
9
+
10
+ /** The JavaScript an item runs: a template only runs what is inside its placeholders. */
11
+ const codeOf = (kind: EvaluationKind, source: string): string[] =>
12
+ kind === EvaluationKind.TEMPLATE
13
+ ? [...source.matchAll(PLACEHOLDER)].map((match) => match[1])
14
+ : [source];
15
+
16
+ /**
17
+ * The property names a definition reads statically from the host global `globalName`
18
+ * (`ExecuteMessage.globals`), as `<globalName>.<IDENT>`, `<globalName>?.<IDENT>` or
19
+ * `<globalName>['<IDENT>']` (either quote), in every expression, template placeholder and CODE
20
+ * source, branches included. Names come once each, in order of first appearance.
21
+ *
22
+ * It is a textual scan, so a string literal that spells such an access counts too: a host that
23
+ * resolves the names it finds only over-resolves. A dynamic access (`secrets[name]`) cannot be
24
+ * resolved ahead of time: it yields `undefined` at run time. `abyss.secrets.get(name)` is the
25
+ * dynamic path.
26
+ */
27
+ export const collectGlobalReferences = (
28
+ definition: Pick<RuntimeDefinition, 'steps'>,
29
+ globalName: string,
30
+ ): string[] => {
31
+ const name = escapeRegExp(globalName);
32
+ // Not preceded by an identifier character or a dot: `other.secrets.A` is not a read of `secrets`.
33
+ const access = new RegExp(
34
+ `(?<![\\w$.])${name}\\s*(?:\\??\\.\\s*([A-Za-z_$][\\w$]*)|\\[\\s*(['"])([A-Za-z_$][\\w$]*)\\2\\s*\\])`,
35
+ 'g',
36
+ );
37
+ const found = new Set<string>();
38
+ walkSteps(definition.steps, (step) => {
39
+ for (const item of collectStepItems(step)) {
40
+ for (const code of codeOf(item.kind, item.source)) {
41
+ for (const match of code.matchAll(access)) {
42
+ found.add(match[1] ?? match[3]);
43
+ }
44
+ }
45
+ }
46
+ });
47
+ return [...found];
48
+ };
@@ -1,56 +1,56 @@
1
- import { AccessKind } from '../access/access.types';
2
- import type { AccessDeclaration } from '../access/access.types';
3
- import { hostMatches } from '../access/host-match';
4
-
5
- export enum AccessVerdict {
6
- ALLOWED = 'ALLOWED',
7
- NOT_DECLARED = 'NOT_DECLARED',
8
- NOT_GRANTED = 'NOT_GRANTED',
9
- }
10
-
11
- const coversHost = (accesses: AccessDeclaration[], host: string): boolean =>
12
- accesses.some(
13
- (access) =>
14
- access.kind === AccessKind.HTTP && access.hosts.some((pattern) => hostMatches(host, pattern)),
15
- );
16
-
17
- const coversAction = (accesses: AccessDeclaration[], action: string): boolean =>
18
- accesses.some((access) => access.kind === AccessKind.HOST_ACTION && access.action === action);
19
-
20
- const verdict = (declared: boolean, granted: boolean): AccessVerdict => {
21
- if (!declared) {
22
- return AccessVerdict.NOT_DECLARED;
23
- }
24
- return granted ? AccessVerdict.ALLOWED : AccessVerdict.NOT_GRANTED;
25
- };
26
-
27
- const hostOf = (url: string): string | null => {
28
- try {
29
- const parsed = new URL(url);
30
- return parsed.protocol === 'http:' || parsed.protocol === 'https:' ? parsed.hostname : null;
31
- } catch {
32
- return null;
33
- }
34
- };
35
-
36
- /**
37
- * An HTTP effect needs its url's host in a declaration AND in a grant; an unparsable url or one
38
- * whose scheme is not http(s) (`file:`, `ftp:`...) is never covered.
39
- */
40
- export const checkHttpAccess = (
41
- url: string,
42
- declared: AccessDeclaration[],
43
- granted: AccessDeclaration[],
44
- ): AccessVerdict => {
45
- const host = hostOf(url);
46
- if (host === null) {
47
- return AccessVerdict.NOT_DECLARED;
48
- }
49
- return verdict(coversHost(declared, host), coversHost(granted, host));
50
- };
51
-
52
- export const checkHostActionAccess = (
53
- action: string,
54
- declared: AccessDeclaration[],
55
- granted: AccessDeclaration[],
56
- ): AccessVerdict => verdict(coversAction(declared, action), coversAction(granted, action));
1
+ import { AccessKind } from '../access/access.types';
2
+ import type { AccessDeclaration } from '../access/access.types';
3
+ import { hostMatches } from '../access/host-match';
4
+
5
+ export enum AccessVerdict {
6
+ ALLOWED = 'ALLOWED',
7
+ NOT_DECLARED = 'NOT_DECLARED',
8
+ NOT_GRANTED = 'NOT_GRANTED',
9
+ }
10
+
11
+ const coversHost = (accesses: AccessDeclaration[], host: string): boolean =>
12
+ accesses.some(
13
+ (access) =>
14
+ access.kind === AccessKind.HTTP && access.hosts.some((pattern) => hostMatches(host, pattern)),
15
+ );
16
+
17
+ const coversAction = (accesses: AccessDeclaration[], action: string): boolean =>
18
+ accesses.some((access) => access.kind === AccessKind.HOST_ACTION && access.action === action);
19
+
20
+ const verdict = (declared: boolean, granted: boolean): AccessVerdict => {
21
+ if (!declared) {
22
+ return AccessVerdict.NOT_DECLARED;
23
+ }
24
+ return granted ? AccessVerdict.ALLOWED : AccessVerdict.NOT_GRANTED;
25
+ };
26
+
27
+ const hostOf = (url: string): string | null => {
28
+ try {
29
+ const parsed = new URL(url);
30
+ return parsed.protocol === 'http:' || parsed.protocol === 'https:' ? parsed.hostname : null;
31
+ } catch {
32
+ return null;
33
+ }
34
+ };
35
+
36
+ /**
37
+ * An HTTP effect needs its url's host in a declaration AND in a grant; an unparsable url or one
38
+ * whose scheme is not http(s) (`file:`, `ftp:`...) is never covered.
39
+ */
40
+ export const checkHttpAccess = (
41
+ url: string,
42
+ declared: AccessDeclaration[],
43
+ granted: AccessDeclaration[],
44
+ ): AccessVerdict => {
45
+ const host = hostOf(url);
46
+ if (host === null) {
47
+ return AccessVerdict.NOT_DECLARED;
48
+ }
49
+ return verdict(coversHost(declared, host), coversHost(granted, host));
50
+ };
51
+
52
+ export const checkHostActionAccess = (
53
+ action: string,
54
+ declared: AccessDeclaration[],
55
+ granted: AccessDeclaration[],
56
+ ): AccessVerdict => verdict(coversAction(declared, action), coversAction(granted, action));
@@ -1,79 +1,87 @@
1
- import { EvaluationKind } from '../runner-protocol/runner-protocol.types';
2
- import type { EvaluationItem } from '../runner-protocol/runner-protocol.types';
3
- import { StepType } from '../definition/definition.types';
4
- import type { Step, ValueSource } from '../definition/definition.types';
5
- import { collectItems, propertyPath, resolveValue } from './value-source';
6
-
7
- interface StepField {
8
- path: string;
9
- source: ValueSource;
10
- }
11
-
12
- /** Resolved top-level fields of a step, by field path (`url`, `headers.Authorization`...). */
13
- export type ResolvedFields = ReadonlyMap<string, unknown>;
14
-
15
- const recordFields = (base: string, record: Record<string, ValueSource> | undefined): StepField[] =>
16
- Object.entries(record ?? {}).map(([key, source]) => ({ path: propertyPath(base, key), source }));
17
-
18
- const optionalField = (path: string, source: ValueSource | undefined): StepField[] =>
19
- source === undefined ? [] : [{ path, source }];
20
-
21
- /** The value sources of a step, each under the path used as evaluation item id. */
22
- const stepFields = (step: Step): StepField[] => {
23
- switch (step.type) {
24
- case StepType.CONDITION:
25
- return [{ path: 'if', source: step.if }];
26
- case StepType.SWITCH:
27
- return [
28
- { path: 'value', source: step.value },
29
- ...step.cases.map((switchCase, index) => ({
30
- path: `cases[${index}].match`,
31
- source: switchCase.match,
32
- })),
33
- ];
34
- case StepType.WAIT:
35
- return [
36
- ...optionalField('durationMs', step.durationMs),
37
- ...optionalField('until', step.until),
38
- ];
39
- case StepType.SET:
40
- return [{ path: 'value', source: step.value }];
41
- case StepType.CODE:
42
- return [];
43
- case StepType.HTTP:
44
- return [
45
- { path: 'url', source: step.url },
46
- ...recordFields('headers', step.headers),
47
- ...optionalField('body', step.body),
48
- ];
49
- case StepType.HOST:
50
- return recordFields('input', step.input);
51
- case StepType.STOP:
52
- return optionalField('output', step.output);
53
- }
54
- };
55
-
56
- /** Every non-literal value of the step, to evaluate in one lot. A CODE step always has one item. */
57
- export const collectStepItems = (step: Step): EvaluationItem[] => {
58
- if (step.type === StepType.CODE) {
59
- return [{ id: 'source', kind: EvaluationKind.CODE, source: step.source }];
60
- }
61
- const items: EvaluationItem[] = [];
62
- for (const field of stepFields(step)) {
63
- collectItems(field.path, field.source, items);
64
- }
65
- return items;
66
- };
67
-
68
- /** `results` maps item ids to evaluated values; a CODE step resolves to its single `source` item. */
69
- export const resolveStepFields = (
70
- step: Step,
71
- results: ReadonlyMap<string, unknown>,
72
- ): ResolvedFields => {
73
- if (step.type === StepType.CODE) {
74
- return new Map([['source', results.get('source')]]);
75
- }
76
- return new Map(
77
- stepFields(step).map((field) => [field.path, resolveValue(field.path, field.source, results)]),
78
- );
79
- };
1
+ import { EvaluationKind } from '../runner-protocol/evaluation.types';
2
+ import type { EvaluationItem } from '../runner-protocol/evaluation.types';
3
+ import { StepType } from '../definition/definition.types';
4
+ import type { Step, ValueSource } from '../definition/definition.types';
5
+ import { collectItems, propertyPath, resolveValue } from './value-source';
6
+
7
+ interface StepField {
8
+ path: string;
9
+ source: ValueSource;
10
+ }
11
+
12
+ /** Resolved top-level fields of a step, by field path (`url`, `headers.Authorization`...). */
13
+ export type ResolvedFields = ReadonlyMap<string, unknown>;
14
+
15
+ const recordFields = (base: string, record: Record<string, ValueSource> | undefined): StepField[] =>
16
+ Object.entries(record ?? {}).map(([key, source]) => ({ path: propertyPath(base, key), source }));
17
+
18
+ const optionalField = (path: string, source: ValueSource | undefined): StepField[] =>
19
+ source === undefined ? [] : [{ path, source }];
20
+
21
+ /** The value sources of a step, each under the path used as evaluation item id. */
22
+ const stepFields = (step: Step): StepField[] => {
23
+ switch (step.type) {
24
+ case StepType.CONDITION:
25
+ return [{ path: 'if', source: step.if }];
26
+ case StepType.SWITCH:
27
+ return [
28
+ { path: 'value', source: step.value },
29
+ ...step.cases.map((switchCase, index) => ({
30
+ path: `cases[${index}].match`,
31
+ source: switchCase.match,
32
+ })),
33
+ ];
34
+ case StepType.WAIT:
35
+ return [
36
+ ...optionalField('durationMs', step.durationMs),
37
+ ...optionalField('until', step.until),
38
+ ];
39
+ case StepType.SET:
40
+ return [{ path: 'value', source: step.value }];
41
+ case StepType.CODE:
42
+ return [];
43
+ case StepType.HTTP:
44
+ return [
45
+ { path: 'url', source: step.url },
46
+ ...recordFields('headers', step.headers),
47
+ ...optionalField('body', step.body),
48
+ ];
49
+ case StepType.HOST:
50
+ return recordFields('input', step.input);
51
+ case StepType.LOG:
52
+ return [{ path: 'message', source: step.message }, ...optionalField('data', step.data)];
53
+ case StepType.RESPOND:
54
+ return [
55
+ { path: 'status', source: step.status },
56
+ ...recordFields('headers', step.headers),
57
+ ...optionalField('body', step.body),
58
+ ];
59
+ case StepType.STOP:
60
+ return optionalField('output', step.output);
61
+ }
62
+ };
63
+
64
+ /** Every non-literal value of the step, to evaluate in one lot. A CODE step always has one item. */
65
+ export const collectStepItems = (step: Step): EvaluationItem[] => {
66
+ if (step.type === StepType.CODE) {
67
+ return [{ id: 'source', kind: EvaluationKind.CODE, source: step.source }];
68
+ }
69
+ const items: EvaluationItem[] = [];
70
+ for (const field of stepFields(step)) {
71
+ collectItems(field.path, field.source, items);
72
+ }
73
+ return items;
74
+ };
75
+
76
+ /** `results` maps item ids to evaluated values; a CODE step resolves to its single `source` item. */
77
+ export const resolveStepFields = (
78
+ step: Step,
79
+ results: ReadonlyMap<string, unknown>,
80
+ ): ResolvedFields => {
81
+ if (step.type === StepType.CODE) {
82
+ return new Map([['source', results.get('source')]]);
83
+ }
84
+ return new Map(
85
+ stepFields(step).map((field) => [field.path, resolveValue(field.path, field.source, results)]),
86
+ );
87
+ };