@powerhousedao/switchboard 6.2.3-dev.80 → 6.2.3-dev.82

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/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@powerhousedao/switchboard",
3
3
  "type": "module",
4
- "version": "6.2.3-dev.80",
4
+ "version": "6.2.3-dev.82",
5
5
  "main": "dist/index.mjs",
6
6
  "exports": {
7
7
  ".": {
@@ -88,24 +88,24 @@
88
88
  "@opentelemetry/sdk-node": "^0.218.0",
89
89
  "@opentelemetry/sdk-trace-base": "^2.7.1",
90
90
  "@opentelemetry/semantic-conventions": "^1.41.1",
91
- "@powerhousedao/config": "6.2.3-dev.80",
92
- "@powerhousedao/host-core": "6.2.3-dev.80",
93
- "@powerhousedao/opentelemetry-instrumentation-reactor": "6.2.3-dev.80",
94
- "@powerhousedao/reactor": "6.2.3-dev.80",
95
- "@powerhousedao/reactor-api": "6.2.3-dev.80",
96
- "@powerhousedao/reactor-attachments": "6.2.3-dev.80",
97
- "@powerhousedao/reactor-drive": "6.2.3-dev.80",
98
- "@powerhousedao/reactor-group": "6.2.3-dev.80",
99
- "@powerhousedao/reactor-privacy": "6.2.3-dev.80",
100
- "@powerhousedao/reactor-workflow": "6.2.3-dev.80",
101
- "@powerhousedao/shared": "6.2.3-dev.80",
102
- "@powerhousedao/vetra": "6.2.3-dev.80",
103
- "@powerhousedao/workflow": "6.2.3-dev.80",
91
+ "@powerhousedao/config": "6.2.3-dev.82",
92
+ "@powerhousedao/host-core": "6.2.3-dev.82",
93
+ "@powerhousedao/opentelemetry-instrumentation-reactor": "6.2.3-dev.82",
94
+ "@powerhousedao/reactor": "6.2.3-dev.82",
95
+ "@powerhousedao/reactor-api": "6.2.3-dev.82",
96
+ "@powerhousedao/reactor-attachments": "6.2.3-dev.82",
97
+ "@powerhousedao/reactor-drive": "6.2.3-dev.82",
98
+ "@powerhousedao/reactor-group": "6.2.3-dev.82",
99
+ "@powerhousedao/reactor-privacy": "6.2.3-dev.82",
100
+ "@powerhousedao/reactor-workflow": "6.2.3-dev.82",
101
+ "@powerhousedao/shared": "6.2.3-dev.82",
102
+ "@powerhousedao/vetra": "6.2.3-dev.82",
103
+ "@powerhousedao/workflow": "6.2.3-dev.82",
104
104
  "@pyroscope/nodejs": "^0.4.5",
105
- "@renown/sdk": "6.2.3-dev.80",
105
+ "@renown/sdk": "6.2.3-dev.82",
106
106
  "@sentry/node": "^10.53.1",
107
107
  "@sentry/opentelemetry": "^10.53.1",
108
- "document-model": "6.2.3-dev.80",
108
+ "document-model": "6.2.3-dev.82",
109
109
  "dotenv": "^16.4.7",
110
110
  "express": "^4.22.1",
111
111
  "graphql": "^16",
@@ -0,0 +1,141 @@
1
+ import { mkdtemp, rm } from "node:fs/promises";
2
+ import { createServer } from "node:net";
3
+ import { tmpdir } from "node:os";
4
+ import { join } from "node:path";
5
+ import type { ILogger } from "document-model";
6
+ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
7
+ import type { startSwitchboard, SwitchboardDeps } from "../src/server.mjs";
8
+ import { bootSwitchboard } from "./boot-helpers.js";
9
+
10
+ type Switchboard = Awaited<ReturnType<typeof startSwitchboard>>;
11
+
12
+ const SLUG = "ready-drive";
13
+
14
+ function stubLogger(): ILogger {
15
+ const logger = {
16
+ verbose: vi.fn(),
17
+ debug: vi.fn(),
18
+ info: vi.fn(),
19
+ warn: vi.fn(),
20
+ error: vi.fn(),
21
+ child: vi.fn(),
22
+ };
23
+ logger.child.mockReturnValue(logger);
24
+ return logger as unknown as ILogger;
25
+ }
26
+
27
+ const ENV = ["PH_REACTOR_DATABASE_URL", "FEATURE_PLUGIN_HOST_ENABLED"];
28
+ let previousEnv: (readonly [string, string | undefined])[] = [];
29
+ let tempRoots: string[] = [];
30
+ let running: Promise<Switchboard>[] = [];
31
+
32
+ beforeEach(() => {
33
+ previousEnv = ENV.map((name) => [name, process.env[name]] as const);
34
+ delete process.env.FEATURE_PLUGIN_HOST_ENABLED;
35
+ });
36
+
37
+ afterEach(async () => {
38
+ for (const booting of running.reverse()) {
39
+ await (await booting).shutdown();
40
+ }
41
+ running = [];
42
+ for (const [name, value] of previousEnv) {
43
+ if (value === undefined) delete process.env[name];
44
+ else process.env[name] = value;
45
+ }
46
+ for (const root of tempRoots) {
47
+ await rm(root, { recursive: true, force: true });
48
+ }
49
+ tempRoots = [];
50
+ });
51
+
52
+ function freePort(): Promise<number> {
53
+ return new Promise((resolve, reject) => {
54
+ const server = createServer();
55
+ server.once("error", reject);
56
+ server.listen(0, () => {
57
+ const address = server.address();
58
+ server.close(() =>
59
+ typeof address === "object" && address
60
+ ? resolve(address.port)
61
+ : reject(new Error("no port")),
62
+ );
63
+ });
64
+ });
65
+ }
66
+
67
+ /** Starts a boot without awaiting it, so `/ready` can be watched coming up. */
68
+ async function startBoot(deps: SwitchboardDeps = {}) {
69
+ const tempRoot = await mkdtemp(join(tmpdir(), "switchboard-ready-"));
70
+ tempRoots.push(tempRoot);
71
+ process.env.PH_REACTOR_DATABASE_URL = join(tempRoot, "reactor-storage");
72
+ const port = await freePort();
73
+ const booting = bootSwitchboard(
74
+ {
75
+ server: { port, strictPort: true },
76
+ storage: { readModel: { url: join(tempRoot, "read-model") } },
77
+ features: { workflows: false, mcp: false },
78
+ packages: { disableLocal: true },
79
+ identity: { keypairPath: join(tempRoot, "identity.json") },
80
+ drive: { slug: SLUG, global: { name: "Ready Drive" } },
81
+ },
82
+ { logger: stubLogger(), ...deps },
83
+ );
84
+ running.push(booting);
85
+ return { origin: `http://localhost:${port}`, booting };
86
+ }
87
+
88
+ async function readyStatus(origin: string): Promise<number | undefined> {
89
+ try {
90
+ return (await fetch(`${origin}/ready`)).status;
91
+ } catch {
92
+ return undefined;
93
+ }
94
+ }
95
+
96
+ async function untilReady(origin: string, timeoutMs = 60_000) {
97
+ const deadline = Date.now() + timeoutMs;
98
+ while (Date.now() < deadline) {
99
+ if ((await readyStatus(origin)) === 200) return;
100
+ await new Promise((resolve) => setTimeout(resolve, 5));
101
+ }
102
+ throw new Error(`${origin}/ready never turned 200`);
103
+ }
104
+
105
+ describe("switchboard readiness", () => {
106
+ it("serves the default drive once /ready is 200", async () => {
107
+ const { origin, booting } = await startBoot();
108
+
109
+ await untilReady(origin);
110
+ const drive = await fetch(`${origin}/d/${SLUG}`);
111
+
112
+ expect(drive.status).toBe(200);
113
+ await booting;
114
+ }, 60_000);
115
+
116
+ it("waits for the drives a caller seeds after start", async () => {
117
+ let seeded!: () => void;
118
+ const readyAfter = new Promise<void>((resolve) => {
119
+ seeded = resolve;
120
+ });
121
+ const { origin, booting } = await startBoot({ readyAfter });
122
+ await booting;
123
+
124
+ // Long past the point an unheld boot turns ready.
125
+ await new Promise((resolve) => setTimeout(resolve, 2_000));
126
+ expect(await readyStatus(origin)).toBe(503);
127
+
128
+ seeded();
129
+ await untilReady(origin, 10_000);
130
+ }, 60_000);
131
+
132
+ it("stays not ready when that seeding fails", async () => {
133
+ const readyAfter = Promise.reject(new Error("seeding failed"));
134
+ readyAfter.catch(() => undefined);
135
+ const { origin, booting } = await startBoot({ readyAfter });
136
+ await booting;
137
+
138
+ await new Promise((resolve) => setTimeout(resolve, 2_000));
139
+ expect(await readyStatus(origin)).toBe(503);
140
+ }, 60_000);
141
+ });
@@ -75,4 +75,28 @@ describe.each([
75
75
  expect(created[0].header.id).toBe("fixed");
76
76
  expect(created[0].header.protocolVersions).toEqual({ "base-reducer": 3 });
77
77
  });
78
+
79
+ it("makes a drive anew under its slug when its pinned id is one only a v2 create derives", async () => {
80
+ const { client: reactor, created } = client();
81
+ const errors: string[] = [];
82
+ // The id of a drive created as v2-required in another store
83
+ const pinned = "HRsIHuMMTdmjgCdy9QGWyx96zOFByPo787oBQcEt9f4";
84
+
85
+ const url = await add(
86
+ reactor,
87
+ { id: pinned, slug: "mail", global: { name: "Mail" } } as never,
88
+ 1,
89
+ { error: (message: string) => errors.push(message) },
90
+ );
91
+
92
+ // Created v2-required under a derived id, not as a legacy one claiming it
93
+ expect(created[0].header.id).not.toBe(pinned);
94
+ expect(created[0].header.protocolVersions).toEqual({
95
+ "base-reducer": 3,
96
+ signature: 2,
97
+ });
98
+ expect(created[0].header.slug).toBe("mail");
99
+ expect(url).toBe("http://localhost:1/d/mail");
100
+ expect(errors[0]).toContain(`pins ${pinned}`);
101
+ });
78
102
  });
@@ -271,6 +271,7 @@
271
271
  "PHID.serialize",
272
272
  "Query._service",
273
273
  "Query.workflowRuntime",
274
+ "SecretRecord.manageable",
274
275
  "URL.parseLiteral",
275
276
  "URL.parseValue",
276
277
  "URL.serialize",
@@ -3904,13 +3904,18 @@ type ReactorInfo {
3904
3904
  }
3905
3905
 
3906
3906
  """
3907
- Reads only. info and documentModels serve every caller; drive and document
3908
- reads are made as the caller through the reactor read gate; the rest need
3909
- one of the host's admins.
3907
+ Reads only. info, documentModels and loadsModelsOnDemand serve every caller;
3908
+ drive and document reads are made as the caller through the reactor read
3909
+ gate; the rest need one of the host's admins.
3910
3910
  """
3911
3911
  type ReactorInspection {
3912
3912
  info: ReactorInfo!
3913
3913
  documentModels: [InspectionDocumentModel!]!
3914
+ """
3915
+ True when a document model loads the first time a document of its type
3916
+ arrives, so documentModels names only those loaded so far.
3917
+ """
3918
+ loadsModelsOnDemand: Boolean!
3914
3919
  drives(cursor: String, limit: Int): InspectionDrivePage!
3915
3920
  """
3916
3921
  Reads every file node's document. Throttled per caller.
@@ -4038,6 +4043,14 @@ input SearchFilterInput {
4038
4043
  type SecretRecord {
4039
4044
  ref: String!
4040
4045
  label: String
4046
+ """
4047
+ The document the secret resolves for; null for a host secret (an OAuth app's).
4048
+ """
4049
+ ownerId: String
4050
+ """
4051
+ Whether the caller may rotate or delete it: its creator, able to write its owner.
4052
+ """
4053
+ manageable: Boolean!
4041
4054
  version: Int!
4042
4055
  status: String!
4043
4056
  createdAt: String!
@@ -4614,16 +4627,23 @@ type WorkflowRuntimeMutations {
4614
4627
  """
4615
4628
  rerun(runId: String!): WorkflowRunPayload!
4616
4629
  """
4617
- Mints a managed secret and returns its ref; the value is stored
4618
- encrypted and is never readable back over any API.
4630
+ Mints a managed secret for a connection or workflow document and returns
4631
+ its ref; only that document resolves it. The value is stored encrypted
4632
+ and is never readable back over any API.
4619
4633
  """
4620
- createSecret(value: String!, label: String): SecretRecord!
4634
+ createSecret(
4635
+ value: String!
4636
+ label: String
4637
+ documentId: String!
4638
+ ): SecretRecord!
4621
4639
  """
4622
4640
  Replaces the value behind an existing ref; documents stay untouched.
4641
+ Only its creator, while able to write its owning document.
4623
4642
  """
4624
4643
  rotateSecret(ref: String!, value: String!): SecretRecord!
4625
4644
  """
4626
- Tombstones a secret; its value becomes unrecoverable.
4645
+ Tombstones a secret; its value becomes unrecoverable. Only its creator,
4646
+ while able to write its owning document.
4627
4647
  """
4628
4648
  deleteSecret(ref: String!): Boolean!
4629
4649
  """
@@ -4812,7 +4832,8 @@ type WorkflowRuntimeQueries {
4812
4832
  """
4813
4833
  webhookEndpoint(workflowId: String!, driveId: String): WebhookEndpointRecord
4814
4834
  """
4815
- Secret metadata (label, version, status). Never the value.
4835
+ Secret metadata (label, version, status). Never the value. Only secrets
4836
+ whose owning document the caller can read.
4816
4837
  """
4817
4838
  secret(ref: String!): SecretRecord
4818
4839
  secrets: [SecretRecord!]!
@@ -605,6 +605,14 @@ type RuntimeHost {
605
605
  type SecretRecord {
606
606
  ref: String!
607
607
  label: String
608
+ """
609
+ The document the secret resolves for; null for a host secret (an OAuth app's).
610
+ """
611
+ ownerId: String
612
+ """
613
+ Whether the caller may rotate or delete it: its creator, able to write its owner.
614
+ """
615
+ manageable: Boolean!
608
616
  version: Int!
609
617
  status: String!
610
618
  createdAt: String!
@@ -800,16 +808,23 @@ type WorkflowRuntimeMutations {
800
808
  """
801
809
  rerun(runId: String!): WorkflowRunPayload!
802
810
  """
803
- Mints a managed secret and returns its ref; the value is stored
804
- encrypted and is never readable back over any API.
811
+ Mints a managed secret for a connection or workflow document and returns
812
+ its ref; only that document resolves it. The value is stored encrypted
813
+ and is never readable back over any API.
805
814
  """
806
- createSecret(value: String!, label: String): SecretRecord!
815
+ createSecret(
816
+ value: String!
817
+ label: String
818
+ documentId: String!
819
+ ): SecretRecord!
807
820
  """
808
821
  Replaces the value behind an existing ref; documents stay untouched.
822
+ Only its creator, while able to write its owning document.
809
823
  """
810
824
  rotateSecret(ref: String!, value: String!): SecretRecord!
811
825
  """
812
- Tombstones a secret; its value becomes unrecoverable.
826
+ Tombstones a secret; its value becomes unrecoverable. Only its creator,
827
+ while able to write its owning document.
813
828
  """
814
829
  deleteSecret(ref: String!): Boolean!
815
830
  """
@@ -998,7 +1013,8 @@ type WorkflowRuntimeQueries {
998
1013
  """
999
1014
  webhookEndpoint(workflowId: String!, driveId: String): WebhookEndpointRecord
1000
1015
  """
1001
- Secret metadata (label, version, status). Never the value.
1016
+ Secret metadata (label, version, status). Never the value. Only secrets
1017
+ whose owning document the caller can read.
1002
1018
  """
1003
1019
  secret(ref: String!): SecretRecord
1004
1020
  secrets: [SecretRecord!]!
@@ -4,7 +4,6 @@ import {
4
4
  createHttpAdapter,
5
5
  HttpRouteService,
6
6
  type Context,
7
- type IAuthorizationService,
8
7
  } from "@powerhousedao/reactor-api";
9
8
  import type { WorkflowRuntimeService } from "@powerhousedao/reactor-workflow";
10
9
  import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";
@@ -115,13 +114,12 @@ describe("startOAuth", () => {
115
114
  user: { address: "0xadmin" },
116
115
  }) as unknown as Context;
117
116
 
118
- function build(callbackUrl: string | undefined, isAdmin = true) {
117
+ function build(callbackUrl: string | undefined) {
119
118
  const runtime = {
120
119
  startOAuth: vi.fn(() => Promise.resolve({})),
121
120
  };
122
121
  const resolvers = getResolvers(
123
122
  runtime as unknown as WorkflowRuntimeService,
124
- { isSupremeAdmin: () => isAdmin } as unknown as IAuthorizationService,
125
123
  callbackUrl ? { callbackUrl } : undefined,
126
124
  ) as Record<string, Record<string, Resolver>>;
127
125
  return {
@@ -133,13 +131,6 @@ describe("startOAuth", () => {
133
131
 
134
132
  const PATH = "/api/@powerhousedao/workflow/oauth/callback";
135
133
 
136
- it("is an administrator's, like minting a secret", () => {
137
- const { start } = build(`https://sb.example${PATH}`, false);
138
- expect(() => start({}, { connectionId: "c1" }, ctx())).toThrow(
139
- "Admin access required",
140
- );
141
- });
142
-
143
134
  it("uses the host's own redirect when it knows its origin", async () => {
144
135
  const { runtime, start } = build(`https://sb.example${PATH}`);
145
136
  await start(
@@ -1,9 +1,7 @@
1
1
  // What the workflow subgraph does with the caller behind a request: every
2
- // workflow-scoped field hands it to the runtime, and secret writes are admins'.
3
- import type {
4
- Context,
5
- IAuthorizationService,
6
- } from "@powerhousedao/reactor-api";
2
+ // workflow-scoped field, secrets included, hands it to the runtime, which
3
+ // gates secrets on their owner document and creator rather than on admin.
4
+ import type { Context } from "@powerhousedao/reactor-api";
7
5
  import {
8
6
  WORKFLOW_SYNCING_MESSAGE,
9
7
  WorkflowSyncingError,
@@ -54,24 +52,20 @@ function fakeRuntime() {
54
52
  reactorAccessDenial: vi.fn((): string | undefined => undefined),
55
53
  testTrigger: vi.fn(() => Promise.resolve(null)),
56
54
  cancelTriggerTestFor: vi.fn(() => Promise.resolve(true)),
57
- secrets: vi.fn(() =>
58
- Promise.resolve({
59
- create: vi.fn(() => Promise.resolve({ ref: "secret://v1:00" })),
60
- rotate: vi.fn(() => Promise.resolve({ ref: "secret://v1:00" })),
61
- delete: vi.fn(() => Promise.resolve()),
62
- }),
63
- ),
55
+ createSecret: vi.fn(() => Promise.resolve({ ref: "secret://v1:00" })),
56
+ rotateSecret: vi.fn(() => Promise.resolve({ ref: "secret://v1:00" })),
57
+ deleteSecret: vi.fn(() => Promise.resolve()),
58
+ secretStat: vi.fn(() => Promise.resolve(null)),
59
+ listSecrets: vi.fn(() => Promise.resolve([])),
60
+ canManageSecret: vi.fn(() => Promise.resolve(false)),
61
+ secrets: vi.fn(),
64
62
  };
65
63
  }
66
64
 
67
- function build(isAdmin: boolean) {
65
+ function build() {
68
66
  const runtime = fakeRuntime();
69
- const authorizationService = {
70
- isSupremeAdmin: vi.fn(() => isAdmin),
71
- } as unknown as IAuthorizationService;
72
67
  const resolvers = getResolvers(
73
68
  runtime as unknown as WorkflowRuntimeService,
74
- authorizationService,
75
69
  undefined,
76
70
  undefined,
77
71
  (documentId) =>
@@ -83,12 +77,13 @@ function build(isAdmin: boolean) {
83
77
  runtime,
84
78
  queries: resolvers.WorkflowRuntimeQueries,
85
79
  mutations: resolvers.WorkflowRuntimeMutations,
80
+ secretRecord: resolvers.SecretRecord,
86
81
  };
87
82
  }
88
83
 
89
84
  describe("the workflow resolvers and the caller", () => {
90
85
  it("hands the caller to every workflow-scoped field", async () => {
91
- const { runtime, queries, mutations } = build(true);
86
+ const { runtime, queries, mutations } = build();
92
87
 
93
88
  await queries.webhookEndpoint({}, { workflowId: "wf-1" }, CTX);
94
89
  await queries.triggerStates({}, {}, CTX);
@@ -132,7 +127,7 @@ describe("the workflow resolvers and the caller", () => {
132
127
  });
133
128
 
134
129
  it("passes the caller's drive, and tags a still-syncing workflow", async () => {
135
- const { runtime, queries, mutations } = build(true);
130
+ const { runtime, queries, mutations } = build();
136
131
  const drive = { driveId: "drive-1" };
137
132
 
138
133
  await queries.webhookEndpoint({}, { workflowId: "wf-1", ...drive }, CTX);
@@ -153,32 +148,49 @@ describe("the workflow resolvers and the caller", () => {
153
148
  expect(runtime.testStep).toHaveBeenCalledWith("wf-1", "s1", CTX, drive);
154
149
  });
155
150
 
156
- it("refuses secret writes to a caller who does not administer the reactor", async () => {
157
- const { runtime, mutations } = build(false);
151
+ it("hands every secret field to the runtime with the caller, never the store", async () => {
152
+ const { runtime, queries, mutations, secretRecord } = build();
153
+ const stat = { ref: "secret://v1:00", ownerId: "conn-1" };
158
154
 
155
+ await mutations.createSecret(
156
+ {},
157
+ { value: "s3cret", documentId: "conn-1" },
158
+ CTX,
159
+ );
160
+ await mutations.rotateSecret({}, { ref: stat.ref, value: "s" }, CTX);
159
161
  await expect(
160
- mutations.createSecret({}, { value: "s3cret" }, CTX),
161
- ).rejects.toThrow("Admin access required");
162
- await expect(
163
- mutations.rotateSecret({}, { ref: "secret://v1:00", value: "s" }, CTX),
164
- ).rejects.toThrow("Admin access required");
165
- await expect(
166
- mutations.deleteSecret({}, { ref: "secret://v1:00" }, CTX),
167
- ).rejects.toThrow("Admin access required");
168
- // Refused before the store is ever opened.
162
+ mutations.deleteSecret({}, { ref: stat.ref }, CTX),
163
+ ).resolves.toBe(true);
164
+ await queries.secret({}, { ref: stat.ref }, CTX);
165
+ await queries.secrets({}, {}, CTX);
166
+ await secretRecord.manageable(stat, {}, CTX);
167
+
168
+ expect(runtime.createSecret).toHaveBeenCalledWith(
169
+ { value: "s3cret", label: undefined, ownerId: "conn-1" },
170
+ CTX,
171
+ );
172
+ expect(runtime.rotateSecret).toHaveBeenCalledWith(stat.ref, "s", CTX);
173
+ expect(runtime.deleteSecret).toHaveBeenCalledWith(stat.ref, CTX);
174
+ expect(runtime.secretStat).toHaveBeenCalledWith(stat.ref, CTX);
175
+ expect(runtime.listSecrets).toHaveBeenCalledWith(CTX);
176
+ expect(runtime.canManageSecret).toHaveBeenCalledWith(stat, CTX);
177
+ // Nothing reaches the raw store, whose get returns values.
169
178
  expect(runtime.secrets).not.toHaveBeenCalled();
170
179
  });
171
180
 
172
- it("lets an administrator write secrets", async () => {
173
- const { runtime, mutations } = build(true);
174
-
175
- await mutations.createSecret({}, { value: "s3cret", label: "slack" }, CTX);
181
+ it("tags a secret minted for a document still syncing", async () => {
182
+ const { runtime, mutations } = build();
183
+ runtime.createSecret.mockRejectedValueOnce(new WorkflowSyncingError());
176
184
 
177
- expect(runtime.secrets).toHaveBeenCalledTimes(1);
185
+ await expect(
186
+ mutations.createSecret({}, { value: "s", documentId: "c1" }, CTX),
187
+ ).rejects.toMatchObject({
188
+ extensions: { code: "WORKFLOW_SYNCING", retryable: true },
189
+ });
178
190
  });
179
191
 
180
192
  it("serves why a workflow got no reactor access, naming the publisher", async () => {
181
- const { runtime, queries } = build(false);
193
+ const { runtime, queries } = build();
182
194
  runtime.reactorAccessDenial.mockReturnValueOnce(
183
195
  'The publisher 0xabc cannot read reactor connection "conn-1"',
184
196
  );
@@ -197,7 +209,7 @@ describe("the workflow resolvers and the caller", () => {
197
209
  });
198
210
 
199
211
  it("serves the piece version a run's steps ran", async () => {
200
- const { runtime, queries } = build(true);
212
+ const { runtime, queries } = build();
201
213
  runtime.run.mockResolvedValueOnce({
202
214
  row: { id: "run-1", warnings: 1, trigger_payload: null },
203
215
  steps: [
@@ -231,7 +243,7 @@ describe("the workflow resolvers and the caller", () => {
231
243
 
232
244
  describe("the runs listing and step data", () => {
233
245
  it("reads step blobs only when the query selects them", async () => {
234
- const { runtime, queries } = build(false);
246
+ const { runtime, queries } = build();
235
247
  const withData = (query: string) =>
236
248
  queries.runs({}, {}, CTX, runsInfo(query)).then(
237
249
  () =>
@@ -271,7 +283,7 @@ describe("the runs listing and step data", () => {
271
283
 
272
284
  describe("the runs page", () => {
273
285
  it("passes paging through and serves the page", async () => {
274
- const { runtime, queries } = build(false);
286
+ const { runtime, queries } = build();
275
287
  runtime.runsPage.mockResolvedValueOnce({
276
288
  records: [],
277
289
  hasNextPage: true,
@@ -310,7 +322,7 @@ describe("the runs page", () => {
310
322
  });
311
323
 
312
324
  it("reports a cursor it did not issue as bad input", async () => {
313
- const { runtime, queries } = build(false);
325
+ const { runtime, queries } = build();
314
326
  const invalid = new Error("Invalid runs cursor");
315
327
  invalid.name = "InvalidRunCursorError";
316
328
  runtime.runsPage.mockRejectedValueOnce(invalid);
@@ -326,7 +338,7 @@ describe("the runs page", () => {
326
338
 
327
339
  describe("piece search", () => {
328
340
  it("passes a valid filter through", async () => {
329
- const { runtime, queries } = build(false);
341
+ const { runtime, queries } = build();
330
342
  await queries.searchPieces(
331
343
  {},
332
344
  { query: "send", kind: "trigger", sources: ["registry", "local"] },
@@ -341,7 +353,7 @@ describe("piece search", () => {
341
353
  });
342
354
 
343
355
  it("refuses a kind or source it does not know, rather than widen", () => {
344
- const { runtime, queries } = build(false);
356
+ const { runtime, queries } = build();
345
357
  expect(() =>
346
358
  queries.searchPieces({}, { query: "send", kind: "triggers" }, CTX),
347
359
  ).toThrow(/kind is "action" or "trigger"/);
@@ -1,4 +1,3 @@
1
- import type { IAuthorizationService } from "@powerhousedao/reactor-api";
2
1
  import type { WorkflowRuntimeService } from "@powerhousedao/reactor-workflow";
3
2
  import { hostname } from "node:os";
4
3
  import { describe, expect, it } from "vitest";
@@ -8,10 +7,10 @@ type Resolver = (...args: unknown[]) => unknown;
8
7
 
9
8
  describe("the runtime's host", () => {
10
9
  it("is the switchboard on this machine, the id apps record as runner", () => {
11
- const resolvers = getResolvers(
12
- {} as WorkflowRuntimeService,
13
- {} as IAuthorizationService,
14
- ) as Record<string, Record<string, Resolver>>;
10
+ const resolvers = getResolvers({} as WorkflowRuntimeService) as Record<
11
+ string,
12
+ Record<string, Resolver>
13
+ >;
15
14
  expect(resolvers.WorkflowRuntimeQueries.host()).toEqual({
16
15
  id: `switchboard@${hostname()}`,
17
16
  label: hostname(),
@@ -1 +0,0 @@
1
- {"version":3,"file":"utils-BbV_nodR.mjs","sources":["../src/utils.mts"],"sourcesContent":["import type { IReactorClient } from \"@powerhousedao/reactor\";\nimport {\n REACTOR_DRIVE_DOCUMENT_TYPE,\n reactorDriveCreateState,\n} from \"@powerhousedao/reactor-drive\";\nimport {\n driveCreateState,\n driveDocumentType,\n} from \"@powerhousedao/shared/document-drive\";\nimport type { DriveInput } from \"@powerhousedao/shared/document-drive\";\nimport type {\n PHBaseState,\n PHDocument,\n} from \"@powerhousedao/shared/document-model\";\n\n/**\n * A configured id pins the drive, and only a legacy drive can take a chosen\n * id; otherwise the client's creation default applies.\n */\nfunction newDrive<TDocument extends PHDocument>(\n client: IReactorClient,\n documentType: string,\n initialState: Partial<PHBaseState>,\n id: string | undefined,\n): Promise<TDocument> {\n return client.newDocument<TDocument>(documentType, {\n initialState,\n ...(id ? { signaturePolicy: \"legacy\" as const, id } : {}),\n });\n}\n\ntype DefaultDriveLogger = { error: (message: string) => void };\n\n/** The document that already holds `slug`; null when two do (an id and a slug). */\nasync function slugHolder(\n client: IReactorClient,\n slug: string,\n): Promise<PHDocument | null | undefined> {\n let id: string;\n try {\n id = await client.resolveIdOrSlug(slug);\n } catch (error) {\n const notFound =\n error instanceof Error && error.name === \"DocumentNotFoundError\";\n return notFound ? undefined : null;\n }\n return client.get(id);\n}\n\n/**\n * A default drive whose slug another document holds: a drive of the same type\n * stands in for it (its URL); anything else keeps it uncreated (null), with an\n * error logged so the server still starts. Undefined when the slug is free.\n */\nasync function slugTakenBy(\n client: IReactorClient,\n drive: DriveInput,\n documentType: string,\n serverPort: number,\n logger: DefaultDriveLogger,\n): Promise<string | null | undefined> {\n if (!drive.slug) return undefined;\n const holder = await slugHolder(client, drive.slug);\n if (holder === undefined) return undefined;\n if (holder?.header.documentType === documentType) {\n return `http://localhost:${serverPort}/d/${holder.header.id}`;\n }\n const owner = holder\n ? `${holder.header.documentType} document ${holder.header.id}`\n : \"two documents\";\n logger.error(\n `The default drive \"${drive.slug}\" was not created: the slug belongs to ${owner}.`,\n );\n return null;\n}\n\n/** Creates a configured drive unless one with its id or slug exists; the\n * URL it is served at, or undefined when another document holds the slug. */\nexport async function addDefaultDrive(\n client: IReactorClient,\n drive: DriveInput,\n serverPort: number,\n logger: DefaultDriveLogger = console,\n): Promise<string | undefined> {\n let driveId = drive.id;\n if (!driveId || driveId.length === 0) {\n driveId = drive.slug;\n }\n\n if (!driveId || driveId.length === 0) {\n throw new Error(\"Invalid Drive Id\");\n }\n\n // check if the drive already exists\n let existingDrive;\n try {\n existingDrive = await client.get(driveId);\n } catch {\n //\n }\n\n // already exists, return the existing drive url\n if (existingDrive) {\n return `http://localhost:${serverPort}/d/${driveId}`;\n }\n\n const { global } = driveCreateState();\n const taken = await slugTakenBy(\n client,\n drive,\n driveDocumentType,\n serverPort,\n logger,\n );\n if (taken !== undefined) return taken ?? undefined;\n\n const document = await newDrive(\n client,\n driveDocumentType,\n {\n global: {\n ...global,\n name: drive.global.name,\n icon: drive.global.icon ?? global.icon,\n },\n local: {\n availableOffline: drive.local?.availableOffline ?? false,\n sharingType: drive.local?.sharingType ?? \"public\",\n listeners: drive.local?.listeners ?? [],\n triggers: drive.local?.triggers ?? [],\n },\n } as Partial<PHBaseState>,\n drive.id,\n );\n if (drive.slug && drive.slug.length > 0) {\n document.header.slug = drive.slug;\n }\n if (drive.global.name) {\n document.header.name = drive.global.name;\n }\n if (drive.preferredEditor) {\n document.header.meta = { preferredEditor: drive.preferredEditor };\n }\n\n try {\n await (\n await client.write.create(document)\n ).readable;\n } catch (e) {\n const errorMessage = e instanceof Error ? e.message : String(e);\n if (!errorMessage.includes(\"already exists\")) {\n throw e;\n }\n }\n\n return `http://localhost:${serverPort}/d/${driveId}`;\n}\n\n/** addDefaultDrive for a reactor drive. */\nexport async function addDefaultReactorDrive(\n client: IReactorClient,\n drive: DriveInput,\n serverPort: number,\n logger: DefaultDriveLogger = console,\n): Promise<string | undefined> {\n let driveId = drive.id;\n if (!driveId || driveId.length === 0) {\n driveId = drive.slug;\n }\n\n if (!driveId || driveId.length === 0) {\n throw new Error(\"Invalid Drive Id\");\n }\n\n let existingDrive;\n try {\n existingDrive = await client.get(driveId);\n } catch {\n //\n }\n\n if (existingDrive) {\n return `http://localhost:${serverPort}/d/${driveId}`;\n }\n\n const { global, local } = reactorDriveCreateState();\n const taken = await slugTakenBy(\n client,\n drive,\n REACTOR_DRIVE_DOCUMENT_TYPE,\n serverPort,\n logger,\n );\n if (taken !== undefined) return taken ?? undefined;\n\n const document = await newDrive(\n client,\n REACTOR_DRIVE_DOCUMENT_TYPE,\n {\n global: {\n ...global,\n name: drive.global.name,\n icon: drive.global.icon ?? global.icon,\n },\n local: {\n ...local,\n availableOffline:\n drive.local?.availableOffline ?? local.availableOffline,\n sharingType: drive.local?.sharingType ?? local.sharingType,\n },\n } as Partial<PHBaseState>,\n drive.id,\n );\n if (drive.slug && drive.slug.length > 0) {\n document.header.slug = drive.slug;\n }\n if (drive.global.name) {\n document.header.name = drive.global.name;\n }\n if (drive.preferredEditor) {\n document.header.meta = { preferredEditor: drive.preferredEditor };\n }\n\n try {\n await (\n await client.write.create(document)\n ).readable;\n } catch (e) {\n const errorMessage = e instanceof Error ? e.message : String(e);\n if (!errorMessage.includes(\"already exists\")) {\n throw e;\n }\n }\n\n return `http://localhost:${serverPort}/d/${driveId}`;\n}\n\nexport { isPostgresUrl } from \"./postgres-url.mjs\";\n"],"names":[],"mappings":";;;;;;;;;AAmBA,SAAS,SACP,QACA,cACA,cACA,IACoB;CACpB,OAAO,OAAO,YAAuB,cAAc;EACjD;EACA,GAAI,KAAK;GAAE,iBAAiB;GAAmB;EAAG,IAAI,CAAC;CACzD,CAAC;AACH;;AAKA,eAAe,WACb,QACA,MACwC;CACxC,IAAI;CACJ,IAAI;EACF,KAAK,MAAM,OAAO,gBAAgB,IAAI;CACxC,SAAS,OAAO;EAGd,OADE,iBAAiB,SAAS,MAAM,SAAS,0BACzB,KAAA,IAAY;CAChC;CACA,OAAO,OAAO,IAAI,EAAE;AACtB;;;;;;AAOA,eAAe,YACb,QACA,OACA,cACA,YACA,QACoC;CACpC,IAAI,CAAC,MAAM,MAAM,OAAO,KAAA;CACxB,MAAM,SAAS,MAAM,WAAW,QAAQ,MAAM,IAAI;CAClD,IAAI,WAAW,KAAA,GAAW,OAAO,KAAA;CACjC,IAAI,QAAQ,OAAO,iBAAiB,cAClC,OAAO,oBAAoB,WAAW,KAAK,OAAO,OAAO;CAE3D,MAAM,QAAQ,SACV,GAAG,OAAO,OAAO,aAAa,YAAY,OAAO,OAAO,OACxD;CACJ,OAAO,MACL,sBAAsB,MAAM,KAAK,yCAAyC,MAAM,EAClF;CACA,OAAO;AACT;;;AAIA,eAAsB,gBACpB,QACA,OACA,YACA,SAA6B,SACA;CAC7B,IAAI,UAAU,MAAM;CACp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