@sanoma-ai/workflows 0.9.1 → 0.10.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (207) hide show
  1. package/README.md +193 -50
  2. package/SECRET-SUPPORT.md +33 -0
  3. package/dist/apply-steps.js +5 -2
  4. package/dist/apply-steps.js.map +1 -1
  5. package/dist/apply.d.ts +3 -0
  6. package/dist/apply.js +27 -13
  7. package/dist/apply.js.map +1 -1
  8. package/dist/approvals.d.ts +1 -0
  9. package/dist/approvals.js +6 -1
  10. package/dist/approvals.js.map +1 -1
  11. package/dist/apps.d.ts +13 -24
  12. package/dist/apps.js +69 -68
  13. package/dist/apps.js.map +1 -1
  14. package/dist/ast.d.ts +9 -7
  15. package/dist/ast.js +2 -0
  16. package/dist/ast.js.map +1 -1
  17. package/dist/authentication.d.ts +54 -0
  18. package/dist/authentication.js +138 -0
  19. package/dist/authentication.js.map +1 -0
  20. package/dist/call-workflow.d.ts +5 -0
  21. package/dist/call-workflow.js +4 -3
  22. package/dist/call-workflow.js.map +1 -1
  23. package/dist/call.d.ts +3 -2
  24. package/dist/call.js +36 -7
  25. package/dist/call.js.map +1 -1
  26. package/dist/cedar.js +14 -1
  27. package/dist/cedar.js.map +1 -1
  28. package/dist/change-steps.js +7 -5
  29. package/dist/change-steps.js.map +1 -1
  30. package/dist/change.d.ts +7 -0
  31. package/dist/change.js +7 -0
  32. package/dist/change.js.map +1 -1
  33. package/dist/client.d.ts +62 -10
  34. package/dist/client.js +272 -47
  35. package/dist/client.js.map +1 -1
  36. package/dist/collection.d.ts +7 -0
  37. package/dist/collection.js +5 -2
  38. package/dist/collection.js.map +1 -1
  39. package/dist/config.d.ts +16 -4
  40. package/dist/config.js +89 -21
  41. package/dist/config.js.map +1 -1
  42. package/dist/connection.d.ts +389 -0
  43. package/dist/connection.js +657 -0
  44. package/dist/connection.js.map +1 -0
  45. package/dist/credentials.d.ts +7 -53
  46. package/dist/credentials.js +84 -247
  47. package/dist/credentials.js.map +1 -1
  48. package/dist/db.js +34 -2
  49. package/dist/db.js.map +1 -1
  50. package/dist/define.d.ts +9 -2
  51. package/dist/define.js.map +1 -1
  52. package/dist/definitions.d.ts +20 -0
  53. package/dist/definitions.js +16 -0
  54. package/dist/definitions.js.map +1 -0
  55. package/dist/deployment-key.d.ts +2 -0
  56. package/dist/deployment-key.js +22 -0
  57. package/dist/deployment-key.js.map +1 -0
  58. package/dist/describe.d.ts +15 -175
  59. package/dist/describe.js +122 -35
  60. package/dist/describe.js.map +1 -1
  61. package/dist/description.d.ts +532 -0
  62. package/dist/description.js +381 -0
  63. package/dist/description.js.map +1 -0
  64. package/dist/direct.js +7 -0
  65. package/dist/direct.js.map +1 -1
  66. package/dist/drift.d.ts +1 -1
  67. package/dist/drift.js +1 -1
  68. package/dist/drift.js.map +1 -1
  69. package/dist/env.d.ts +2 -0
  70. package/dist/env.js +2 -2
  71. package/dist/env.js.map +1 -1
  72. package/dist/fake.d.ts +13 -1
  73. package/dist/fake.js +70 -0
  74. package/dist/fake.js.map +1 -1
  75. package/dist/index.d.ts +11 -3
  76. package/dist/index.js +10 -2
  77. package/dist/index.js.map +1 -1
  78. package/dist/ledger.d.ts +2 -0
  79. package/dist/ledger.js +1 -1
  80. package/dist/ledger.js.map +1 -1
  81. package/dist/lint.d.ts +0 -9
  82. package/dist/lint.js +2 -17
  83. package/dist/lint.js.map +1 -1
  84. package/dist/load.d.ts +85 -0
  85. package/dist/load.js +391 -0
  86. package/dist/load.js.map +1 -0
  87. package/dist/lockfile.d.ts +2 -0
  88. package/dist/lockfile.js +8 -3
  89. package/dist/lockfile.js.map +1 -1
  90. package/dist/op.d.ts +22 -5
  91. package/dist/op.js +20 -2
  92. package/dist/op.js.map +1 -1
  93. package/dist/outline.d.ts +5 -0
  94. package/dist/outline.js +46 -5
  95. package/dist/outline.js.map +1 -1
  96. package/dist/paths.d.ts +18 -2
  97. package/dist/paths.js +19 -7
  98. package/dist/paths.js.map +1 -1
  99. package/dist/plugin.d.ts +0 -11
  100. package/dist/plugin.js +3 -18
  101. package/dist/plugin.js.map +1 -1
  102. package/dist/policy.d.ts +2 -0
  103. package/dist/policy.js.map +1 -1
  104. package/dist/resource.d.ts +10 -4
  105. package/dist/resource.js +11 -4
  106. package/dist/resource.js.map +1 -1
  107. package/dist/resources.d.ts +33 -76
  108. package/dist/resources.js +219 -227
  109. package/dist/resources.js.map +1 -1
  110. package/dist/run.d.ts +4 -0
  111. package/dist/run.js.map +1 -1
  112. package/dist/sandbox.d.ts +5 -2
  113. package/dist/sandbox.js +56 -7
  114. package/dist/sandbox.js.map +1 -1
  115. package/dist/scenario.d.ts +5 -0
  116. package/dist/scenario.js +3 -2
  117. package/dist/scenario.js.map +1 -1
  118. package/dist/scenarios.js +7 -1
  119. package/dist/scenarios.js.map +1 -1
  120. package/dist/schema.js +8 -0
  121. package/dist/schema.js.map +1 -1
  122. package/dist/secret-store-check.d.ts +11 -0
  123. package/dist/secret-store-check.js +76 -0
  124. package/dist/secret-store-check.js.map +1 -0
  125. package/dist/secret-store.d.ts +106 -0
  126. package/dist/secret-store.js +228 -0
  127. package/dist/secret-store.js.map +1 -0
  128. package/dist/secret.d.ts +2 -0
  129. package/dist/secret.js +32 -0
  130. package/dist/secret.js.map +1 -1
  131. package/dist/shared.d.ts +21 -11
  132. package/dist/shared.js +41 -7
  133. package/dist/shared.js.map +1 -1
  134. package/dist/sites.d.ts +4 -93
  135. package/dist/sites.js +76 -84
  136. package/dist/sites.js.map +1 -1
  137. package/dist/steps.d.ts +3 -0
  138. package/dist/steps.js.map +1 -1
  139. package/dist/version.d.ts +2 -1
  140. package/dist/version.js +2 -1
  141. package/dist/version.js.map +1 -1
  142. package/dist/wakeup-driver.js +15 -6
  143. package/dist/wakeup-driver.js.map +1 -1
  144. package/dist/worker.js +12 -8
  145. package/dist/worker.js.map +1 -1
  146. package/dist/writer.d.ts +53 -14
  147. package/dist/writer.js +113 -43
  148. package/dist/writer.js.map +1 -1
  149. package/oxlint.json +1 -5
  150. package/package.json +6 -1
  151. package/src/apply-steps.ts +5 -2
  152. package/src/apply.ts +54 -21
  153. package/src/approvals.ts +7 -1
  154. package/src/apps.ts +71 -86
  155. package/src/ast.ts +6 -6
  156. package/src/authentication.ts +191 -0
  157. package/src/call-workflow.ts +5 -4
  158. package/src/call.ts +52 -9
  159. package/src/cedar.ts +14 -1
  160. package/src/change-steps.ts +7 -4
  161. package/src/change.ts +10 -0
  162. package/src/client.ts +346 -45
  163. package/src/collection.ts +10 -2
  164. package/src/config.ts +107 -19
  165. package/src/connection.ts +912 -0
  166. package/src/credentials.ts +94 -281
  167. package/src/db.ts +34 -2
  168. package/src/define.ts +7 -2
  169. package/src/definitions.ts +31 -0
  170. package/src/deployment-key.ts +23 -0
  171. package/src/describe.ts +150 -227
  172. package/src/description.ts +426 -0
  173. package/src/direct.ts +7 -0
  174. package/src/drift.ts +10 -2
  175. package/src/env.ts +4 -2
  176. package/src/fake.ts +71 -0
  177. package/src/index.ts +53 -1
  178. package/src/ledger.ts +3 -1
  179. package/src/lint.ts +2 -17
  180. package/src/load.ts +466 -0
  181. package/src/lockfile.ts +10 -3
  182. package/src/op.ts +41 -7
  183. package/src/outline.ts +53 -7
  184. package/src/paths.ts +21 -6
  185. package/src/plugin.ts +3 -24
  186. package/src/policy.ts +2 -0
  187. package/src/resource.ts +24 -6
  188. package/src/resources.ts +246 -301
  189. package/src/run.ts +4 -0
  190. package/src/sandbox.ts +61 -7
  191. package/src/scenario.ts +24 -6
  192. package/src/scenarios.ts +7 -1
  193. package/src/schema.ts +10 -0
  194. package/src/secret-store-check.ts +93 -0
  195. package/src/secret-store.ts +314 -0
  196. package/src/secret.ts +29 -0
  197. package/src/shared.ts +44 -10
  198. package/src/sites.ts +85 -179
  199. package/src/steps.ts +3 -2
  200. package/src/version.ts +2 -1
  201. package/src/wakeup-driver.ts +22 -6
  202. package/src/worker.ts +12 -8
  203. package/src/writer.ts +145 -56
  204. package/dist/datafile.d.ts +0 -97
  205. package/dist/datafile.js +0 -479
  206. package/dist/datafile.js.map +0 -1
  207. package/src/datafile.ts +0 -601
@@ -0,0 +1,912 @@
1
+ import type { Principal } from "./define.ts";
2
+ import { createHash, randomUUID } from "node:crypto";
3
+ import { z } from "zod";
4
+ import {
5
+ checkAuthenticationStore,
6
+ decodeCredentials,
7
+ defineAuthentication,
8
+ verifyAuthentication,
9
+ AuthenticationError,
10
+ authenticationProblem,
11
+ type AuthenticationProblem,
12
+ type Authentication,
13
+ type CallAuthentication,
14
+ } from "./authentication.ts";
15
+ import { type Connector, setupOf, VENDOR, defineConnector, defineDriver, type CallContext } from "./op.ts";
16
+ import { isSecret, type Secret } from "./secret.ts";
17
+ import { SanomaError } from "./errors.ts";
18
+ import { SecretStoreError, type SecretAccess, type SecretLocation } from "./secret-store.ts";
19
+ import type { Db } from "./db.ts";
20
+
21
+ /** Serializable account reference; vendor literal prevents cross-connector selection in typed calls. */
22
+ export interface ConnectionRef<V extends string = string> {
23
+ readonly $connection: string;
24
+ readonly vendor: V;
25
+ readonly revision?: string;
26
+ }
27
+ export interface ConnectionDefinition<V extends string = string> extends ConnectionRef<V> {
28
+ readonly name: string;
29
+ readonly method: string;
30
+ readonly credentials?: Secret;
31
+ readonly scopes: readonly string[];
32
+ readonly account?: string;
33
+ readonly default: boolean;
34
+ }
35
+ export interface ConnectionRule<V extends string = string> {
36
+ readonly name: string;
37
+ readonly vendor: V;
38
+ readonly method: string;
39
+ readonly createBy: readonly (string | { readonly group: string })[];
40
+ readonly scopes: readonly string[];
41
+ }
42
+ export interface ConnectionSnapshot {
43
+ id: string;
44
+ vendor: string;
45
+ method: string;
46
+ account: string;
47
+ scopes: string[];
48
+ revision: string;
49
+ definition: string;
50
+ /** A logical reference only, never the value or a provider credential. */
51
+ credentials?: Secret;
52
+ }
53
+ export type ConnectionTarget = { connection: ConnectionRef } | { rule: string };
54
+ export interface ConnectionCard {
55
+ id: string;
56
+ vendor: string;
57
+ name: string;
58
+ method: string;
59
+ account?: string;
60
+ scopes: readonly string[];
61
+ requiredScopes: readonly string[];
62
+ expectedAccount?: string;
63
+ revision?: string;
64
+ owner?: string;
65
+ status: "missing" | "connected" | "disconnected" | "pending" | "uncertain" | "configuration_changed";
66
+ location?: SecretLocation;
67
+ boundLocation?: SecretLocation;
68
+ updatedBy?: string;
69
+ updatedAt?: string;
70
+ health?: ConnectionHealth;
71
+ }
72
+ export interface ConnectionHealth {
73
+ state:
74
+ | AuthenticationProblem
75
+ | "connected"
76
+ | "disconnected"
77
+ | "pending"
78
+ | "configuration_changed"
79
+ | "store_denied"
80
+ | "invalid";
81
+ checkedAt: string;
82
+ externallyRenewed: boolean;
83
+ }
84
+ export interface ConnectionSetup {
85
+ target: ConnectionTarget;
86
+ id: string;
87
+ vendor: string;
88
+ method: string;
89
+ definition: string;
90
+ credential?: string;
91
+ location?: SecretLocation;
92
+ expectedRevision: string | null;
93
+ requiredScopes: readonly string[];
94
+ expectedAccount?: string;
95
+ previousAccount?: string;
96
+ previousLocation?: SecretLocation;
97
+ }
98
+ const idPart = /^[a-z][a-z0-9-]{0,63}$/;
99
+ function refuse(message: string): never {
100
+ throw new SanomaError("invalid_input", message);
101
+ }
102
+ export const connectionRefSchema = z.object({
103
+ $connection: z.string().min(1),
104
+ vendor: z.string().min(1),
105
+ revision: z.string().optional(),
106
+ });
107
+ const snapshotSchema = z.object({
108
+ id: z.string(),
109
+ vendor: z.string(),
110
+ method: z.string(),
111
+ account: z.string(),
112
+ scopes: z.array(z.string()),
113
+ revision: z.string(),
114
+ definition: z.string(),
115
+ credentials: z.object({ $secret: z.string() }).optional(),
116
+ });
117
+ export const connectionTargetSchema = z.union([
118
+ z.object({ connection: connectionRefSchema }),
119
+ z.object({ rule: z.string().min(1) }),
120
+ ]);
121
+ const setupSchema = z.object({
122
+ target: connectionTargetSchema,
123
+ id: z.string(),
124
+ vendor: z.string(),
125
+ method: z.string(),
126
+ definition: z.string(),
127
+ credential: z.string().optional(),
128
+ location: z
129
+ .object({ store: z.string(), namespace: z.string(), path: z.string(), management: z.enum(["sanoma", "external"]) })
130
+ .optional(),
131
+ expectedRevision: z.string().nullable(),
132
+ requiredScopes: z.array(z.string()),
133
+ expectedAccount: z.string().optional(),
134
+ previousAccount: z.string().optional(),
135
+ previousLocation: z
136
+ .object({ store: z.string(), namespace: z.string(), path: z.string(), management: z.enum(["sanoma", "external"]) })
137
+ .optional(),
138
+ });
139
+
140
+ export function defineConnection<C extends Connector<any, any>>(
141
+ connector: C,
142
+ options: {
143
+ name: string;
144
+ method: string;
145
+ credentials?: Secret;
146
+ scopes?: readonly string[];
147
+ account?: string;
148
+ default?: boolean;
149
+ },
150
+ ): ConnectionDefinition<C[typeof VENDOR]["id"]> {
151
+ if (!idPart.test(options.name)) refuse("A connection needs a stable lowercase name");
152
+ const vendor = connector[VENDOR].id;
153
+ const auth = setupOf(connector).authentication?.[options.method];
154
+ if (!auth) refuse("The connector does not declare this authentication method");
155
+ if (auth.kind === "workload-identity" ? options.credentials !== undefined : !isSecret(options.credentials))
156
+ refuse("Credentials must match the authentication method");
157
+ return Object.freeze({
158
+ $connection: `${vendor}/${options.name}`,
159
+ vendor,
160
+ name: options.name,
161
+ method: options.method,
162
+ ...(options.credentials && { credentials: Object.freeze({ $secret: options.credentials.$secret }) }),
163
+ scopes: Object.freeze([...(options.scopes ?? [])]),
164
+ ...(options.account && { account: options.account }),
165
+ default: options.default ?? false,
166
+ });
167
+ }
168
+
169
+ export function defineConnectionRule<C extends Connector<any, any>>(
170
+ connector: C,
171
+ options: {
172
+ name: string;
173
+ method: string;
174
+ createBy: readonly (string | { readonly group: string })[];
175
+ scopes?: readonly string[];
176
+ },
177
+ ): ConnectionRule<C[typeof VENDOR]["id"]> {
178
+ if (
179
+ !idPart.test(options.name) ||
180
+ !options.createBy.length ||
181
+ options.createBy.some((x) =>
182
+ typeof x === "string" ? !x.trim() : !x || typeof x.group !== "string" || !x.group.trim(),
183
+ )
184
+ )
185
+ refuse("A connection rule needs a name and allowed creators");
186
+ if (!setupOf(connector).authentication?.[options.method])
187
+ refuse("The connector does not declare this authentication method");
188
+ return Object.freeze({
189
+ name: options.name,
190
+ vendor: connector[VENDOR].id,
191
+ method: options.method,
192
+ createBy: Object.freeze(options.createBy.map((x) => (typeof x === "string" ? x : Object.freeze({ ...x })))),
193
+ scopes: Object.freeze([...(options.scopes ?? [])]),
194
+ });
195
+ }
196
+
197
+ /** Reconstitutes a dynamic reference; authority is checked from the persisted record on every call. */
198
+ export function connectionRef<V extends string>(rule: ConnectionRule<V>, id: string): ConnectionRef<V> {
199
+ if (!id.startsWith(`${rule.vendor}/${rule.name}/`)) refuse("The connection is outside this rule");
200
+ return Object.freeze({ $connection: id, vendor: rule.vendor });
201
+ }
202
+
203
+ export interface ConnectionCatalog {
204
+ definitions: ReadonlyMap<string, ConnectionDefinition>;
205
+ rules: ReadonlyMap<string, ConnectionRule>;
206
+ methods: ReadonlyMap<string, Readonly<Record<string, Authentication>>>;
207
+ }
208
+ export function connectionCatalog(
209
+ connectors: readonly Connector<any, any>[],
210
+ definitions: readonly ConnectionDefinition[] = [],
211
+ rules: readonly ConnectionRule[] = [],
212
+ ): ConnectionCatalog {
213
+ const methods = new Map<string, Record<string, Authentication>>();
214
+ for (const connector of connectors) {
215
+ const vendor = connector[VENDOR].id;
216
+ const entries = methods.get(vendor) ?? {};
217
+ for (const [name, method] of Object.entries(setupOf(connector).authentication ?? {})) {
218
+ if (entries[name] && entries[name] !== method) refuse("Conflicting authentication methods for a connector");
219
+ defineAuthentication(method);
220
+ entries[name] = method;
221
+ }
222
+ methods.set(vendor, entries);
223
+ }
224
+ const defined = new Map<string, ConnectionDefinition>();
225
+ const defaults = new Set<string>();
226
+ for (const d of definitions) {
227
+ if (
228
+ !d ||
229
+ !idPart.test(d.name) ||
230
+ d.$connection !== `${d.vendor}/${d.name}` ||
231
+ !methods.get(d.vendor)?.[d.method] ||
232
+ defined.has(d.$connection)
233
+ )
234
+ refuse("Invalid or duplicate connection declaration");
235
+ const auth = methods.get(d.vendor)![d.method]!;
236
+ if (auth.kind === "workload-identity" ? d.credentials !== undefined : !isSecret(d.credentials))
237
+ refuse("Credentials must match the authentication method");
238
+ if (d.default && defaults.has(d.vendor)) refuse("A connector can have only one explicit default connection");
239
+ if (d.default) defaults.add(d.vendor);
240
+ defined.set(d.$connection, d);
241
+ }
242
+ const dynamic = new Map<string, ConnectionRule>();
243
+ for (const r of rules) {
244
+ const id = `${r.vendor}/${r.name}`;
245
+ if (
246
+ !idPart.test(r.name) ||
247
+ !methods.get(r.vendor)?.[r.method] ||
248
+ dynamic.has(id) ||
249
+ defined.has(id) ||
250
+ !r.createBy.length
251
+ )
252
+ refuse("Invalid or duplicate connection rule");
253
+ dynamic.set(id, r);
254
+ }
255
+ return { definitions: defined, rules: dynamic, methods };
256
+ }
257
+
258
+ type ConnectionRow = {
259
+ id: string;
260
+ vendor: string;
261
+ method: string;
262
+ owner: string | null;
263
+ rule: string | null;
264
+ account: string;
265
+ scopes: string[];
266
+ revision: string;
267
+ definition: string;
268
+ credential: string | null;
269
+ location?: SecretLocation | null;
270
+ status: "connected" | "disconnected" | "pending" | "uncertain";
271
+ updated_by?: string;
272
+ updated_at?: Date;
273
+ health?: ConnectionHealth["state"];
274
+ checked_at?: Date;
275
+ externally_renewed?: boolean;
276
+ };
277
+ const snapshot = (r: ConnectionRow): ConnectionSnapshot => ({
278
+ id: r.id,
279
+ vendor: r.vendor,
280
+ method: r.method,
281
+ account: r.account,
282
+ scopes: r.scopes,
283
+ revision: r.revision,
284
+ definition: r.definition,
285
+ ...(r.credential && { credentials: { $secret: r.credential } }),
286
+ });
287
+ const fingerprint = (declaration: ConnectionDefinition | ConnectionRule, method: Authentication): string =>
288
+ createHash("sha256")
289
+ .update(JSON.stringify({ declaration, kind: method.kind, version: method.version, storage: method.storage }))
290
+ .digest("hex");
291
+
292
+ /** Persists account metadata only. Secret values are handled outside these operations. */
293
+ export class ConnectionRegistry {
294
+ readonly catalog: ConnectionCatalog;
295
+ private readonly db: () => Promise<Db>;
296
+ private readonly secrets?: SecretAccess;
297
+ constructor(catalog: ConnectionCatalog, db: () => Promise<Db>, secrets?: SecretAccess) {
298
+ this.catalog = catalog;
299
+ this.db = db;
300
+ this.secrets = secrets;
301
+ }
302
+
303
+ /** A direct metadata write uses the same transaction as its default ledger record. */
304
+ onDatabase(db: Db): ConnectionRegistry {
305
+ return new ConnectionRegistry(this.catalog, async () => db, this.secrets);
306
+ }
307
+
308
+ /** Safe card data only. Listing does not read credential values or contact a vendor. */
309
+ async cards(actor: string): Promise<ConnectionCard[]> {
310
+ const rows = (
311
+ await (
312
+ await this.db()
313
+ ).query<ConnectionRow>(
314
+ "SELECT c.*, h.health, h.checked_at, h.externally_renewed FROM sanoma_connections c LEFT JOIN sanoma_connection_health h ON c.id=h.connection_id AND c.revision=h.revision WHERE c.owner IS NULL OR c.owner=$1",
315
+ [actor],
316
+ )
317
+ ).rows;
318
+ const found = new Map(rows.map((r) => [r.id, r]));
319
+ const ids = new Set([...this.catalog.definitions.keys(), ...rows.filter((r) => r.rule).map((r) => r.id)]);
320
+ const cards: ConnectionCard[] = [];
321
+ for (const id of ids) {
322
+ const row = found.get(id);
323
+ const declaration = row?.rule ? this.catalog.rules.get(row.rule) : this.catalog.definitions.get(id);
324
+ if (!declaration || (row?.rule && row.owner !== actor)) continue;
325
+ const method = this.catalog.methods.get(declaration.vendor)?.[declaration.method];
326
+ if (!method) continue;
327
+ const credential =
328
+ method.kind === "workload-identity"
329
+ ? undefined
330
+ : "default" in declaration
331
+ ? declaration.credentials?.$secret
332
+ : row?.credential;
333
+ cards.push({
334
+ id,
335
+ vendor: declaration.vendor,
336
+ name: row?.rule ? id.slice(declaration.vendor.length + 1) : declaration.name,
337
+ method: declaration.method,
338
+ ...(row && { account: row.account, revision: row.revision }),
339
+ scopes: row?.scopes ?? [],
340
+ requiredScopes: declaration.scopes,
341
+ ...("account" in declaration && declaration.account && { expectedAccount: declaration.account }),
342
+ ...(row?.owner && { owner: row.owner }),
343
+ status: !row
344
+ ? "missing"
345
+ : row.definition !== this.bindingFingerprint(declaration, method, credential)
346
+ ? "configuration_changed"
347
+ : row.status,
348
+ ...(credential && this.secrets && { location: this.secrets.location(credential) }),
349
+ ...(row?.location && { boundLocation: row.location }),
350
+ ...(row?.updated_by && { updatedBy: row.updated_by }),
351
+ ...(row?.updated_at && { updatedAt: row.updated_at.toISOString() }),
352
+ ...(row?.health &&
353
+ row.checked_at && {
354
+ health: {
355
+ state: row.health,
356
+ checkedAt: row.checked_at.toISOString(),
357
+ externallyRenewed: row.externally_renewed ?? false,
358
+ },
359
+ }),
360
+ });
361
+ }
362
+ return cards;
363
+ }
364
+
365
+ /** Resolve code-defined setup authority without reading a credential. The request id stays
366
+ * stable across preview, approval and retry; account allocation is scoped to its principal. */
367
+ async setup(target: ConnectionTarget, actor: Principal, requestId: string): Promise<ConnectionSetup> {
368
+ let declaration: ConnectionDefinition | ConnectionRule | undefined;
369
+ let row: ConnectionRow | undefined;
370
+ let id: string;
371
+ let credential: string | undefined;
372
+ if ("rule" in target) {
373
+ const rule = this.catalog.rules.get(target.rule);
374
+ if (
375
+ !rule ||
376
+ !rule.createBy.some((by) => (typeof by === "string" ? by === actor.id : actor.groups?.includes(by.group)))
377
+ )
378
+ throw new SanomaError("policy_denied", "This principal cannot create connections under this rule");
379
+ declaration = rule;
380
+ const allocation = createHash("sha256")
381
+ .update(JSON.stringify([actor.id, target.rule, requestId]))
382
+ .digest("hex");
383
+ id = `${target.rule}/${allocation}`;
384
+ credential = `CONNECTION_${allocation.toUpperCase()}`;
385
+ row = await this.row(id);
386
+ } else {
387
+ id = target.connection.$connection;
388
+ row = await this.row(id);
389
+ declaration = row?.rule ? this.catalog.rules.get(row.rule) : this.catalog.definitions.get(id);
390
+ if (!declaration || declaration.vendor !== target.connection.vendor) refuse("The connection is not declared");
391
+ if (row?.rule && row.owner !== actor.id)
392
+ throw new SanomaError("policy_denied", "The connection belongs to another principal");
393
+ credential = "credentials" in declaration ? declaration.credentials?.$secret : (row?.credential ?? undefined);
394
+ }
395
+ const method = this.catalog.methods.get(declaration.vendor)?.[declaration.method];
396
+ if (!method?.verify) throw new AuthenticationError("unsupported");
397
+ if (method.kind === "workload-identity") credential = undefined;
398
+ this.checkStore(method, credential);
399
+ return {
400
+ target,
401
+ id,
402
+ vendor: declaration.vendor,
403
+ method: declaration.method,
404
+ definition: this.bindingFingerprint(declaration, method, credential),
405
+ ...(credential && { credential, ...(this.secrets && { location: this.secrets.location(credential) }) }),
406
+ expectedRevision: row?.revision ?? null,
407
+ requiredScopes: declaration.scopes,
408
+ ...("account" in declaration && declaration.account && { expectedAccount: declaration.account }),
409
+ ...(row && { previousAccount: row.account }),
410
+ ...(row?.location && { previousLocation: row.location }),
411
+ };
412
+ }
413
+
414
+ /** Metadata-only, policy-authorized reservation. Calls cannot use it until activation verifies
415
+ * the saved bundle. A store write failure leaves an explicit uncertain, unusable account. */
416
+ async configure(
417
+ target: ConnectionTarget,
418
+ requestId: string,
419
+ expectedRevision: string | null,
420
+ definition: string,
421
+ account: string,
422
+ scopes: string[],
423
+ actor: Principal,
424
+ ): Promise<ConnectionSnapshot> {
425
+ const setup = await this.setup(target, actor, requestId);
426
+ if (setup.definition !== definition || setup.expectedRevision !== expectedRevision)
427
+ refuse("The connection changed; review it again before saving");
428
+ if (setup.expectedAccount && setup.expectedAccount !== account) throw new AuthenticationError("wrong_account");
429
+ if (setup.requiredScopes.some((s) => !scopes.includes(s))) throw new AuthenticationError("scope_changed");
430
+ const current = await this.row(setup.id);
431
+ const row: ConnectionRow = {
432
+ id: setup.id,
433
+ vendor: setup.vendor,
434
+ method: setup.method,
435
+ owner: "rule" in target ? actor.id : (current?.owner ?? null),
436
+ rule: "rule" in target ? target.rule : (current?.rule ?? null),
437
+ account,
438
+ scopes,
439
+ revision: randomUUID(),
440
+ definition,
441
+ credential: setup.credential ?? null,
442
+ status: "pending",
443
+ };
444
+ await this.save(row, expectedRevision, actor.id);
445
+ return snapshot(row);
446
+ }
447
+
448
+ async uncertain(ref: ConnectionRef, revision: string, actor: string): Promise<void> {
449
+ await (
450
+ await this.db()
451
+ ).query(
452
+ "UPDATE sanoma_connections SET status='uncertain',updated_by=$3,updated_at=now() WHERE id=$1 AND revision=$2 AND status='pending'",
453
+ [ref.$connection, revision, actor],
454
+ );
455
+ }
456
+
457
+ async storedVersion(id: string, revision: string): Promise<string | undefined> {
458
+ return (
459
+ await (
460
+ await this.db()
461
+ ).query<{ credential_version: string }>(
462
+ "SELECT credential_version FROM sanoma_connection_setups WHERE connection_id=$1 AND revision=$2",
463
+ [id, revision],
464
+ )
465
+ ).rows[0]?.credential_version;
466
+ }
467
+
468
+ async recordStoredVersion(id: string, revision: string, version: string): Promise<void> {
469
+ await (
470
+ await this.db()
471
+ ).query(
472
+ "INSERT INTO sanoma_connection_setups (connection_id,revision,credential_version) SELECT id,revision,$3 FROM sanoma_connections WHERE id=$1 AND revision=$2 AND status='pending' ON CONFLICT DO NOTHING",
473
+ [id, revision, version],
474
+ );
475
+ if ((await this.storedVersion(id, revision)) !== version) throw new SecretStoreError("conflict");
476
+ }
477
+
478
+ private async health(
479
+ id: string,
480
+ revision: string,
481
+ state: ConnectionHealth["state"],
482
+ version?: string,
483
+ external = false,
484
+ ): Promise<ConnectionHealth> {
485
+ const previous = (
486
+ await (
487
+ await this.db()
488
+ ).query<{ credential_version: string | null }>(
489
+ "SELECT credential_version FROM sanoma_connection_health WHERE connection_id=$1 AND revision=$2",
490
+ [id, revision],
491
+ )
492
+ ).rows[0];
493
+ const renewed =
494
+ external &&
495
+ previous?.credential_version != null &&
496
+ version !== undefined &&
497
+ previous.credential_version !== version;
498
+ const result = await (
499
+ await this.db()
500
+ ).query<{ checked_at: Date }>(
501
+ "INSERT INTO sanoma_connection_health (connection_id,revision,health,credential_version,externally_renewed) SELECT id,revision,$3,$4,$5 FROM sanoma_connections WHERE id=$1 AND revision=$2 ON CONFLICT(connection_id) DO UPDATE SET revision=excluded.revision,health=excluded.health,credential_version=excluded.credential_version,externally_renewed=excluded.externally_renewed,checked_at=now() RETURNING checked_at",
502
+ [id, revision, state, version ?? previous?.credential_version ?? null, renewed],
503
+ );
504
+ const checked = result.rows[0];
505
+ if (!checked) refuse("The connection changed during the test; reload before testing it again");
506
+ return { state, checkedAt: checked.checked_at.toISOString(), externallyRenewed: renewed };
507
+ }
508
+
509
+ async test(ref: ConnectionRef, actor: Principal): Promise<ConnectionHealth> {
510
+ const setup = await this.setup({ connection: ref }, actor, "test");
511
+ const row = await this.row(setup.id);
512
+ if (!row) return { state: "missing", checkedAt: new Date().toISOString(), externallyRenewed: false };
513
+ if (row.definition !== setup.definition)
514
+ return { state: "configuration_changed", checkedAt: new Date().toISOString(), externallyRenewed: false };
515
+ if (row.status !== "connected") return this.health(row.id, row.revision, row.status);
516
+ try {
517
+ const material = await this.authenticate(snapshot(row), actor.id);
518
+ return this.health(
519
+ row.id,
520
+ row.revision,
521
+ "connected",
522
+ material.credentialVersion,
523
+ setup.location?.management === "external" || !this.secrets?.store.capabilities.writable,
524
+ );
525
+ } catch (error) {
526
+ const code = (error as { code?: string })?.code;
527
+ const state =
528
+ authenticationProblem(error) ??
529
+ (code === "denied" ? "store_denied" : code === "invalid_value" ? "invalid" : "unavailable");
530
+ return this.health(row.id, row.revision, state);
531
+ }
532
+ }
533
+
534
+ async setupState(selected: ConnectionSnapshot, actor: Principal): Promise<"pending" | "connected"> {
535
+ const setup = await this.setup(
536
+ { connection: { vendor: selected.vendor, $connection: selected.id } },
537
+ actor,
538
+ "state",
539
+ );
540
+ const row = await this.row(selected.id);
541
+ if (
542
+ !row ||
543
+ row.definition !== setup.definition ||
544
+ row.account !== selected.account ||
545
+ JSON.stringify(row.scopes.toSorted()) !== JSON.stringify(selected.scopes.toSorted())
546
+ )
547
+ refuse("The connection changed; review it again before saving");
548
+ if (row.status === "connected") return "connected";
549
+ if (row.status !== "pending" || row.revision !== selected.revision)
550
+ refuse("The connection changed; review it again before saving");
551
+ return "pending";
552
+ }
553
+
554
+ /** Used inside an authorized operation; verification reads stay inside its driver step. */
555
+ async activate(ref: ConnectionRef, revision: string, actor: Principal): Promise<ConnectionSnapshot> {
556
+ const setup = await this.setup({ connection: ref }, actor, "activate");
557
+ const row = await this.row(setup.id);
558
+ if (
559
+ !row ||
560
+ row.revision !== revision ||
561
+ row.definition !== setup.definition ||
562
+ !["pending", "uncertain"].includes(row.status)
563
+ )
564
+ refuse("The connection changed; review it again before activating");
565
+ const method = this.catalog.methods.get(row.vendor)![row.method]!;
566
+ const bundle = row.credential ? await this.secrets?.read(row.credential) : undefined;
567
+ if (row.credential && !bundle) throw new SecretStoreError("unavailable");
568
+ const identity = await verifyAuthentication(method, bundle && decodeCredentials(method, bundle.value));
569
+ if (identity.account !== row.account) throw new AuthenticationError("wrong_account");
570
+ if (JSON.stringify(identity.scopes) !== JSON.stringify([...new Set(row.scopes)].toSorted()))
571
+ throw new AuthenticationError("scope_changed");
572
+ const next = randomUUID();
573
+ const result = await (
574
+ await this.db()
575
+ ).query(
576
+ "UPDATE sanoma_connections SET status='connected',revision=$3,updated_by=$4,updated_at=now() WHERE id=$1 AND revision=$2 RETURNING id",
577
+ [row.id, revision, next, actor.id],
578
+ );
579
+ if (!result.rowCount) refuse("The connection changed; review it again before activating");
580
+ await this.health(row.id, next, "connected", bundle?.version);
581
+ return snapshot({ ...row, revision: next, status: "connected" });
582
+ }
583
+
584
+ private bindingFingerprint(
585
+ declaration: ConnectionDefinition | ConnectionRule,
586
+ method: Authentication,
587
+ credential?: string | null,
588
+ ): string {
589
+ const name = credential ?? ("credentials" in declaration ? declaration.credentials?.$secret : undefined);
590
+ const location = name ? this.secrets?.location(name) : undefined;
591
+ return createHash("sha256")
592
+ .update(JSON.stringify({ contract: fingerprint(declaration, method), location }))
593
+ .digest("hex");
594
+ }
595
+
596
+ private checkStore(method: Authentication, credential?: string | null): void {
597
+ if (!this.secrets || !credential) return;
598
+ const location = this.secrets.location(credential);
599
+ const caps =
600
+ location.namespace === ""
601
+ ? {
602
+ writable: false,
603
+ maxBytes: Number.MAX_SAFE_INTEGER,
604
+ conditionalWrites: "none" as const,
605
+ deletion: "unsupported" as const,
606
+ changeDetection: "read" as const,
607
+ }
608
+ : this.secrets.store.capabilities;
609
+ checkAuthenticationStore(method, caps, location.management);
610
+ }
611
+
612
+ private async row(id: string): Promise<ConnectionRow | undefined> {
613
+ return (await (await this.db()).query<ConnectionRow>("SELECT * FROM sanoma_connections WHERE id=$1", [id])).rows[0];
614
+ }
615
+
616
+ async select(vendor: string, ref: ConnectionRef | undefined, actor: string): Promise<ConnectionSnapshot | undefined> {
617
+ if (!ref) {
618
+ const defaults = [...this.catalog.definitions.values()].filter((d) => d.vendor === vendor && d.default);
619
+ if (defaults[0]) ref = defaults[0];
620
+ else if (
621
+ Object.keys(this.catalog.methods.get(vendor) ?? {}).length ||
622
+ [...this.catalog.definitions.values()].some((d) => d.vendor === vendor)
623
+ )
624
+ refuse("Select a named connection or declare an explicit default");
625
+ else return undefined; // Operations without an authentication method need no connection.
626
+ }
627
+ if (!ref || ref.vendor !== vendor) refuse("The selected connection belongs to another connector");
628
+ const row = await this.row(ref.$connection);
629
+ if (!row || row.vendor !== vendor || row.status !== "connected")
630
+ refuse("The connection is missing or disconnected");
631
+ if (ref.revision !== undefined && ref.revision !== row.revision)
632
+ refuse("The connection changed after authorization; start a new call");
633
+ const declaration = row.rule ? this.catalog.rules.get(row.rule) : this.catalog.definitions.get(row.id);
634
+ if (!declaration || declaration.vendor !== vendor || declaration.method !== row.method)
635
+ refuse("The connection is not declared");
636
+ if (row.rule && row.owner !== actor)
637
+ throw new SanomaError("policy_denied", "The connection belongs to another principal");
638
+ const method = this.catalog.methods.get(vendor)?.[row.method];
639
+ if (!method || row.definition !== this.bindingFingerprint(declaration, method, row.credential))
640
+ refuse("The connection declaration changed; reconnect before use");
641
+ this.checkStore(method, row.credential);
642
+ return snapshot(row);
643
+ }
644
+
645
+ async assertCurrent(selected: ConnectionSnapshot | undefined, actor: string): Promise<void> {
646
+ if (!selected) return;
647
+ const current = await this.select(selected.vendor, { vendor: selected.vendor, $connection: selected.id }, actor);
648
+ if (
649
+ !current ||
650
+ current.revision !== selected.revision ||
651
+ current.definition !== selected.definition ||
652
+ current.method !== selected.method ||
653
+ current.account !== selected.account ||
654
+ current.credentials?.$secret !== selected.credentials?.$secret ||
655
+ JSON.stringify(current.scopes.toSorted()) !== JSON.stringify(selected.scopes.toSorted())
656
+ )
657
+ refuse("The connection changed after authorization; start a new call");
658
+ }
659
+
660
+ /** Only called inside an authorized driver boundary. No value escapes into workflow history. */
661
+ async authenticate(selected: ConnectionSnapshot, actor: string): Promise<CallAuthentication> {
662
+ await this.assertCurrent(selected, actor);
663
+ const method = this.catalog.methods.get(selected.vendor)?.[selected.method];
664
+ if (!method?.verify) throw new AuthenticationError("unsupported");
665
+ const material: CallAuthentication = { method: selected.method, kind: method.kind };
666
+ if (method.kind !== "workload-identity") {
667
+ if (!this.secrets || !selected.credentials) throw new SecretStoreError("unavailable");
668
+ const bundle = await this.secrets.read(selected.credentials.$secret);
669
+ if (!bundle) throw new AuthenticationError("missing");
670
+ material.credentials = decodeCredentials(method, bundle.value);
671
+ material.credentialVersion = bundle.version;
672
+ }
673
+ const identity = await verifyAuthentication(method, material.credentials);
674
+ if (identity.account !== selected.account) throw new AuthenticationError("wrong_account");
675
+ if (JSON.stringify(identity.scopes) !== JSON.stringify([...new Set(selected.scopes)].toSorted()))
676
+ throw new AuthenticationError("scope_changed");
677
+ // A disconnect or rebind while verification was in flight revokes this invocation too.
678
+ await this.assertCurrent(selected, actor);
679
+ return material;
680
+ }
681
+
682
+ async bind(
683
+ ref: ConnectionRef,
684
+ account: string,
685
+ scopes: string[],
686
+ expectedRevision: string | null,
687
+ actor: string,
688
+ ): Promise<ConnectionSnapshot> {
689
+ const declaration = this.catalog.definitions.get(ref.$connection);
690
+ if (!declaration || declaration.vendor !== ref.vendor) refuse("The connection is not declared");
691
+ if (declaration.account && account !== declaration.account)
692
+ refuse("The account does not match the connection requirement");
693
+ if (declaration.scopes.some((s) => !scopes.includes(s))) refuse("The account has not granted the required scopes");
694
+ const method = this.catalog.methods.get(ref.vendor)![declaration.method]!;
695
+ const row: ConnectionRow = {
696
+ id: ref.$connection,
697
+ vendor: ref.vendor,
698
+ method: declaration.method,
699
+ owner: null,
700
+ rule: null,
701
+ account,
702
+ scopes,
703
+ revision: randomUUID(),
704
+ definition: this.bindingFingerprint(declaration, method),
705
+ credential: declaration.credentials?.$secret ?? null,
706
+ status: "connected",
707
+ };
708
+ this.checkStore(method, row.credential);
709
+ await this.save(row, expectedRevision, actor);
710
+ return snapshot(row);
711
+ }
712
+
713
+ async create(
714
+ ruleId: string,
715
+ account: string,
716
+ scopes: string[],
717
+ actor: Principal | string,
718
+ ): Promise<ConnectionSnapshot> {
719
+ const rule = this.catalog.rules.get(ruleId);
720
+ const person = typeof actor === "string" ? { id: actor } : actor;
721
+ if (
722
+ !rule ||
723
+ !rule.createBy.some((by) => (typeof by === "string" ? by === person.id : person.groups?.includes(by.group)))
724
+ )
725
+ throw new SanomaError("policy_denied", "This principal cannot create connections under this rule");
726
+ if (rule.scopes.some((s) => !scopes.includes(s))) refuse("The account has not granted the required scopes");
727
+ const method = this.catalog.methods.get(rule.vendor)![rule.method]!;
728
+ const id = `${ruleId}/${randomUUID()}`;
729
+ const credential =
730
+ method.kind === "workload-identity" ? null : `CONNECTION_${randomUUID().replaceAll("-", "").toUpperCase()}`;
731
+ const row: ConnectionRow = {
732
+ id,
733
+ vendor: rule.vendor,
734
+ method: rule.method,
735
+ owner: person.id,
736
+ rule: ruleId,
737
+ account,
738
+ scopes,
739
+ revision: randomUUID(),
740
+ definition: this.bindingFingerprint(rule, method, credential),
741
+ credential,
742
+ status: "connected",
743
+ };
744
+ this.checkStore(method, row.credential);
745
+ await this.save(row, null, person.id);
746
+ return snapshot(row);
747
+ }
748
+
749
+ async disconnect(
750
+ ref: ConnectionRef,
751
+ expectedRevision: string,
752
+ actor: string,
753
+ ): Promise<{ id: string; revision: string; status: "disconnected" }> {
754
+ const row = await this.row(ref.$connection);
755
+ if (
756
+ !row ||
757
+ row.vendor !== ref.vendor ||
758
+ (row.rule ? !this.catalog.rules.has(row.rule) : !this.catalog.definitions.has(row.id))
759
+ )
760
+ refuse("The connection is not declared");
761
+ if (row.rule && row.owner !== actor)
762
+ throw new SanomaError("policy_denied", "The connection belongs to another principal");
763
+ const revision = randomUUID();
764
+ const changed = await (
765
+ await this.db()
766
+ ).query(
767
+ "UPDATE sanoma_connections SET status='disconnected',revision=$2,updated_by=$3,updated_at=now() WHERE id=$1 AND revision=$4 RETURNING id",
768
+ [row.id, revision, actor, expectedRevision],
769
+ );
770
+ if (!changed.rowCount) refuse("The connection changed; reload before disconnecting it");
771
+ return { id: row.id, revision, status: "disconnected" };
772
+ }
773
+
774
+ private async save(row: ConnectionRow, expected: string | null, actor: string): Promise<void> {
775
+ const values = [
776
+ row.id,
777
+ row.vendor,
778
+ row.method,
779
+ row.owner,
780
+ row.rule,
781
+ row.account,
782
+ JSON.stringify(row.scopes),
783
+ row.revision,
784
+ row.definition,
785
+ row.credential,
786
+ actor,
787
+ row.status,
788
+ row.credential && this.secrets ? JSON.stringify(this.secrets.location(row.credential)) : null,
789
+ ];
790
+ const query =
791
+ expected === null
792
+ ? "INSERT INTO sanoma_connections (id,vendor,method,owner,rule,account,scopes,revision,definition,credential,updated_by,status,location) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13) ON CONFLICT(id) DO NOTHING RETURNING id"
793
+ : "UPDATE sanoma_connections SET vendor=$2,method=$3,owner=$4,rule=$5,account=$6,scopes=$7,revision=$8,definition=$9,credential=$10,updated_by=$11,updated_at=now(),status=$12,location=$13 WHERE id=$1 AND revision=$14 RETURNING id";
794
+ const result = await (await this.db()).query(query, [...values, ...(expected === null ? [] : [expected])]);
795
+ if (!result.rowCount) refuse("The connection changed; reload before binding it");
796
+ }
797
+ }
798
+
799
+ /** Metadata mutations are access operations, so they are policy-reviewed and audited like other effects. */
800
+ export const connectionOps = defineConnector("sanoma", {
801
+ connection: {
802
+ test: {
803
+ effect: "read",
804
+ input: z.object({ connection: connectionRefSchema }),
805
+ output: z.object({
806
+ state: z.enum([
807
+ "missing",
808
+ "expired",
809
+ "revoked",
810
+ "rejected",
811
+ "wrong_account",
812
+ "scope_changed",
813
+ "uncertain",
814
+ "unavailable",
815
+ "unsupported",
816
+ "connected",
817
+ "disconnected",
818
+ "pending",
819
+ "configuration_changed",
820
+ "store_denied",
821
+ "invalid",
822
+ ]),
823
+ checkedAt: z.string(),
824
+ externallyRenewed: z.boolean(),
825
+ }),
826
+ target: (input: { connection: ConnectionRef }) => input.connection.$connection,
827
+ },
828
+ prepare: {
829
+ effect: "access",
830
+ input: z.object({
831
+ target: connectionTargetSchema,
832
+ requestId: z.string().min(1),
833
+ definition: z.string(),
834
+ authorization: z.string(),
835
+ }),
836
+ output: setupSchema,
837
+ target: (input: { target: ConnectionTarget }) =>
838
+ "connection" in input.target ? input.target.connection.$connection : input.target.rule,
839
+ },
840
+ configure: {
841
+ effect: "access",
842
+ input: z.object({
843
+ target: connectionTargetSchema,
844
+ requestId: z.string().min(1),
845
+ expectedRevision: z.string().nullable(),
846
+ definition: z.string(),
847
+ account: z.string().min(1),
848
+ scopes: z.array(z.string()),
849
+ }),
850
+ output: snapshotSchema,
851
+ target: (input: { target: ConnectionTarget }) =>
852
+ "connection" in input.target ? input.target.connection.$connection : input.target.rule,
853
+ },
854
+ activate: {
855
+ effect: "access",
856
+ input: z.object({ connection: connectionRefSchema, expectedRevision: z.string() }),
857
+ output: snapshotSchema,
858
+ target: (input: { connection: ConnectionRef }) => input.connection.$connection,
859
+ },
860
+ disconnect: {
861
+ effect: "access",
862
+ input: z.object({ connection: connectionRefSchema, expectedRevision: z.string() }),
863
+ output: z.object({ id: z.string(), revision: z.string(), status: z.literal("disconnected") }),
864
+ target: (input: { connection: ConnectionRef }) => input.connection.$connection,
865
+ },
866
+ bind: {
867
+ effect: "access",
868
+ input: z.object({
869
+ connection: connectionRefSchema,
870
+ account: z.string().min(1),
871
+ scopes: z.array(z.string()),
872
+ expectedRevision: z.string().nullable(),
873
+ }),
874
+ output: snapshotSchema,
875
+ target: (input: { connection: ConnectionRef }) => input.connection.$connection,
876
+ },
877
+ create: {
878
+ effect: "access",
879
+ input: z.object({ rule: z.string(), account: z.string().min(1), scopes: z.array(z.string()) }),
880
+ output: snapshotSchema,
881
+ target: (input: { rule: string }) => input.rule,
882
+ },
883
+ },
884
+ });
885
+ const actor = (call: CallContext) => call.principal ?? refuse("Connection mutation needs an authenticated principal");
886
+ export function connectionDriver(registry: ConnectionRegistry) {
887
+ return defineDriver(connectionOps, {
888
+ connection: {
889
+ test: (input, call) => registry.test(input.connection, actor(call)),
890
+ prepare: async (input, call) => {
891
+ const setup = await registry.setup(input.target, actor(call), input.requestId);
892
+ if (setup.definition !== input.definition) refuse("The connection changed; review its requirements again");
893
+ return { ...setup, requiredScopes: [...setup.requiredScopes] };
894
+ },
895
+ configure: (input, call) =>
896
+ registry.configure(
897
+ input.target,
898
+ input.requestId,
899
+ input.expectedRevision,
900
+ input.definition,
901
+ input.account,
902
+ input.scopes,
903
+ actor(call),
904
+ ),
905
+ activate: (input, call) => registry.activate(input.connection, input.expectedRevision, actor(call)),
906
+ disconnect: (input, call) => registry.disconnect(input.connection, input.expectedRevision, actor(call).id),
907
+ bind: (input, call) =>
908
+ registry.bind(input.connection, input.account, input.scopes, input.expectedRevision, actor(call).id),
909
+ create: (input, call) => registry.create(input.rule, input.account, input.scopes, actor(call)),
910
+ },
911
+ });
912
+ }