@stage-labs/metro 0.1.0-beta.287 → 0.1.0-beta.289

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 (54) hide show
  1. package/package.json +1 -1
  2. package/runtime/marketplace/plugin/.claude-plugin/plugin.json +1 -1
  3. package/runtime/marketplace/plugin/bin/policy.mjs +3 -2
  4. package/runtime/node_modules/@metro-labs/core/package.json +1 -0
  5. package/runtime/node_modules/@metro-labs/core/src/connector-sync.ts +17 -0
  6. package/runtime/node_modules/@metro-labs/daemon/src/approvals/pending.ts +6 -0
  7. package/runtime/node_modules/@metro-labs/daemon/src/boot/boot.ts +7 -3
  8. package/runtime/node_modules/@metro-labs/daemon/src/connectors/agent-key.ts +148 -0
  9. package/runtime/node_modules/@metro-labs/daemon/src/connectors/api.ts +14 -2
  10. package/runtime/node_modules/@metro-labs/daemon/src/connectors/config.ts +2 -72
  11. package/runtime/node_modules/@metro-labs/daemon/src/connectors/enroll-api.ts +101 -0
  12. package/runtime/node_modules/@metro-labs/daemon/src/connectors/gates.ts +40 -4
  13. package/runtime/node_modules/@metro-labs/daemon/src/connectors/metro-api.ts +93 -0
  14. package/runtime/node_modules/@metro-labs/daemon/src/connectors/migration-preview.ts +201 -0
  15. package/runtime/node_modules/@metro-labs/daemon/src/connectors/migration-url.ts +32 -0
  16. package/runtime/node_modules/@metro-labs/daemon/src/connectors/oauth-routes.ts +3 -3
  17. package/runtime/node_modules/@metro-labs/daemon/src/connectors/oauth.ts +4 -7
  18. package/runtime/node_modules/@metro-labs/daemon/src/connectors/org-relay.ts +61 -0
  19. package/runtime/node_modules/@metro-labs/daemon/src/connectors/org-runtime-discovery.ts +111 -0
  20. package/runtime/node_modules/@metro-labs/daemon/src/connectors/org-runtime.ts +246 -0
  21. package/runtime/node_modules/@metro-labs/daemon/src/connectors/org-sync-api.ts +25 -0
  22. package/runtime/node_modules/@metro-labs/daemon/src/connectors/org-sync-control.ts +138 -0
  23. package/runtime/node_modules/@metro-labs/daemon/src/connectors/org-sync-setting.ts +60 -0
  24. package/runtime/node_modules/@metro-labs/daemon/src/connectors/org-sync-watch.ts +39 -0
  25. package/runtime/node_modules/@metro-labs/daemon/src/connectors/org-sync.ts +187 -0
  26. package/runtime/node_modules/@metro-labs/daemon/src/connectors/plugin-sync.ts +11 -1
  27. package/runtime/node_modules/@metro-labs/daemon/src/connectors/publication.ts +33 -0
  28. package/runtime/node_modules/@metro-labs/daemon/src/connectors/relay-id.ts +2 -0
  29. package/runtime/node_modules/@metro-labs/daemon/src/connectors/relay-session.ts +10 -0
  30. package/runtime/node_modules/@metro-labs/daemon/src/connectors/relay-target.ts +4 -0
  31. package/runtime/node_modules/@metro-labs/daemon/src/connectors/relay.ts +25 -4
  32. package/runtime/node_modules/@metro-labs/daemon/src/connectors/store.ts +10 -20
  33. package/runtime/node_modules/@metro-labs/daemon/src/connectors/tools.ts +16 -13
  34. package/runtime/node_modules/@metro-labs/daemon/src/connectors/transfer-store.ts +3 -2
  35. package/runtime/node_modules/@metro-labs/daemon/src/policy/policy.ts +2 -1
  36. package/runtime/node_modules/@metro-labs/daemon/src/routes/local-mode.ts +13 -3
  37. package/runtime/node_modules/@metro-labs/daemon/src/routes/session-apis.ts +6 -0
  38. package/runtime/node_modules/@metro-labs/http/package.json +10 -2
  39. package/runtime/node_modules/@metro-labs/http/src/agent-signature.ts +110 -0
  40. package/runtime/node_modules/@metro-labs/http/src/api-http.ts +6 -2
  41. package/runtime/node_modules/@metro-labs/http/src/connector-delivery-validation.ts +115 -0
  42. package/runtime/node_modules/@metro-labs/http/src/connector-delivery.ts +54 -0
  43. package/runtime/node_modules/@metro-labs/{daemon/src/connectors/oauth-discovery.ts → http/src/connector-discovery.ts} +31 -14
  44. package/runtime/node_modules/@metro-labs/http/src/connector-input.ts +73 -0
  45. package/runtime/node_modules/@metro-labs/{daemon/src/connectors/verify.ts → http/src/connector-mcp.ts} +16 -16
  46. package/runtime/node_modules/@metro-labs/{daemon/src/connectors/oauth-client.ts → http/src/connector-oauth.ts} +36 -13
  47. package/runtime/node_modules/@metro-labs/http/src/connector-policy.ts +53 -0
  48. package/runtime/node_modules/@metro-labs/{daemon/src/connectors/url.ts → http/src/connector-url.ts} +1 -1
  49. package/runtime/node_modules/@metro-labs/http/src/ed25519.ts +56 -0
  50. package/runtime/runtime.json +1 -1
  51. package/runtime/sdk-runner/node_modules/@metro-labs/core/package.json +1 -0
  52. package/runtime/sdk-runner/node_modules/@metro-labs/core/src/connector-sync.ts +17 -0
  53. package/runtime/sdk-runner/runner.json +1 -1
  54. /package/runtime/node_modules/@metro-labs/{daemon/src/connectors/reach.ts → http/src/connector-reach.ts} +0 -0
@@ -0,0 +1,246 @@
1
+ import { log } from '@metro-labs/core/log';
2
+ import type { FetchLike } from '@metro-labs/core/stations/oauth';
3
+ import type { ToolGroup } from '@metro-labs/core/stations/types';
4
+ import type { DeliveredConnector } from '@metro-labs/http/connector-delivery';
5
+ import type { ApiError } from '@metro-labs/http/api-error';
6
+ import { requestConnectorBlocker, type GateRow } from './gates.js';
7
+ import { publishOrgConnectors } from './publication.js';
8
+ import { isOrgRelayId, orgRelayId } from './relay-id.js';
9
+ import type { RelaySession } from './relay-session.js';
10
+ import type { RelayTarget } from './relay-target.js';
11
+ import type { OrgConnectorSync } from './org-sync.js';
12
+ import { discoverOrgGroups, orgMissing, orgRuntimeError, orgSignin, orgUnavailable } from './org-runtime-discovery.js';
13
+
14
+ interface RuntimeDeps {
15
+ enabled?: () => boolean;
16
+ publish?: (rows: readonly GateRow[]) => void;
17
+ fetch?: FetchLike;
18
+ }
19
+
20
+ interface Entry {
21
+ id: string;
22
+ epoch: number;
23
+ stamp: string;
24
+ controller: AbortController;
25
+ groups: Record<string, ToolGroup>;
26
+ scan: Promise<void> | null;
27
+ nextScan: number;
28
+ error: ApiError | null;
29
+ }
30
+
31
+ interface Session {
32
+ entry: Entry;
33
+ controller: AbortController;
34
+ revision: string | null;
35
+ error: ApiError | null;
36
+ }
37
+
38
+ const stampOf = (row: DeliveredConnector): string => JSON.stringify([
39
+ row.name, row.url, row.auth, row.policy.read ?? 'allow', row.policy.write ?? 'allow',
40
+ Object.entries(row.policy.tools ?? {}).sort(([a], [b]) => a.localeCompare(b)),
41
+ ]);
42
+
43
+ const rowError = (row: DeliveredConnector | undefined): ApiError | null => {
44
+ if (row === undefined) return orgMissing();
45
+ if (row.state === 'signin') return orgSignin();
46
+ return row.state === 'ready' ? null : orgUnavailable();
47
+ };
48
+
49
+ const targetOf = (row: DeliveredConnector): RelayTarget => ({ kind: 'ok', url: row.url, headers: { ...row.headers } });
50
+
51
+ export class OrgConnectorRuntime {
52
+ private readonly entries = new Map<string, Entry>();
53
+ private readonly sessions = new Set<Session>();
54
+ private readonly unsubscribe: () => void;
55
+ private readonly timer: ReturnType<typeof setInterval>;
56
+ private published = '';
57
+ private stopped = false;
58
+ private scans = 0;
59
+
60
+ constructor(private readonly sync: OrgConnectorSync, private readonly deps: RuntimeDeps = {}) {
61
+ this.unsubscribe = sync.onChange(() => { this.update(); });
62
+ this.timer = setInterval(() => {
63
+ try {
64
+ this.update();
65
+ } catch {
66
+ log.warn('organization connectors: runtime metadata could not be updated');
67
+ }
68
+ }, 1000);
69
+ this.timer.unref();
70
+ this.update();
71
+ }
72
+
73
+ private enabled(): boolean {
74
+ return !this.stopped && (this.deps.enabled?.() ?? process.env.METRO_CONNECTORS_LIVE_ENABLED === 'true');
75
+ }
76
+
77
+ private abort(session: Session, error: ApiError): void {
78
+ session.error ??= error;
79
+ session.controller.abort();
80
+ this.sessions.delete(session);
81
+ }
82
+
83
+ private publish(rows: DeliveredConnector[]): void {
84
+ const metadata: GateRow[] = rows.filter((row) => row.state === 'ready').map((row) => ({
85
+ id: orgRelayId(row.id), name: row.name,
86
+ config: { policy: structuredClone(row.policy), toolGroups: { ...this.entries.get(row.id)?.groups } },
87
+ }));
88
+ const text = JSON.stringify(metadata);
89
+ if (text === this.published) return;
90
+ try {
91
+ (this.deps.publish ?? publishOrgConnectors)(metadata);
92
+ this.published = text;
93
+ } catch {
94
+ this.published = '';
95
+ for (const session of this.sessions) this.abort(session, orgUnavailable());
96
+ throw orgUnavailable();
97
+ }
98
+ }
99
+
100
+ private invalidateEntries(rows: DeliveredConnector[], epoch: number, available: boolean): void {
101
+ for (const [id, entry] of this.entries) {
102
+ const row = rows.find((value) => value.id === id);
103
+ const valid = available && entry.epoch === epoch;
104
+ if (valid && row?.state === 'ready' && entry.stamp === stampOf(row)) continue;
105
+ const error = valid ? rowError(row) ?? orgUnavailable() : orgUnavailable();
106
+ entry.controller.abort();
107
+ this.entries.delete(id);
108
+ this.abortEntry(entry, error);
109
+ }
110
+ }
111
+
112
+ private abortEntry(entry: Entry, error: ApiError): void {
113
+ for (const session of this.sessions) if (session.entry === entry) this.abort(session, error);
114
+ }
115
+
116
+ private update(): DeliveredConnector[] | null {
117
+ const snapshot = this.enabled() ? this.sync.read() : null;
118
+ const rows = snapshot?.connectors ?? [];
119
+ const epoch = this.sync.epoch();
120
+ this.invalidateEntries(rows, epoch, snapshot !== null);
121
+ for (const row of rows) {
122
+ if (row.state !== 'ready' || this.entries.has(row.id)) continue;
123
+ this.entries.set(row.id, { id: row.id, epoch, stamp: stampOf(row), controller: new AbortController(), groups: {}, scan: null, nextScan: 0, error: null });
124
+ }
125
+ this.publish(rows);
126
+ return snapshot === null ? null : rows;
127
+ }
128
+
129
+ private currentEntry(entry: Entry): DeliveredConnector {
130
+ const rows = this.update();
131
+ if (rows === null || entry.epoch !== this.sync.epoch()) throw orgUnavailable();
132
+ const row = rows.find((value) => value.id === entry.id);
133
+ if (row === undefined) throw orgMissing();
134
+ const error = rowError(row);
135
+ if (error !== null) throw error;
136
+ if (entry.controller.signal.aborted || this.entries.get(entry.id) !== entry) throw orgUnavailable();
137
+ return row;
138
+ }
139
+
140
+ private currentSession(session: Session): DeliveredConnector {
141
+ if (session.error !== null) throw session.error;
142
+ try {
143
+ return this.currentEntry(session.entry);
144
+ } catch (error) {
145
+ throw session.error ?? orgRuntimeError(error);
146
+ }
147
+ }
148
+
149
+ private async fresh(entry: Entry, refresh?: { connectorId: string; revision: string }): Promise<DeliveredConnector> {
150
+ this.currentEntry(entry);
151
+ try {
152
+ await this.sync.syncFresh(refresh);
153
+ } catch (error) {
154
+ throw orgRuntimeError(error);
155
+ }
156
+ return this.currentEntry(entry);
157
+ }
158
+
159
+ private async scan(entry: Entry): Promise<void> {
160
+ const row = this.currentEntry(entry);
161
+ const signal = AbortSignal.any([entry.controller.signal, AbortSignal.timeout(45_000)]);
162
+ const groups = await discoverOrgGroups(row.url, {
163
+ fresh: (revision) => this.fresh(entry, revision === undefined ? undefined : { connectorId: entry.id, revision }),
164
+ current: () => this.currentEntry(entry), signal, fetch: this.deps.fetch ?? fetch,
165
+ });
166
+ this.currentEntry(entry);
167
+ if (JSON.stringify(groups) !== JSON.stringify(entry.groups)) {
168
+ for (const session of this.sessions) if (session.entry === entry && session.revision !== null) this.abort(session, orgUnavailable());
169
+ }
170
+ entry.groups = groups;
171
+ entry.error = null;
172
+ entry.nextScan = performance.now() + 60_000;
173
+ this.update();
174
+ }
175
+
176
+ private discover(entry: Entry): Promise<void> | null {
177
+ if (entry.scan !== null) return entry.scan;
178
+ if (performance.now() < entry.nextScan) {
179
+ if (entry.error !== null) throw entry.error;
180
+ return null;
181
+ }
182
+ if (this.scans >= 4) throw orgUnavailable();
183
+ this.scans += 1;
184
+ entry.scan = this.scan(entry).catch((error: unknown) => {
185
+ entry.error = orgRuntimeError(error);
186
+ entry.nextScan = performance.now() + 30_000;
187
+ log.debug({ status: entry.error.status }, 'organization connectors: tool discovery failed');
188
+ throw entry.error;
189
+ }).finally(() => {
190
+ this.scans -= 1;
191
+ entry.scan = null;
192
+ });
193
+ return entry.scan;
194
+ }
195
+
196
+ private async target(session: Session, force: boolean): Promise<RelayTarget> {
197
+ this.currentSession(session);
198
+ if (force && session.revision === null) throw orgUnavailable();
199
+ const refresh = force && session.revision !== null ? { connectorId: session.entry.id, revision: session.revision } : undefined;
200
+ await this.fresh(session.entry, refresh);
201
+ this.currentSession(session);
202
+ const discovery = this.discover(session.entry);
203
+ if (discovery !== null) {
204
+ await discovery;
205
+ this.currentSession(session);
206
+ await this.fresh(session.entry);
207
+ }
208
+ return targetOf(this.currentSession(session));
209
+ }
210
+
211
+ open(id: string): RelaySession {
212
+ if (!isOrgRelayId(id)) throw orgMissing();
213
+ const rows = this.update();
214
+ if (rows === null) throw orgUnavailable();
215
+ const rawId = id.slice(4);
216
+ const error = rowError(rows.find((row) => row.id === rawId));
217
+ if (error !== null) throw error;
218
+ const entry = this.entries.get(rawId);
219
+ if (entry === undefined) throw orgUnavailable();
220
+ const session: Session = { entry, controller: new AbortController(), revision: null, error: null };
221
+ this.sessions.add(session);
222
+ const blocker = requestConnectorBlocker();
223
+ return {
224
+ target: (force) => this.target(session, force),
225
+ current: () => {
226
+ const row = this.currentSession(session);
227
+ session.revision = row.revision;
228
+ return targetOf(row);
229
+ },
230
+ blocker: () => {
231
+ this.currentSession(session);
232
+ return blocker();
233
+ },
234
+ signal: session.controller.signal,
235
+ close: () => { this.abort(session, orgUnavailable()); },
236
+ };
237
+ }
238
+
239
+ stop(): void {
240
+ if (this.stopped) return;
241
+ this.stopped = true;
242
+ this.unsubscribe();
243
+ clearInterval(this.timer);
244
+ this.update();
245
+ }
246
+ }
@@ -0,0 +1,25 @@
1
+ import type { IncomingMessage, ServerResponse } from 'node:http';
2
+ import type { ConnectorSyncStatus } from '@metro-labs/core/connector-sync';
3
+ import { isRecord } from '@metro-labs/core/is-record';
4
+ import { ApiError } from '@metro-labs/http/api-error';
5
+ import { readJsonBody, sessionRoute } from '@metro-labs/http/api-http';
6
+
7
+ const PATH = '/api/connectors/sync';
8
+
9
+ export interface ConnectorSyncApiDeps {
10
+ status: () => ConnectorSyncStatus;
11
+ set: (enabled: boolean, scope: string) => ConnectorSyncStatus;
12
+ }
13
+
14
+ export function handleConnectorSyncRequest(req: IncomingMessage, res: ServerResponse, deps: ConnectorSyncApiDeps): boolean {
15
+ return sessionRoute(req, res, { methods: { [PATH]: ['GET', 'PUT'] }, admin: true, label: 'connector-sync-api' }, async (session) => {
16
+ const body = req.method === 'PUT' ? await readJsonBody(req) : null;
17
+ const current = deps.status();
18
+ if (current.owner === null || current.owner !== session.subject) throw new ApiError('This agent belongs to another organization.', 403);
19
+ if (req.method !== 'PUT') return current;
20
+ if (!isRecord(body) || typeof body.enabled !== 'boolean' || typeof body.scope !== 'string' || !/^[a-f0-9]{64}$/.test(body.scope) || Object.keys(body).some((key) => key !== 'enabled' && key !== 'scope')) {
21
+ throw new ApiError('Sync needs an enabled flag and the current enrollment scope.', 400);
22
+ }
23
+ return deps.set(body.enabled, body.scope);
24
+ });
25
+ }
@@ -0,0 +1,138 @@
1
+ import { createHash, randomBytes } from 'node:crypto';
2
+ import type { ConnectorSyncStatus } from '@metro-labs/core/connector-sync';
3
+ import { log } from '@metro-labs/core/log';
4
+ import { ApiError } from '@metro-labs/http/api-error';
5
+ import { agentsDir } from '../agents/files.js';
6
+ import { METRO_API, type MetroApi } from './metro-api.js';
7
+ import { OrgConnectorSync, type OrgSyncDeps } from './org-sync.js';
8
+ import { OrgConnectorRuntime } from './org-runtime.js';
9
+ import { connectorSyncScope, disableSavedSync, saveSyncSetting, syncOptedIn, syncSetting } from './org-sync-setting.js';
10
+ import type { RelaySession } from './relay-session.js';
11
+
12
+ type ControlDeps = Pick<OrgSyncDeps, 'owner' | 'key' | 'monotonic'> & { api?: MetroApi; dir?: string };
13
+ type Context = Pick<ConnectorSyncStatus, 'owner' | 'agentId' | 'scope' | 'enrolled'>;
14
+ const POLL_MS = 60_000;
15
+ const liveEnabled = (): boolean => process.env.METRO_CONNECTORS_LIVE_ENABLED === 'true';
16
+ const emptyReceipt = { lastReceivedAt: null, leaseExpiresAt: null, counts: null };
17
+
18
+ export class OrgConnectorControl {
19
+ private readonly dir: string;
20
+ private readonly api: MetroApi;
21
+ private sync: OrgConnectorSync | null = null;
22
+ private runtime: OrgConnectorRuntime | null = null;
23
+ private scope: string | null = null;
24
+ private operation = randomBytes(16).toString('hex');
25
+ private timer: ReturnType<typeof setInterval> | null = null;
26
+
27
+ constructor(private readonly deps: ControlDeps) {
28
+ this.dir = deps.dir ?? agentsDir();
29
+ this.api = deps.api ?? METRO_API;
30
+ }
31
+
32
+ private context(): Context {
33
+ const owner = this.deps.owner();
34
+ const key = this.deps.key();
35
+ const enrollment = key?.enrollment;
36
+ const agentId = owner !== null && enrollment?.organization === owner ? enrollment.server : null;
37
+ const scope = connectorSyncScope(owner, key);
38
+ return { owner, agentId, scope, enrolled: agentId !== null };
39
+ }
40
+
41
+ private clear(): void {
42
+ this.sync?.invalidate();
43
+ this.sync = null;
44
+ const runtime = this.runtime;
45
+ this.runtime = null;
46
+ try {
47
+ runtime?.stop();
48
+ } catch {
49
+ log.warn('organization connectors: stopped runtime publication could not be cleared');
50
+ }
51
+ }
52
+
53
+ private reconcile(start: boolean): { context: Context; setting: ReturnType<typeof syncSetting> } {
54
+ const context = this.context();
55
+ if (this.scope !== null && this.scope !== context.scope) {
56
+ this.clear();
57
+ this.operation = randomBytes(16).toString('hex');
58
+ disableSavedSync(this.dir);
59
+ }
60
+ this.scope = context.scope;
61
+ const setting = syncSetting(this.dir, context.scope);
62
+ if (setting.source === 'scope_changed') disableSavedSync(this.dir);
63
+ if (!setting.enabled || !context.enrolled) this.clear();
64
+ else if (start && this.sync === null) {
65
+ const scope = context.scope;
66
+ this.sync = new OrgConnectorSync({ ...this.deps, api: this.api, enabled: () => this.context().scope === scope && syncSetting(this.dir, scope).enabled });
67
+ if (liveEnabled()) this.runtime = new OrgConnectorRuntime(this.sync, { enabled: liveEnabled });
68
+ }
69
+ return { context, setting };
70
+ }
71
+
72
+ status(): ConnectorSyncStatus {
73
+ try {
74
+ const { context, setting } = this.reconcile(false);
75
+ const receipt = this.sync?.status() ?? { state: 'waiting' as const, ...emptyReceipt };
76
+ const state = !setting.enabled ? 'off' : !context.enrolled ? 'not_enrolled' : receipt.state;
77
+ const scope = createHash('sha256').update(`${context.scope}:${this.operation}`).digest('hex');
78
+ return { ...context, ...setting, ...receipt, scope, state, liveEnabled: liveEnabled() };
79
+ } catch {
80
+ this.clear();
81
+ throw new ApiError('Metro could not read the connector sync status.', 503);
82
+ }
83
+ }
84
+
85
+ set(enabled: boolean, scope: string): ConnectorSyncStatus {
86
+ const current = this.status();
87
+ if (scope !== current.scope) throw new ApiError('The organization or enrollment changed. Refresh the sync status before trying again.', 409);
88
+ if (enabled && !current.enrolled) throw new ApiError('Enroll this agent with its organization before enabling sync.', 409);
89
+ if (enabled && liveEnabled()) throw new ApiError('Live organization tools are enabled separately on this server. Disable that setting before enabling memory-only sync here.', 409);
90
+ saveSyncSetting(this.dir, enabled, this.context().scope);
91
+ if (!enabled) this.clear();
92
+ else this.tick();
93
+ return this.status();
94
+ }
95
+
96
+ async poll(): Promise<void> {
97
+ if (this.sync === null && !syncOptedIn(this.dir)) return;
98
+ try {
99
+ this.reconcile(true);
100
+ } catch (err) {
101
+ this.clear();
102
+ throw err;
103
+ }
104
+ await this.sync?.sync();
105
+ }
106
+
107
+ private tick(): void {
108
+ this.poll().catch(() => {
109
+ log.warn('organization connectors: memory sync unavailable; cached credentials were cleared');
110
+ });
111
+ }
112
+
113
+ start(): void {
114
+ if (this.timer !== null) return;
115
+ this.tick();
116
+ this.timer = setInterval(() => { this.tick(); }, POLL_MS);
117
+ this.timer.unref();
118
+ }
119
+
120
+ invalidate(): void {
121
+ this.operation = randomBytes(16).toString('hex');
122
+ this.clear();
123
+ disableSavedSync(this.dir);
124
+ }
125
+
126
+ stop(): void {
127
+ if (this.timer !== null) clearInterval(this.timer);
128
+ this.timer = null;
129
+ this.clear();
130
+ }
131
+
132
+ open(id: string): RelaySession {
133
+ if (this.runtime === null) throw new ApiError('Organization connectors are not available on this agent.', 503);
134
+ this.reconcile(false);
135
+ if (!liveEnabled() || this.runtime === null) throw new ApiError('Organization connectors are not available on this agent.', 503);
136
+ return this.runtime.open(id);
137
+ }
138
+ }
@@ -0,0 +1,60 @@
1
+ import { createHash } from 'node:crypto';
2
+ import type { AgentKey } from './agent-key.js';
3
+ import { readFileSync } from 'node:fs';
4
+ import { join } from 'node:path';
5
+ import type { ConnectorSyncStatus } from '@metro-labs/core/connector-sync';
6
+ import { isRecord } from '@metro-labs/core/is-record';
7
+ import { writeSecure } from '@metro-labs/core/secure-fs';
8
+ import { ApiError } from '@metro-labs/http/api-error';
9
+
10
+ interface SavedSetting {
11
+ version: 1;
12
+ enabled: boolean;
13
+ scope: string;
14
+ }
15
+
16
+ type Stored = SavedSetting | 'absent' | 'invalid';
17
+ const pathOf = (dir: string): string => join(dir, 'org-connector-sync.json');
18
+
19
+ function read(dir: string): Stored {
20
+ let raw: unknown;
21
+ try {
22
+ raw = JSON.parse(readFileSync(pathOf(dir), 'utf8')) as unknown;
23
+ } catch (err) {
24
+ return isRecord(err) && err.code === 'ENOENT' ? 'absent' : 'invalid';
25
+ }
26
+ if (!isRecord(raw) || raw.version !== 1 || typeof raw.enabled !== 'boolean' || typeof raw.scope !== 'string' || !/^[a-f0-9]{64}$/.test(raw.scope)) return 'invalid';
27
+ return { version: 1, enabled: raw.enabled, scope: raw.scope };
28
+ }
29
+
30
+ export function connectorSyncScope(owner: string | null, key: AgentKey | null): string {
31
+ const agentId = owner !== null && key?.enrollment?.organization === owner ? key.enrollment.server : null;
32
+ return createHash('sha256').update(JSON.stringify([owner, agentId, key?.keyId ?? null, key?.sealingKey ?? null])).digest('hex');
33
+ }
34
+
35
+ export function syncOptedIn(dir: string): boolean {
36
+ const saved = read(dir);
37
+ if (saved === 'absent') return process.env.METRO_CONNECTORS_SYNC_ENABLED === 'true';
38
+ return saved !== 'invalid' && saved.enabled;
39
+ }
40
+
41
+ export function syncSetting(dir: string, scope: string): Pick<ConnectorSyncStatus, 'enabled' | 'source'> {
42
+ const saved = read(dir);
43
+ if (saved === 'invalid') return { enabled: false, source: 'invalid' };
44
+ if (saved === 'absent') return process.env.METRO_CONNECTORS_SYNC_ENABLED === 'true' ? { enabled: true, source: 'environment' } : { enabled: false, source: 'default' };
45
+ if (saved.scope !== scope) return { enabled: false, source: 'scope_changed' };
46
+ return { enabled: saved.enabled, source: 'saved' };
47
+ }
48
+
49
+ export function saveSyncSetting(dir: string, enabled: boolean, scope: string): void {
50
+ try {
51
+ writeSecure(pathOf(dir), `${JSON.stringify({ version: 1, enabled, scope })}\n`);
52
+ } catch {
53
+ throw new ApiError('Metro could not save the connector sync setting.', 503);
54
+ }
55
+ }
56
+
57
+ export function disableSavedSync(dir: string): void {
58
+ const saved = read(dir);
59
+ if (typeof saved !== 'string' && saved.enabled) saveSyncSetting(dir, false, saved.scope);
60
+ }
@@ -0,0 +1,39 @@
1
+ import { ApiError } from '@metro-labs/http/api-error';
2
+ import type { ConnectorSyncStatus } from '@metro-labs/core/connector-sync';
3
+ import { OrgConnectorControl } from './org-sync-control.js';
4
+ import { isOrgRelayId } from './relay-id.js';
5
+ import type { RelaySession } from './relay-session.js';
6
+
7
+ let active: OrgConnectorControl | null = null;
8
+
9
+ function control(): OrgConnectorControl {
10
+ if (active === null) throw new ApiError('Organization connector sync is unavailable. Restart Metro before trying again.', 503);
11
+ return active;
12
+ }
13
+
14
+ export function orgConnectorRelaySession(id: string): RelaySession | null {
15
+ return isOrgRelayId(id) ? control().open(id) : null;
16
+ }
17
+
18
+ export function orgConnectorSyncStatus(): ConnectorSyncStatus {
19
+ return control().status();
20
+ }
21
+
22
+ export function setOrgConnectorSync(enabled: boolean, scope: string): ConnectorSyncStatus {
23
+ return control().set(enabled, scope);
24
+ }
25
+
26
+ export function invalidateOrgConnectorSync(): void {
27
+ active?.invalidate();
28
+ }
29
+
30
+ export function stopOrgConnectorSync(): void {
31
+ active?.stop();
32
+ active = null;
33
+ }
34
+
35
+ export function watchOrgConnectorSync(deps: ConstructorParameters<typeof OrgConnectorControl>[0]): void {
36
+ stopOrgConnectorSync();
37
+ active = new OrgConnectorControl(deps);
38
+ active.start();
39
+ }