@coda-console/plugin-check 0.8.28 → 0.8.30
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 +13 -23
- package/check/coda/adapters/plugin-events.mjs +3 -10
- package/check/coda/adapters/plugin-modules.mjs +19 -23
- package/check/coda/adapters/plugin-setup-api.mjs +5 -0
- package/check/coda/adapters/plugin-test-host.d.mts +0 -13
- package/check/coda/adapters/plugin-test-host.mjs +6 -25
- package/check/coda/api-surface.txt +3 -6
- package/check/coda/application/contributions.mjs +1 -0
- package/check/coda/builtin.json +15 -49
- package/check/coda/components/plugins/contribution-points.mjs +1 -2
- package/check/coda/components/plugins/git-contributions.mjs +10 -6
- package/check/coda/components/plugins/plugin-extensions.mjs +9 -72
- package/check/coda/components/plugins/plugin-rules.mjs +16 -20
- package/check/coda/components/plugins/plugin-source-rules.mjs +13 -29
- package/check/coda/components/plugins/self-contributions.mjs +13 -0
- package/check/coda/components/protocols/record-rules.mjs +8 -0
- package/check/coda/contract.json +18 -26
- package/check/manifest.mjs +10 -8
- package/package.json +2 -2
- package/templates/module/main.mjs +6 -13
- package/templates/module/package.json +7 -7
- package/templates/module/test/main.test.mjs +7 -23
- package/check/coda/application/host-protocols.mjs +0 -19
- package/check/coda/components/workflows/workflow-protocol-definitions.mjs +0 -362
- package/check/coda/domain/accord.mjs +0 -144
- package/check/coda/domain/jcs.mjs +0 -58
- package/check/coda/domain/usage.mjs +0 -56
- package/check/coda/kernel/accord-protocol.mjs +0 -168
- package/check/coda/kernel/plugin-protocol.mjs +0 -56
- package/check/coda/kernel/project-protocol.mjs +0 -52
- package/check/coda/kernel/thread-protocol.mjs +0 -167
- package/check/coda/kernel/usage-protocol.mjs +0 -97
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "notes",
|
|
3
3
|
"displayName": "便条(模板)",
|
|
4
|
-
"description": "带模块的插件模板:自己的协议 notes/note@1
|
|
4
|
+
"description": "带模块的插件模板:自己的协议 notes/note@1(一个查询、一个做事的操作、一个事件),模块登记操作、写记录、订阅事件,附测试。",
|
|
5
5
|
"version": "1.0.0",
|
|
6
6
|
"categories": ["工作流程"],
|
|
7
7
|
"main": "main.mjs",
|
|
@@ -46,24 +46,24 @@
|
|
|
46
46
|
}
|
|
47
47
|
},
|
|
48
48
|
"add": {
|
|
49
|
-
"description": "
|
|
49
|
+
"description": "记一条便条(同标题是同一条)。标题与正文的长度在输入里限住,超了在写入前就拒绝。",
|
|
50
50
|
"input": {
|
|
51
51
|
"type": "object",
|
|
52
|
-
"properties": { "title": { "type": "string", "minLength": 1, "maxLength": 100 }, "body": { "type": "string", "maxLength": 10000 }
|
|
53
|
-
"required": ["title", "body"
|
|
52
|
+
"properties": { "title": { "type": "string", "minLength": 1, "maxLength": 100 }, "body": { "type": "string", "maxLength": 10000 } },
|
|
53
|
+
"required": ["title", "body"],
|
|
54
54
|
"additionalProperties": false
|
|
55
55
|
},
|
|
56
56
|
"result": {
|
|
57
57
|
"type": "object",
|
|
58
|
-
"properties": { "key": { "type": "string" }
|
|
59
|
-
"required": ["key"
|
|
58
|
+
"properties": { "key": { "type": "string" } },
|
|
59
|
+
"required": ["key"],
|
|
60
60
|
"additionalProperties": false
|
|
61
61
|
}
|
|
62
62
|
}
|
|
63
63
|
},
|
|
64
64
|
"events": {
|
|
65
65
|
"note_notes.added": {
|
|
66
|
-
"description": "
|
|
66
|
+
"description": "记了一条便条(由命令行 coda event 或流程的 publish-event 动作发布)。",
|
|
67
67
|
"payload": {
|
|
68
68
|
"type": "object",
|
|
69
69
|
"properties": { "key": { "type": "string" }, "title": { "type": "string" }, "body": { "type": "string" } },
|
|
@@ -29,37 +29,21 @@ test('activating over notes already there leaves them as they are', async () =>
|
|
|
29
29
|
await host.close();
|
|
30
30
|
});
|
|
31
31
|
|
|
32
|
-
test('add makes the note
|
|
32
|
+
test('add makes the note, same title the same note; the module counts the events it is given', async () => {
|
|
33
33
|
const host = await started();
|
|
34
|
-
const input = { title: '买牛奶', body: '两盒'
|
|
35
|
-
assert.deepEqual(await host.call(note, 'add', input), { key: '买牛奶'
|
|
34
|
+
const input = { title: '买牛奶', body: '两盒' };
|
|
35
|
+
assert.deepEqual(await host.call(note, 'add', input), { key: '买牛奶' });
|
|
36
36
|
await host.call(note, 'add', input);
|
|
37
|
-
assert.equal(host.emitted.length, 2);
|
|
38
|
-
const [event] = host.emitted;
|
|
39
|
-
assert.equal(event.name, 'note_notes.added');
|
|
40
|
-
assert.equal(event.kind, NOTE);
|
|
41
|
-
assert.deepEqual(event.data, { key: '买牛奶', title: '买牛奶', body: '两盒' });
|
|
42
37
|
assert.deepEqual((await host.call(note, 'find', { query: '牛奶' })).notes, [{ key: '买牛奶', title: '买牛奶' }]);
|
|
43
|
-
|
|
38
|
+
// An event is published by the command line or a workflow, not by the module: the test hands one to its `coda.on` handler.
|
|
39
|
+
await host.emit({ name: 'note_notes.added', kind: NOTE, subject: 'note:any', project: 'p1', data: { key: '买牛奶', title: '买牛奶', body: '两盒' }, publisher: 'notes' });
|
|
44
40
|
assert.equal((await host.call(note, 'find')).seen, 1);
|
|
45
41
|
await host.close();
|
|
46
42
|
});
|
|
47
43
|
|
|
48
|
-
test('an input over the limits is refused before anything is written
|
|
44
|
+
test('an input over the limits is refused before anything is written', async () => {
|
|
49
45
|
const host = await started();
|
|
50
|
-
await assert.rejects(host.call(note, 'add', { title: '长', body: 'x'.repeat(10001)
|
|
46
|
+
await assert.rejects(host.call(note, 'add', { title: '长', body: 'x'.repeat(10001) }), { code: 'invalid_input' });
|
|
51
47
|
assert.deepEqual((await host.call(note, 'find')).notes.map(entry => entry.key), ['欢迎']);
|
|
52
|
-
assert.deepEqual(host.emitted, []);
|
|
53
|
-
await host.close();
|
|
54
|
-
});
|
|
55
|
-
|
|
56
|
-
test('add that cannot publish still saves the note, and says it did not tell anyone', async () => {
|
|
57
|
-
const host = createTestHost({ plugin: { protocols: contributes.protocols, protocolImplementations: contributes.protocolImplementations, uses } });
|
|
58
|
-
const coda = { ...host.coda, emit: async () => { throw host.coda.error('invalid_input', '项目 nope 不存在'); } };
|
|
59
|
-
await activate(coda);
|
|
60
|
-
const added = await host.call(note, 'add', { title: '买牛奶', body: '两盒', project: 'nope' });
|
|
61
|
-
assert.deepEqual(added, { key: '买牛奶', notified: false, reason: added.reason });
|
|
62
|
-
assert.match(String(added.reason), /项目 nope 不存在/);
|
|
63
|
-
assert.deepEqual((await host.call(note, 'find')).notes.map(entry => entry.key).sort(), ['买牛奶', '欢迎']);
|
|
64
48
|
await host.close();
|
|
65
49
|
});
|
|
@@ -1,19 +0,0 @@
|
|
|
1
|
-
// Coda's own protocols (docs/plugins.md「用到的权限」), each as its component defines it: data that nothing running changes,
|
|
2
|
-
// listed once. The service registers them from here, each bound by its kind to what serves it (components/protocols/protocols.mjs
|
|
3
|
-
// `bind`: application/assembly.mjs; a composer's and a group's own component binds that one), none left unbound once it is
|
|
4
|
-
// put together (server.mjs `checkBound`); and the plugins are judged against them from the first reading of the catalog on, before any is
|
|
5
|
-
// registered (components/plugins/plugins.mjs `protocols`). The plugin host for a plugin's tests takes Coda's events from here
|
|
6
|
-
// too (adapters/plugin-test-host.mjs), so nothing this imports runs. The protocol package's core protocols are not among them
|
|
7
|
-
// (CORE_PROTOCOLS).
|
|
8
|
-
import { PLUGIN_PROTOCOL } from '../kernel/plugin-protocol.mjs';
|
|
9
|
-
import { PROJECT_PROTOCOL } from '../kernel/project-protocol.mjs';
|
|
10
|
-
import { USAGE_PROTOCOL } from '../kernel/usage-protocol.mjs';
|
|
11
|
-
import { ACCORD_PROTOCOL } from '../kernel/accord-protocol.mjs';
|
|
12
|
-
import { THREAD_PROTOCOL } from '../kernel/thread-protocol.mjs';
|
|
13
|
-
import { composerType, submissionType } from '../components/composers/schemas.mjs';
|
|
14
|
-
import { groupType } from '../components/concurrency-groups/schemas.mjs';
|
|
15
|
-
import { WORKFLOW_PROTOCOL, WORKFLOW_RUN_PROTOCOL, withWorkflows } from '../components/workflows/workflow-protocol-definitions.mjs';
|
|
16
|
-
|
|
17
|
-
// A session's, with the workflows' query and the group that has it (workflow-protocol-definitions.mjs `withWorkflows`).
|
|
18
|
-
export const THREAD_DEFINITION = withWorkflows(THREAD_PROTOCOL);
|
|
19
|
-
export const HOST_PROTOCOLS = [THREAD_DEFINITION, PROJECT_PROTOCOL, PLUGIN_PROTOCOL, USAGE_PROTOCOL, ACCORD_PROTOCOL, WORKFLOW_PROTOCOL, WORKFLOW_RUN_PROTOCOL, composerType, submissionType, groupType];
|
|
@@ -1,362 +0,0 @@
|
|
|
1
|
-
// Coda's own protocols of its workflows, as data: `coda/workflow@1`, `coda/workflow-run@1` and the query of `coda/thread@1` they
|
|
2
|
-
// answer (`withWorkflows`), each a definition and the schemas it is made of (./workflow-protocols.mjs says what they are and
|
|
3
|
-
// gives their records). Nothing here runs: application/host-protocols.mjs lists them for the backend and the plugin host for
|
|
4
|
-
// a plugin's tests (adapters/plugin-test-host.mjs) alike.
|
|
5
|
-
import { INPUT_SOURCES, INPUT_TYPES } from '@coda-console/protocol/workflow';
|
|
6
|
-
import { derivedUUID } from '../../domain/values.mjs';
|
|
7
|
-
|
|
8
|
-
// A text input's length: room for what one workflow hands another, such as release notes (`run-workflows`), for a
|
|
9
|
-
// command the user is asked to approve, as long as its card takes (`approve-command`, components/workflows/task-fields.mjs),
|
|
10
|
-
// and for a task's note (workflow-tasks.mjs), which a process may take as such a text: release notes, an executor's next task.
|
|
11
|
-
export const INPUT_LIMIT = 16 * 1024;
|
|
12
|
-
// The most a run's requirement says (`run.message`): what a message takes (store acceptMessage).
|
|
13
|
-
export const MESSAGE_LIMIT = 100_000;
|
|
14
|
-
|
|
15
|
-
export const WORKFLOW = 'coda/workflow@1';
|
|
16
|
-
// Coda's sessions, whose directory's workflows are a query of theirs these answer (`withWorkflows`).
|
|
17
|
-
export const THREAD = 'coda/thread@1';
|
|
18
|
-
export const WORKFLOW_RUN = 'coda/workflow-run@1';
|
|
19
|
-
// A workflow's record is named by its directory and its name: the same workflow of the same directory is the same record
|
|
20
|
-
// on every reading. A run's record is named by the run's ID.
|
|
21
|
-
export const workflowRecordId = (project, workflow) => derivedUUID(WORKFLOW, project, workflow);
|
|
22
|
-
|
|
23
|
-
export const object = (properties, required = [], rest = {}) =>
|
|
24
|
-
({ type: 'object', properties, ...(required.length ? { required } : {}), additionalProperties: false, ...rest });
|
|
25
|
-
export const list = items => ({ type: 'array', items });
|
|
26
|
-
const text = { type: 'string', minLength: 1 };
|
|
27
|
-
const flag = { type: 'boolean' };
|
|
28
|
-
const count = { type: 'integer', minimum: 0 };
|
|
29
|
-
export const time = { type: 'string', pattern: '^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?Z$' };
|
|
30
|
-
const timeOrNull = { ...time, type: ['string', 'null'] };
|
|
31
|
-
const textOrNull = { ...text, type: ['string', 'null'] };
|
|
32
|
-
// A workflow's file name, without `.bpmn` (components/workflows/workflow.mjs workflowName).
|
|
33
|
-
const workflowName = { type: 'string', pattern: '^[a-z][a-z0-9-]{0,39}$' };
|
|
34
|
-
const SOURCES = Object.keys(INPUT_SOURCES);
|
|
35
|
-
|
|
36
|
-
// An Agent combination, the value of an `agent` input (session-config/contributions.mjs `coda-agent`).
|
|
37
|
-
const AGENT = object({
|
|
38
|
-
agent: { type: 'string', pattern: '^[a-z][a-z0-9-]{0,39}$' },
|
|
39
|
-
model: text, effort: text, mode: text,
|
|
40
|
-
options: { type: 'object', additionalProperties: { anyOf: [flag, { type: 'string', minLength: 1, maxLength: 200 }] } },
|
|
41
|
-
}, ['agent']);
|
|
42
|
-
// A value given for an input, of its declared type; a run's own inputs, as resolved, leave an `agent` one with none null.
|
|
43
|
-
const VALUE = { anyOf: [{ type: 'string', maxLength: INPUT_LIMIT }, { type: 'number' }, flag, AGENT] };
|
|
44
|
-
const RESOLVED = { anyOf: [...VALUE.anyOf, { type: 'null' }] };
|
|
45
|
-
// An input as the workflow declares it (`coda:input`, components/workflows/bpmn.mjs).
|
|
46
|
-
const INPUT = {
|
|
47
|
-
type: { enum: INPUT_TYPES }, label: text, description: text, required: flag,
|
|
48
|
-
defaultFrom: { enum: SOURCES }, default: { type: ['string', 'number', 'boolean'] },
|
|
49
|
-
};
|
|
50
|
-
// Where an input takes its value from when a run is given none: a value, or a source of the session it starts from.
|
|
51
|
-
const RULE = { oneOf: [object({ value: VALUE }, ['value']), object({ from: { enum: SOURCES } }, ['from'])] };
|
|
52
|
-
// What the sources give in a session now (INPUT_SOURCES): its branch, its Agent combination.
|
|
53
|
-
const SOURCE_VALUES = object(Object.fromEntries(Object.entries(INPUT_SOURCES)
|
|
54
|
-
.map(([name, { types }]) => [name, types.includes('agent') ? AGENT : text])));
|
|
55
|
-
|
|
56
|
-
// The outputs a step or a run gives (a step's `$GITHUB_OUTPUT`, the end event's `coda:output`).
|
|
57
|
-
const OUTPUTS = { type: 'object', additionalProperties: { type: ['string', 'number', 'boolean', 'null'] } };
|
|
58
|
-
const RUN_STATE = { enum: ['waiting', 'running', 'cancelling', 'succeeded', 'failed', 'cancelled'] };
|
|
59
|
-
// A step's attempt, or `pending` / `skipped` for one this round has not reached.
|
|
60
|
-
const JOB_STATE = { enum: ['pending', 'queued', 'running', 'succeeded', 'failed', 'cancelled', 'skipped'] };
|
|
61
|
-
|
|
62
|
-
// What the user, a session or its project set for a workflow (components/workflows/workflow-settings.mjs), as a session
|
|
63
|
-
// sees it: whether the events that start it by themselves do (only for one they start, `startedBy`), each input's rule
|
|
64
|
-
// and the value it would take now, and where each comes from (`SEEN`); and what the session's sources give now.
|
|
65
|
-
export const SEEN = {
|
|
66
|
-
enabled: object({ value: flag, source: { enum: ['session', 'project', 'plugin', 'template'] } }, ['value', 'source']),
|
|
67
|
-
inputs: list(object({ name: text, ...INPUT, rule: RULE, source: { enum: ['session', 'project', 'template'] }, value: RESOLVED },
|
|
68
|
-
['name', 'type', 'source', 'value'])),
|
|
69
|
-
};
|
|
70
|
-
export const SETTINGS = object({ ...SEEN, sources: SOURCE_VALUES }, ['inputs', 'sources']);
|
|
71
|
-
|
|
72
|
-
// A run as it stands (workflow_status of one run, components/workflows/workflow-run-records.mjs `describe`): its state and
|
|
73
|
-
// round (`attempt`), what its card says (title, line, stages, the messages from the user it waits on), whether a resume
|
|
74
|
-
// goes on where it failed (`rerun`), its place in the queue, its workspace's retention, its times, how it ended, each step
|
|
75
|
-
// with its attempt and that attempt's steps and sessions, each user task of the round, and the runs it called. What a task
|
|
76
|
-
// asks (its choices, fields) is on its card; a step's log is read as the stream `log`, not by a path on the machine that ran it.
|
|
77
|
-
export const STEP = object({
|
|
78
|
-
index: count, name: text,
|
|
79
|
-
state: { enum: ['pending', 'running', 'success', 'failure', 'cancelled', 'skipped'] },
|
|
80
|
-
conclusion: { enum: [null, 'success', 'failure', 'cancelled', 'skipped'] },
|
|
81
|
-
// How it went before `continue-on-error` made a failure its conclusion's success.
|
|
82
|
-
outcome: { enum: [null, 'success', 'failure', 'cancelled', 'skipped'] },
|
|
83
|
-
exitCode: { type: ['integer', 'null'] }, startedAt: timeOrNull, finishedAt: timeOrNull,
|
|
84
|
-
}, ['index', 'name', 'state', 'conclusion', 'exitCode', 'startedAt', 'finishedAt']);
|
|
85
|
-
export const JOB = object({
|
|
86
|
-
job: text, name: text, needs: list(text), group: text, state: JOB_STATE,
|
|
87
|
-
// Its current attempt, 0 before the first; the commit, error and outputs of that attempt.
|
|
88
|
-
attempt: count, commit: textOrNull, error: { type: ['string', 'null'] }, outputs: OUTPUTS,
|
|
89
|
-
queuedAt: timeOrNull, startedAt: timeOrNull, finishedAt: timeOrNull,
|
|
90
|
-
// The line it is at while it runs, and why and until when its agent is held up, the how-manieth time.
|
|
91
|
-
step: text, blocked: object({ reason: text, until: time, attempt: { type: 'integer', minimum: 1 } }, ['reason', 'until', 'attempt']),
|
|
92
|
-
steps: list(STEP),
|
|
93
|
-
// The sessions its `coda-agent` steps started, every attempt's.
|
|
94
|
-
agents: list(object({ session: text, title: { type: 'string' }, agent: text, model: text, effort: text,
|
|
95
|
-
step: { type: ['integer', 'null'], minimum: 0 }, attempt: { type: 'integer', minimum: 1 } }, ['session', 'title', 'agent', 'attempt'])),
|
|
96
|
-
// Every attempt of it whose history is kept, oldest first: how each went and ended.
|
|
97
|
-
attempts: list(object({ attempt: { type: 'integer', minimum: 1 }, state: JOB_STATE, startedAt: timeOrNull, finishedAt: timeOrNull,
|
|
98
|
-
error: { type: ['string', 'null'] } }, ['attempt', 'state', 'startedAt', 'finishedAt', 'error'])),
|
|
99
|
-
// Its attempts' logs reclaimed past their retention.
|
|
100
|
-
logsPruned: flag,
|
|
101
|
-
// Its current attempt's sessions wait on a card of theirs, the run then held up by the user, not by its work.
|
|
102
|
-
agentNeedsInput: { const: true },
|
|
103
|
-
}, ['job', 'name', 'needs', 'state', 'attempt', 'steps', 'agents']);
|
|
104
|
-
// An answer a user task offers (components/workflows/bpmn.mjs parseChoices).
|
|
105
|
-
const CHOICE_FACTS = { id: text, name: text, detail: { type: 'string' }, primary: { const: true }, note: { const: 'required' }, fields: list(text),
|
|
106
|
-
options: list({ type: 'object' }) };
|
|
107
|
-
const CHOICE = object({ ...CHOICE_FACTS, more: list(object(CHOICE_FACTS, ['id', 'name'])) }, ['id', 'name']);
|
|
108
|
-
// A user task of this round: whom an open one waits on (`agent`, `input` the user) since when, its ID (what `task` answers),
|
|
109
|
-
// its card while open and the answers it offers (`choices`, as the process declares them: `more` held one level down), whether
|
|
110
|
-
// its card has fields to fill (`form`, answered there), whether its holding session is told of it only with its next input
|
|
111
|
-
// (`toldAlong`); what it asks the agent (`instructions`, not said of one for the user); how a decided one was.
|
|
112
|
-
export const TASK = object({
|
|
113
|
-
step: text, name: text, state: { enum: ['pending', 'skipped', 'agent', 'input', 'succeeded', 'failed', 'cancelled'] },
|
|
114
|
-
task: text, assignee: { enum: ['agent', 'user'] }, holder: text, card: text, since: time, choices: list(CHOICE), form: { const: true },
|
|
115
|
-
toldAlong: { const: true }, instructions: text,
|
|
116
|
-
startedAt: time, finishedAt: timeOrNull, decidedBy: text, note: text,
|
|
117
|
-
}, ['step', 'name', 'state']);
|
|
118
|
-
// Where a node, or an instance of it, stands this round, as its kind, its step or its task says (workflow-graph.mjs `shown`).
|
|
119
|
-
const NODE_STATE = { enum: ['pending', 'queued', 'running', 'waiting', 'agent', 'input', 'finishing', 'succeeded', 'failed', 'cancelled', 'skipped'] };
|
|
120
|
-
// What a node of the process is (workflow-graph.mjs `bpmnGraph`): an event node by its event (a caught error is `boundary`).
|
|
121
|
-
const NODE_KIND = { enum: ['start', 'end', 'event', 'job', 'action', 'task', 'call', 'manual', 'step', 'subprocess', 'gateway', 'boundary',
|
|
122
|
-
'timer', 'message', 'signal', 'conditional', 'escalation', 'link', 'compensation', 'cancel'] };
|
|
123
|
-
// Where the run is while it goes (workflowGraph `current`): each instance going that nothing else goes inside, since when,
|
|
124
|
-
// and when one waiting on a timer is due.
|
|
125
|
-
export const PLACE = object({ node: text, executionId: text, name: text, kind: NODE_KIND, parent: text, state: NODE_STATE, since: time, dueAt: time },
|
|
126
|
-
['node', 'name', 'kind', 'state', 'since']);
|
|
127
|
-
// An event it listens for meanwhile, no instance of its node until it happens (workflowGraph `listening`): a boundary
|
|
128
|
-
// event beside an activity (`attachedTo`), one an event-based gateway races, a start event of an event subprocess; by
|
|
129
|
-
// its kind, the message it waits for or the timer it is set to and when that is due, since when it listens.
|
|
130
|
-
export const LISTENING = object({ node: text, executionId: text, name: text, kind: NODE_KIND, parent: text, attachedTo: text,
|
|
131
|
-
message: text, timer: text, since: time, dueAt: time }, ['node', 'name', 'kind']);
|
|
132
|
-
// The runs a node called (`run-workflows`, a call activity).
|
|
133
|
-
export const CALLED = list(object({ run: text, workflow: workflowName, name: text, state: RUN_STATE }, ['run', 'workflow', 'name', 'state']));
|
|
134
|
-
// The whole drawing of the run (`graph`): each node as the process declares it (`bpmnGraph`) with where it stands this
|
|
135
|
-
// round (its latest instance, how many and how they ended, whether it is only listened for, the line it shows), each flow
|
|
136
|
-
// with how often it was taken, and where the run is. A node's step or task is the status's job of the same id.
|
|
137
|
-
export const GRAPH = object({
|
|
138
|
-
nodes: list(object({
|
|
139
|
-
id: text, name: text, kind: NODE_KIND, type: text,
|
|
140
|
-
triggeredByEvent: { const: true }, throw: { const: true }, eventGateway: text, interrupting: { const: false },
|
|
141
|
-
loop: { enum: ['sequential', 'parallel'] }, forCompensation: { const: true }, lane: text,
|
|
142
|
-
inspect: list(object({ label: text, type: { enum: ['string', 'number', 'boolean', 'timestamp'] }, value: text, phase: { enum: ['input', 'output'] } },
|
|
143
|
-
['label', 'type', 'value', 'phase'])),
|
|
144
|
-
parent: text, attachedTo: text, group: text, action: text, message: text, timer: text,
|
|
145
|
-
state: NODE_STATE, visits: count, counts: object({ active: count, succeeded: count, failed: count, cancelled: count }, ['active', 'succeeded', 'failed', 'cancelled']),
|
|
146
|
-
executionId: text, startedAt: time, finishedAt: time, dueAt: time, listener: { const: true }, detail: text, since: time, called: CALLED,
|
|
147
|
-
}, ['id', 'name', 'kind', 'type', 'state'])),
|
|
148
|
-
edges: list(object({ id: text, from: text, to: text, name: text, default: { const: true }, boundary: { const: true }, link: { const: true },
|
|
149
|
-
compensation: { const: true }, taken: count }, ['id', 'from', 'to'])),
|
|
150
|
-
current: list(PLACE), listening: list(LISTENING),
|
|
151
|
-
}, ['nodes', 'edges', 'current', 'listening']);
|
|
152
|
-
// A round the run went (its first, then each resume or re-run): for which session it was, if any, by the user or not, and
|
|
153
|
-
// where in that session's history it started and ended (`startedAfterSeq`, `afterSeq`); whether its end is told (`reportResult`),
|
|
154
|
-
// whether it went on where the last failed (`resumed`), and how it ended.
|
|
155
|
-
export const ROUND = object({ session: text, startedAt: time, startedAfterSeq: { type: ['integer', 'null'] }, byUser: { const: true }, reportResult: flag,
|
|
156
|
-
resumed: { const: true }, state: RUN_STATE, endedAt: time, afterSeq: { type: ['integer', 'null'] } }, ['startedAt']);
|
|
157
|
-
export const RUN_STATUS = object({
|
|
158
|
-
state: RUN_STATE, attempt: { type: 'integer', minimum: 1 }, rounds: list(ROUND),
|
|
159
|
-
// Where it is and what it listens for, while it goes (empty once it ended); the whole drawing is `graph`'s.
|
|
160
|
-
current: list(PLACE), listening: list(LISTENING),
|
|
161
|
-
// `lineLive`: whether the step that wrote the line still runs; once it ended, the line stays and says so.
|
|
162
|
-
title: text, line: text, lineLive: flag,
|
|
163
|
-
stages: list(object({ id: text, name: text, state: { enum: ['pending', 'running', 'agent', 'input', 'succeeded', 'failed', 'cancelled', 'skipped'] } },
|
|
164
|
-
['id', 'name', 'state'])),
|
|
165
|
-
messages: list(object({ name: { type: 'string', pattern: '^user\\.' }, label: text }, ['name', 'label'])),
|
|
166
|
-
// The steps for the user's eyes only (`coda:audience="user"`), not among `jobs`: the user's page reads them with `private`.
|
|
167
|
-
userOnly: list(text),
|
|
168
|
-
cancelRequested: { const: true }, rerun: { enum: ['resume', 'start', 'caller'] }, ahead: count,
|
|
169
|
-
workspace: object({ state: { enum: ['active', 'retained', 'reclaimed'] }, cleanupAfter: timeOrNull, reclaimedAt: timeOrNull },
|
|
170
|
-
['state', 'cleanupAfter', 'reclaimedAt']),
|
|
171
|
-
createdAt: time, startedAt: timeOrNull, finishedAt: timeOrNull,
|
|
172
|
-
// How it ended: what went wrong, what it gives, and the outcome told to whoever started it.
|
|
173
|
-
error: text, outputs: OUTPUTS, result: text,
|
|
174
|
-
jobs: list(JOB), tasks: list(TASK),
|
|
175
|
-
called: CALLED,
|
|
176
|
-
// A text that changes as what `requirement` gives does (the runs under it moving among it), for a page to ask it again by.
|
|
177
|
-
requirementRevision: text,
|
|
178
|
-
}, ['state', 'attempt', 'current', 'listening', 'createdAt', 'startedAt', 'finishedAt', 'jobs', 'tasks', 'called'],
|
|
179
|
-
{ dependentRequired: { line: ['lineLive'] } });
|
|
180
|
-
|
|
181
|
-
// A node's instances in this round, newest last, a page at a time (components/workflows/workflow-run-records.mjs
|
|
182
|
-
// `nodeHistory`): each with what it was given and gave, the conditions it took its way by, the attempt or task it was and
|
|
183
|
-
// the runs it called. `next` is the `before` of the page before it, null at the first.
|
|
184
|
-
const FIELD = object({ label: text, type: text, source: text, value: { type: ['string', 'number', 'boolean'] },
|
|
185
|
-
missing: { const: true }, truncated: { const: true }, sourceLabel: text }, ['source']);
|
|
186
|
-
const INSTANCE = object({
|
|
187
|
-
executionId: text, ordinal: count, parent: text, iteration: { type: ['integer', 'null'] },
|
|
188
|
-
state: NODE_STATE,
|
|
189
|
-
startedAt: time, endedAt: timeOrNull, dueAt: timeOrNull,
|
|
190
|
-
inputs: list(FIELD), outputs: list(FIELD),
|
|
191
|
-
conditions: list(object({ id: text, name: text, expression: text, inputs: list(FIELD), label: text, default: flag, error: text, result: flag }, ['id'])),
|
|
192
|
-
taken: list(text), error: text,
|
|
193
|
-
attempt: object({ attempt: { type: 'integer', minimum: 1 }, state: JOB_STATE, queuedAt: timeOrNull, startedAt: timeOrNull,
|
|
194
|
-
finishedAt: timeOrNull, error: text }, ['attempt', 'state']),
|
|
195
|
-
task: object({ state: { enum: ['open', 'completed', 'rejected', 'withdrawn'] }, assignee: { enum: ['agent', 'user'] }, decidedBy: text, note: text },
|
|
196
|
-
['state', 'assignee']),
|
|
197
|
-
called: list(object({ run: text, workflow: workflowName, state: RUN_STATE }, ['run', 'workflow', 'state'])),
|
|
198
|
-
}, ['executionId', 'state', 'startedAt']);
|
|
199
|
-
const HISTORY = object({ instances: list(INSTANCE), retainedInstances: count, historyPruned: flag,
|
|
200
|
-
next: { type: ['integer', 'null'], minimum: 1 } }, ['instances', 'retainedInstances', 'historyPruned', 'next']);
|
|
201
|
-
// The requirement the run was started for (components/workflows/workflow-run-records.mjs `requirement`): its words, every run
|
|
202
|
-
// under it (each by the node of its caller that called it and that caller's round), the sessions its steps and its own agent
|
|
203
|
-
// are, and the user tasks of those runs — each kept to its share of the bytes, `truncated` saying which was cut.
|
|
204
|
-
const REQUIREMENT = object({
|
|
205
|
-
message: { type: 'string' },
|
|
206
|
-
truncated: object({ message: flag, runs: flag, sessions: flag, tasks: flag }, ['message', 'runs', 'sessions', 'tasks']),
|
|
207
|
-
runs: list(object({ run: text, workflow: workflowName, name: text, state: RUN_STATE, error: text, createdAt: time, startedAt: timeOrNull, finishedAt: timeOrNull,
|
|
208
|
-
parent: text, node: object({ id: text, name: text }, ['id', 'name']), round: { type: 'integer', minimum: 1 }, callerRound: { type: 'integer', minimum: 1 },
|
|
209
|
-
outputs: OUTPUTS }, ['run', 'workflow', 'name', 'state', 'createdAt', 'startedAt', 'finishedAt', 'outputs'])),
|
|
210
|
-
sessions: list(object({ session: text, title: { type: 'string' }, agent: text, archived: flag,
|
|
211
|
-
role: object({ main: { const: true }, run: text, node: text, name: text, attempt: { type: 'integer', minimum: 1 }, step: { type: ['integer', 'null'], minimum: 0 } }, ['run']) },
|
|
212
|
-
['session', 'title', 'agent', 'archived', 'role'])),
|
|
213
|
-
tasks: list(object({ task: text, run: text, round: { type: 'integer', minimum: 1 }, node: text, name: text, state: { enum: ['open', 'completed', 'rejected', 'withdrawn'] },
|
|
214
|
-
assignee: { enum: ['agent', 'user'] }, turn: { enum: ['agent', 'user'] }, holder: text, decidedBy: text, choice: object({ id: text, name: text }, ['id', 'name']),
|
|
215
|
-
note: text, createdAt: time, decidedAt: timeOrNull }, ['task', 'run', 'round', 'node', 'name', 'state', 'assignee', 'createdAt', 'decidedAt'])),
|
|
216
|
-
}, ['message', 'truncated', 'runs', 'sessions', 'tasks']);
|
|
217
|
-
// How each of its jobs ended in the latest runs of its workflow in its directory that ended, up to it, oldest first; null in
|
|
218
|
-
// one a job did not run in.
|
|
219
|
-
const RECENT = object({ jobs: list(object({ job: text, history: list({ enum: [...JOB_STATE.enum, null] }) }, ['job', 'history'])) }, ['jobs']);
|
|
220
|
-
|
|
221
|
-
export const WORKFLOW_PROTOCOL = {
|
|
222
|
-
kind: WORKFLOW,
|
|
223
|
-
title: '流程',
|
|
224
|
-
// What the workflow is, as `workflow_list` gives each (components/workflows/workflow-definitions.mjs `list`): of which
|
|
225
|
-
// directory and by which name, a plugin's when a plugin brings it (and the directory has no file of that name), a
|
|
226
|
-
// capability when it is only called; read from the directory's default branch as last fetched, or the plugin. Its
|
|
227
|
-
// inputs, whether it runs only merged commits, whether it can be started by hand, the hooks it joins, the events that
|
|
228
|
-
// start it by themselves, its schedule, its key, its `coda:autoRun`, whether it follows sessions from their opening;
|
|
229
|
-
// or, for one that cannot be read, why (`error`) instead.
|
|
230
|
-
// No `runsOn`: the executors are gone (结构减负), and `listed()` no longer gives the labels a workflow's steps need.
|
|
231
|
-
spec: object({
|
|
232
|
-
project: text, workflow: workflowName, plugin: text, capability: { const: true },
|
|
233
|
-
name: text, inputs: { type: 'object', additionalProperties: object(INPUT, ['type']) },
|
|
234
|
-
mergedOnly: flag, manual: flag,
|
|
235
|
-
joins: list(object({ hook: text, name: text, detail: text, default: flag, order: { type: 'number' },
|
|
236
|
-
inputs: list(object({ id: text, label: text }, ['id', 'label'])) }, ['hook', 'default'])),
|
|
237
|
-
startedBy: list(text), schedule: object({ cycle: text, once: flag }, ['cycle', 'once']),
|
|
238
|
-
key: text, autoRun: text, lifecycle: { const: true },
|
|
239
|
-
error: text,
|
|
240
|
-
}, ['project', 'workflow'], { oneOf: [{ required: ['error'] }, { required: ['name', 'inputs', 'mergedOnly', 'manual'] }] }),
|
|
241
|
-
// What changes of it in its directory: the branch and commit it was read from (none for a plugin's), what was set for
|
|
242
|
-
// it in the directory, its schedule there (when it next starts, or why it does not), the events it starts on that
|
|
243
|
-
// nothing here publishes, and the plugins that bring the same name when two do (it is refused until one is disabled).
|
|
244
|
-
status: object({
|
|
245
|
-
ref: text, commit: text,
|
|
246
|
-
settings: object({ enabled: flag, inputs: { type: 'object', additionalProperties: RULE } }, ['inputs']),
|
|
247
|
-
schedule: object({ cycle: text, next: timeOrNull, off: { const: true }, error: text, project: text }, ['cycle']),
|
|
248
|
-
unheard: list(text), conflicts: list(text),
|
|
249
|
-
}, ['settings']),
|
|
250
|
-
operations: {
|
|
251
|
-
// Starts it from `session`, as the session's "+" does (`workflow_run`, as the user's): on the newest commit of the
|
|
252
|
-
// session's branch, with `inputs` (the rest as the session sets them, else as declared) and `message`, the requirement
|
|
253
|
-
// it goes with, sent into the session as the user's message. A call here has no session of its own: no `commit`, and
|
|
254
|
-
// no `confirm`: the card only a session's agent can propose (its workflow tool's own arguments), and this way does not take it.
|
|
255
|
-
run: { input: object({
|
|
256
|
-
session: text, inputs: { type: 'object', additionalProperties: VALUE }, message: { type: 'string', maxLength: MESSAGE_LIMIT },
|
|
257
|
-
}, ['session']),
|
|
258
|
-
result: object({ run: text, status: RUN_STATUS, reused: { const: true } }, ['run', 'status']) },
|
|
259
|
-
// What is set for it as `session` sees it, or as set for its directory without one.
|
|
260
|
-
settings: { safe: true, input: object({ session: text }), result: SETTINGS },
|
|
261
|
-
// Sets it, from `session`, for the session alone or for its directory (`project`): whether the events that start it do
|
|
262
|
-
// (`enabled`, null goes back to what comes after) and its inputs' rules (null clears one). Set for the directory, the
|
|
263
|
-
// session drops its own of what was set, following its directory. Gives what `settings` gives after, for the session.
|
|
264
|
-
'save-settings': { idempotent: true, input: object({
|
|
265
|
-
scope: { enum: ['session', 'project'] }, session: text, enabled: { type: ['boolean', 'null'] },
|
|
266
|
-
inputs: { type: 'object', additionalProperties: { anyOf: [RULE, { type: 'null' }] } },
|
|
267
|
-
}, ['scope', 'session']), result: SETTINGS },
|
|
268
|
-
},
|
|
269
|
-
// What a plugin may ask for in its `uses` (docs/plugins.md「用到的权限」), on trial while the protocol is not stable.
|
|
270
|
-
permissions: {
|
|
271
|
-
read: { title: '查看各目录里可用的流程与它们的设置', trial: true, read: true, operations: ['settings'] },
|
|
272
|
-
run: { title: '发起流程', trial: true, operations: ['run'] },
|
|
273
|
-
configure: { title: '修改流程在会话或目录里的设置', trial: true, operations: ['save-settings'] },
|
|
274
|
-
},
|
|
275
|
-
// Its doing operations are the workflows', on the backend that holds the record (`workflowOperations`).
|
|
276
|
-
side: 'workflows',
|
|
277
|
-
};
|
|
278
|
-
|
|
279
|
-
// The workflows of a session's directory, as its workflows panel reads them as it opens (#2749 3.5: what a panel takes at
|
|
280
|
-
// once is one query of the record it is of): a query of `coda/thread@1` the workflows answer, added to it as it is
|
|
281
|
-
// registered (`withWorkflows`). Each workflow the user may start there, or an event may (not a capability, which is called,
|
|
282
|
-
// nor a lifecycle, which follows sessions, nor one only a schedule starts): its record's ID and what it is, and what is set
|
|
283
|
-
// for it as the session sees it (not for one that cannot be read); what the session's sources give now; and why the
|
|
284
|
-
// directory's own could not be read, when they could not (no `origin/main`, no repository: `error`), so that none read is
|
|
285
|
-
// not none there; a plugin's, which plugin by its name. A group of its own, not `read`'s: it says what is set.
|
|
286
|
-
export const THREAD_WORKFLOWS = {
|
|
287
|
-
safe: true, input: object({}),
|
|
288
|
-
result: object({
|
|
289
|
-
project: text,
|
|
290
|
-
workflows: list(object({ id: text, spec: WORKFLOW_PROTOCOL.spec, plugin: object({ id: text, name: text }, ['id', 'name']), settings: object(SEEN, ['inputs']) }, ['id', 'spec'])),
|
|
291
|
-
sources: SOURCE_VALUES, error: text,
|
|
292
|
-
}, ['project', 'workflows', 'sources']),
|
|
293
|
-
};
|
|
294
|
-
export const withWorkflows = protocol => ({ ...protocol, operations: { ...protocol.operations, workflows: THREAD_WORKFLOWS },
|
|
295
|
-
permissions: { ...protocol.permissions, workflows: { title: '查看会话的目录里能发起的流程,以及它们在这个会话里的设置', trial: true, operations: ['workflows'] } } });
|
|
296
|
-
|
|
297
|
-
export const WORKFLOW_RUN_PROTOCOL = {
|
|
298
|
-
kind: WORKFLOW_RUN,
|
|
299
|
-
title: '流程运行',
|
|
300
|
-
// Where the run comes from: the workflow of which directory (its record `workflowRecordId(project, workflow)`), a
|
|
301
|
-
// plugin's or a capability, under which name; the commit and branch it runs on (none for a plugin's that checks nothing
|
|
302
|
-
// out; a resume with `commit` moves it), the inputs it was started with as resolved, the requirement it goes with, its
|
|
303
|
-
// key; and who started it (`origin`): an agent, the user, an event, a schedule or another run (`parent`), for which
|
|
304
|
-
// session (`session`, whom it reports to), and for a session's lifecycle, the session it follows (`subject`).
|
|
305
|
-
spec: object({
|
|
306
|
-
project: text, workflow: workflowName, plugin: text, capability: { const: true }, name: text,
|
|
307
|
-
commit: textOrNull, ref: textOrNull,
|
|
308
|
-
inputs: { type: 'object', additionalProperties: RESOLVED },
|
|
309
|
-
message: { type: 'string', maxLength: MESSAGE_LIMIT }, key: text,
|
|
310
|
-
origin: object({ by: { enum: ['agent', 'user', 'event', 'schedule', 'run'] }, session: text, parent: text, event: text, subject: text }, ['by']),
|
|
311
|
-
}, ['project', 'workflow', 'name', 'commit', 'ref', 'inputs', 'origin']),
|
|
312
|
-
status: RUN_STATUS,
|
|
313
|
-
operations: {
|
|
314
|
-
// Cancels a run waiting or going (`workflow_cancel`); renews a failed or cancelled one's workspace and artifacts for
|
|
315
|
-
// another stretch from now (`workflow_renew`); resumes a failed or cancelled one (`workflow_resume`): where it failed,
|
|
316
|
-
// or from its start (`from`), on its commit, on `commit`, or on the newest commit of its branch (`latest`). Each
|
|
317
|
-
// gives the run as it stands after.
|
|
318
|
-
cancel: { input: object({}), result: RUN_STATUS },
|
|
319
|
-
renew: { input: object({}), result: RUN_STATUS },
|
|
320
|
-
resume: { input: object({ commit: text, from: { type: 'string', enum: ['start'] }, latest: { const: true } }, [], { not: { required: ['commit', 'latest'] } }),
|
|
321
|
-
result: RUN_STATUS },
|
|
322
|
-
// Answers a task the run gave the caller's session (`workflow_task`), which only the task's holder may — a caller that
|
|
323
|
-
// is no session (the user, through a plugin's page), one that waits on the user —: `completed` with the `choice`
|
|
324
|
-
// taken, its `options` and their `inputs`, or `rejected`, with `note`; or hands it up (`handUp`) to the level above,
|
|
325
|
-
// with what is to be done in `note`, which only a session does.
|
|
326
|
-
task: { input: object({
|
|
327
|
-
task: text, result: { type: 'string', enum: ['completed', 'rejected'] }, handUp: flag, choice: text,
|
|
328
|
-
options: { type: 'object', additionalProperties: flag },
|
|
329
|
-
inputs: { type: 'object', additionalProperties: { type: 'string', maxLength: INPUT_LIMIT } },
|
|
330
|
-
note: { type: 'string', maxLength: INPUT_LIMIT },
|
|
331
|
-
}, ['task'], { if: { properties: { handUp: { const: true } }, required: ['handUp'] }, then: { required: ['note'] }, else: { required: ['result'] } }),
|
|
332
|
-
result: object({ task: text, name: text, result: { enum: ['completed', 'rejected'] }, choice: text, handedUp: { const: true } }, ['task', 'name'],
|
|
333
|
-
{ oneOf: [{ required: ['result'] }, { required: ['handedUp'] }] }) },
|
|
334
|
-
// A message from the user that the run waits on (one of its status's `messages`), as its page's button sends it.
|
|
335
|
-
message: { input: object({ name: { type: 'string', pattern: '^user\\.' } }, ['name']), result: RUN_STATUS },
|
|
336
|
-
// A page of a node's instances in this round, before `before` (a page's `next`), the latest without.
|
|
337
|
-
history: { safe: true, input: object({ node: text, before: { type: 'integer', minimum: 1 } }, ['node']), result: HISTORY },
|
|
338
|
-
// The whole drawing of the run as it stands, for its page to draw.
|
|
339
|
-
graph: { safe: true, input: object({}), result: GRAPH },
|
|
340
|
-
// The requirement it was started for, with the runs under it, their sessions and tasks; asked again as its status's
|
|
341
|
-
// `requirementRevision` changes.
|
|
342
|
-
requirement: { safe: true, input: object({}), result: REQUIREMENT },
|
|
343
|
-
// Its jobs' results in the latest runs of its workflow in its directory.
|
|
344
|
-
recent: { safe: true, input: object({}), result: RECENT },
|
|
345
|
-
// Its steps for the user's eyes only (its status's `userOnly`), as the user's page shows them: refused to a session.
|
|
346
|
-
private: { safe: true, input: object({}), result: object({ jobs: list(JOB) }, ['jobs']) },
|
|
347
|
-
},
|
|
348
|
-
// A step's output as it is (`text/plain`), from byte `after` to its end as it is read, not cut and not followed: step `step`
|
|
349
|
-
// of the job, or the job's own log (`job`), of its current attempt or of `attempt` (transport/record-streams.mjs). Read on
|
|
350
|
-
// from where it was (`after`, the bytes read), the attempt is named, so that one begun meanwhile is not read on.
|
|
351
|
-
streams: {
|
|
352
|
-
log: { input: object({ job: text, step: { type: 'string', pattern: '^(?:[0-9]+|job)$' }, attempt: { type: 'string', pattern: '^[1-9][0-9]*$' },
|
|
353
|
-
after: { type: 'string', pattern: '^[0-9]+$' } }, ['job', 'step']) },
|
|
354
|
-
},
|
|
355
|
-
permissions: {
|
|
356
|
-
read: { title: '查看流程运行:进度、流程图、步骤、节点历史、日志、需求与最近的结果', trial: true, read: true,
|
|
357
|
-
operations: ['history', 'graph', 'requirement', 'recent', 'private'], streams: ['log'] },
|
|
358
|
-
control: { title: '取消、续期、重跑流程运行,或替你点运行在等的按钮', trial: true, operations: ['cancel', 'renew', 'resume', 'message'] },
|
|
359
|
-
task: { title: '答复流程交给会话的任务', trial: true, operations: ['task'] },
|
|
360
|
-
},
|
|
361
|
-
side: 'workflows',
|
|
362
|
-
};
|
|
@@ -1,144 +0,0 @@
|
|
|
1
|
-
import { createPrivateKey, createPublicKey, generateKeyPairSync, sign, verify } from 'node:crypto';
|
|
2
|
-
import { jcs } from './jcs.mjs';
|
|
3
|
-
|
|
4
|
-
// Accord records (AIP-01) and bindings (AIP-02): formats, signing and verification. Pure: keys are node:crypto KeyObjects.
|
|
5
|
-
|
|
6
|
-
export const MAX_RECORD_BYTES = 65536;
|
|
7
|
-
const KEY = /^ed25519:[0-9a-f]{64}$/;
|
|
8
|
-
const SIGNATURE = /^[0-9a-f]{128}$/;
|
|
9
|
-
const KIND = /^[a-z0-9-]{1,64}(\/[a-z0-9-]{1,64})?$/;
|
|
10
|
-
// RFC 8410: SubjectPublicKeyInfo of an Ed25519 key is this prefix followed by the 32 raw bytes.
|
|
11
|
-
const SPKI_PREFIX = Buffer.from('302a300506032b6570032100', 'hex');
|
|
12
|
-
const RECORD_DOMAIN = 'accord:record:1\n';
|
|
13
|
-
const CERT_DOMAIN = 'accord:cert:1\n';
|
|
14
|
-
const CERT_FIELDS = ['key', 'from', 'until', 'sig'];
|
|
15
|
-
|
|
16
|
-
const isObject = value => value !== null && typeof value === 'object' && !Array.isArray(value);
|
|
17
|
-
const isTime = value => Number.isSafeInteger(value) && value >= 0;
|
|
18
|
-
const bytes = text => Buffer.byteLength(text, 'utf8');
|
|
19
|
-
|
|
20
|
-
export const isAccordKind = kind => typeof kind === 'string' && KIND.test(kind);
|
|
21
|
-
|
|
22
|
-
export function generateIdentity() {
|
|
23
|
-
const { publicKey, privateKey } = generateKeyPairSync('ed25519');
|
|
24
|
-
return { author: publicKeyToAuthor(publicKey), publicKey, privateKey };
|
|
25
|
-
}
|
|
26
|
-
|
|
27
|
-
export function publicKeyToAuthor(publicKey) {
|
|
28
|
-
const der = publicKey.export({ format: 'der', type: 'spki' });
|
|
29
|
-
if (der.length !== SPKI_PREFIX.length + 32 || !der.subarray(0, SPKI_PREFIX.length).equals(SPKI_PREFIX)) {
|
|
30
|
-
throw new TypeError('不是 Ed25519 公钥');
|
|
31
|
-
}
|
|
32
|
-
return `ed25519:${der.subarray(SPKI_PREFIX.length).toString('hex')}`;
|
|
33
|
-
}
|
|
34
|
-
|
|
35
|
-
export function authorToPublicKey(author) {
|
|
36
|
-
if (typeof author !== 'string' || !KEY.test(author)) throw new TypeError('钥匙格式不合法');
|
|
37
|
-
return createPublicKey({ key: Buffer.concat([SPKI_PREFIX, Buffer.from(author.slice(8), 'hex')]), format: 'der', type: 'spki' });
|
|
38
|
-
}
|
|
39
|
-
|
|
40
|
-
const isEd25519 = privateKey => privateKey?.type === 'private' && privateKey.asymmetricKeyType === 'ed25519';
|
|
41
|
-
const signed = (domain, value, privateKey) => {
|
|
42
|
-
if (!isEd25519(privateKey)) throw new TypeError('签名须用 Ed25519 私钥');
|
|
43
|
-
return sign(null, Buffer.from(domain + jcs(value), 'utf8'), privateKey).toString('hex');
|
|
44
|
-
};
|
|
45
|
-
const verified = (domain, value, signature, key) => verify(null, Buffer.from(domain + jcs(value), 'utf8'), authorToPublicKey(key), Buffer.from(signature, 'hex'));
|
|
46
|
-
|
|
47
|
-
function certBodyProblem({ key, from, until }) {
|
|
48
|
-
if (typeof key !== 'string' || !KEY.test(key)) return '证书钥匙格式不合法';
|
|
49
|
-
if (!isTime(from) || !isTime(until) || from > until) return '证书有效期不合法';
|
|
50
|
-
return null;
|
|
51
|
-
}
|
|
52
|
-
|
|
53
|
-
function certProblem(cert) {
|
|
54
|
-
if (!isObject(cert)) return '证书不是对象';
|
|
55
|
-
if (Object.keys(cert).length !== CERT_FIELDS.length || !CERT_FIELDS.every(name => Object.hasOwn(cert, name))) return '证书字段不符';
|
|
56
|
-
if (typeof cert.sig !== 'string' || !SIGNATURE.test(cert.sig)) return '证书签名格式不合法';
|
|
57
|
-
return certBodyProblem(cert);
|
|
58
|
-
}
|
|
59
|
-
|
|
60
|
-
/// A certificate: the author's signature over the key that may sign for them during [from, until].
|
|
61
|
-
export function signCert({ key, from, until }, authorPrivateKey) {
|
|
62
|
-
const body = { key, from, until };
|
|
63
|
-
const problem = certBodyProblem(body);
|
|
64
|
-
if (problem) throw new TypeError(problem);
|
|
65
|
-
return { ...body, sig: signed(CERT_DOMAIN, body, authorPrivateKey) };
|
|
66
|
-
}
|
|
67
|
-
|
|
68
|
-
export function verifyCert(cert, author) {
|
|
69
|
-
const problem = certProblem(cert);
|
|
70
|
-
if (problem) return { ok: false, reason: problem };
|
|
71
|
-
if (typeof author !== 'string' || !KEY.test(author)) return { ok: false, reason: '作者钥匙格式不合法' };
|
|
72
|
-
const { key, from, until, sig } = cert;
|
|
73
|
-
return verified(CERT_DOMAIN, { key, from, until }, sig, author) ? { ok: true } : { ok: false, reason: '证书签名不符' };
|
|
74
|
-
}
|
|
75
|
-
|
|
76
|
-
function recordProblem(record) {
|
|
77
|
-
if (!isObject(record)) return '记录不是对象';
|
|
78
|
-
if (Object.hasOwn(record, 'gone')) return '记录顶层不能有 gone';
|
|
79
|
-
if (typeof record.author !== 'string' || !KEY.test(record.author)) return '作者钥匙格式不合法';
|
|
80
|
-
if (typeof record.id !== 'string' || bytes(record.id) < 1 || bytes(record.id) > 256) return 'id 须为 1 到 256 字节';
|
|
81
|
-
if (!isAccordKind(record.kind)) return '种类不合法';
|
|
82
|
-
if (!isTime(record.version)) return 'version 须为安全非负整数';
|
|
83
|
-
if (Object.hasOwn(record, 'body') && !isObject(record.body)) return 'body 须为对象';
|
|
84
|
-
return null;
|
|
85
|
-
}
|
|
86
|
-
|
|
87
|
-
export function signRecord(record, signerPrivateKey) {
|
|
88
|
-
if (isObject(record) && Object.hasOwn(record, 'sig')) throw new TypeError('待签记录不能已有 sig');
|
|
89
|
-
const problem = recordProblem(record);
|
|
90
|
-
if (problem) throw new TypeError(problem);
|
|
91
|
-
const full = { ...record, sig: signed(RECORD_DOMAIN, record, signerPrivateKey) };
|
|
92
|
-
const checked = verifyRecord(full);
|
|
93
|
-
if (!checked.ok) throw new TypeError(checked.reason);
|
|
94
|
-
return full;
|
|
95
|
-
}
|
|
96
|
-
|
|
97
|
-
export function verifyRecord(record) {
|
|
98
|
-
const problem = recordProblem(record);
|
|
99
|
-
if (problem) return { ok: false, reason: problem };
|
|
100
|
-
if (typeof record.sig !== 'string' || !SIGNATURE.test(record.sig)) return { ok: false, reason: '签名格式不合法' };
|
|
101
|
-
const { sig, ...rest } = record;
|
|
102
|
-
let whole;
|
|
103
|
-
try { whole = jcs(record); } catch (error) { return { ok: false, reason: `记录不能规范化:${error.message}` }; }
|
|
104
|
-
if (bytes(whole) > MAX_RECORD_BYTES) return { ok: false, reason: '记录超过 64 KiB' };
|
|
105
|
-
let signer = record.author;
|
|
106
|
-
if (Object.hasOwn(record, 'cert')) {
|
|
107
|
-
const certified = verifyCert(record.cert, record.author);
|
|
108
|
-
if (!certified.ok) return certified;
|
|
109
|
-
if (record.version < record.cert.from || record.version > record.cert.until) return { ok: false, reason: 'version 不在证书有效期内' };
|
|
110
|
-
signer = record.cert.key;
|
|
111
|
-
}
|
|
112
|
-
return verified(RECORD_DOMAIN, rest, sig, signer) ? { ok: true } : { ok: false, reason: '签名不符' };
|
|
113
|
-
}
|
|
114
|
-
|
|
115
|
-
/// AIP-02: the record by which an author says that `endpoint` speaks for them in `scope`.
|
|
116
|
-
const bindingProblem = (scope, endpoint) => {
|
|
117
|
-
if (typeof scope !== 'string' || scope === '') return 'scope 须为非空字符串';
|
|
118
|
-
if (typeof endpoint !== 'string' || endpoint === '') return 'endpoint 须为非空字符串';
|
|
119
|
-
return null;
|
|
120
|
-
};
|
|
121
|
-
|
|
122
|
-
export function signBinding({ author, id, version, scope, endpoint, cert }, signerPrivateKey) {
|
|
123
|
-
const problem = bindingProblem(scope, endpoint);
|
|
124
|
-
if (problem) throw new TypeError(problem);
|
|
125
|
-
const record = { author, id, kind: 'binding', version, body: { scope, endpoint } };
|
|
126
|
-
if (cert !== undefined) record.cert = cert;
|
|
127
|
-
return signRecord(record, signerPrivateKey);
|
|
128
|
-
}
|
|
129
|
-
|
|
130
|
-
export function verifyBinding(record, { scope, endpoint, now = Date.now(), clockSkewMs = 5 * 60_000 }) {
|
|
131
|
-
const expected = bindingProblem(scope, endpoint);
|
|
132
|
-
if (expected) return { ok: false, reason: `期望的${expected}` };
|
|
133
|
-
const checked = verifyRecord(record);
|
|
134
|
-
if (!checked.ok) return checked;
|
|
135
|
-
if (record.kind !== 'binding') return { ok: false, reason: '不是绑定记录' };
|
|
136
|
-
const stated = bindingProblem(record.body?.scope, record.body?.endpoint);
|
|
137
|
-
if (stated) return { ok: false, reason: `记录的${stated}` };
|
|
138
|
-
if (record.body?.scope !== scope) return { ok: false, reason: 'scope 不符' };
|
|
139
|
-
if (record.body?.endpoint !== endpoint) return { ok: false, reason: 'endpoint 不符' };
|
|
140
|
-
if (record.cert && !(now >= record.cert.from - clockSkewMs && now <= record.cert.until + clockSkewMs)) {
|
|
141
|
-
return { ok: false, reason: '证书不在有效期内' };
|
|
142
|
-
}
|
|
143
|
-
return { ok: true, author: record.author };
|
|
144
|
-
}
|