@sanoma-ai/workflows 0.9.0 → 0.10.0

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 (205) hide show
  1. package/README.md +169 -52
  2. package/dist/apply-steps.js +5 -2
  3. package/dist/apply-steps.js.map +1 -1
  4. package/dist/apply.d.ts +3 -0
  5. package/dist/apply.js +35 -21
  6. package/dist/apply.js.map +1 -1
  7. package/dist/approvals.d.ts +1 -0
  8. package/dist/approvals.js +6 -1
  9. package/dist/approvals.js.map +1 -1
  10. package/dist/apps.d.ts +7 -24
  11. package/dist/apps.js +51 -67
  12. package/dist/apps.js.map +1 -1
  13. package/dist/ast.d.ts +9 -7
  14. package/dist/ast.js +2 -0
  15. package/dist/ast.js.map +1 -1
  16. package/dist/authentication.d.ts +24 -0
  17. package/dist/authentication.js +68 -0
  18. package/dist/authentication.js.map +1 -0
  19. package/dist/call-workflow.d.ts +5 -0
  20. package/dist/call-workflow.js +4 -3
  21. package/dist/call-workflow.js.map +1 -1
  22. package/dist/call.d.ts +3 -2
  23. package/dist/call.js +34 -7
  24. package/dist/call.js.map +1 -1
  25. package/dist/cedar.js +14 -1
  26. package/dist/cedar.js.map +1 -1
  27. package/dist/change-steps.js +7 -5
  28. package/dist/change-steps.js.map +1 -1
  29. package/dist/change.d.ts +7 -0
  30. package/dist/change.js +7 -0
  31. package/dist/change.js.map +1 -1
  32. package/dist/client.d.ts +10 -6
  33. package/dist/client.js +96 -43
  34. package/dist/client.js.map +1 -1
  35. package/dist/collection.d.ts +7 -0
  36. package/dist/collection.js +5 -2
  37. package/dist/collection.js.map +1 -1
  38. package/dist/config.d.ts +14 -3
  39. package/dist/config.js +55 -14
  40. package/dist/config.js.map +1 -1
  41. package/dist/connection.d.ts +168 -0
  42. package/dist/connection.js +327 -0
  43. package/dist/connection.js.map +1 -0
  44. package/dist/credentials.d.ts +7 -53
  45. package/dist/credentials.js +84 -247
  46. package/dist/credentials.js.map +1 -1
  47. package/dist/cucumber.d.ts +4 -2
  48. package/dist/cucumber.js +8 -3
  49. package/dist/cucumber.js.map +1 -1
  50. package/dist/db.js +21 -2
  51. package/dist/db.js.map +1 -1
  52. package/dist/define.d.ts +9 -2
  53. package/dist/define.js.map +1 -1
  54. package/dist/definitions.d.ts +20 -0
  55. package/dist/definitions.js +16 -0
  56. package/dist/definitions.js.map +1 -0
  57. package/dist/deployment-key.d.ts +2 -0
  58. package/dist/deployment-key.js +22 -0
  59. package/dist/deployment-key.js.map +1 -0
  60. package/dist/describe.d.ts +9 -177
  61. package/dist/describe.js +71 -34
  62. package/dist/describe.js.map +1 -1
  63. package/dist/description.d.ts +532 -0
  64. package/dist/description.js +381 -0
  65. package/dist/description.js.map +1 -0
  66. package/dist/direct.js +3 -0
  67. package/dist/direct.js.map +1 -1
  68. package/dist/drift.d.ts +1 -1
  69. package/dist/drift.js +1 -1
  70. package/dist/drift.js.map +1 -1
  71. package/dist/env.d.ts +2 -0
  72. package/dist/env.js +2 -2
  73. package/dist/env.js.map +1 -1
  74. package/dist/index.d.ts +10 -2
  75. package/dist/index.js +10 -2
  76. package/dist/index.js.map +1 -1
  77. package/dist/ledger.d.ts +2 -0
  78. package/dist/ledger.js +1 -1
  79. package/dist/ledger.js.map +1 -1
  80. package/dist/lint.d.ts +0 -9
  81. package/dist/lint.js +1 -16
  82. package/dist/lint.js.map +1 -1
  83. package/dist/load.d.ts +74 -0
  84. package/dist/load.js +357 -0
  85. package/dist/load.js.map +1 -0
  86. package/dist/lockfile.d.ts +2 -0
  87. package/dist/lockfile.js +8 -3
  88. package/dist/lockfile.js.map +1 -1
  89. package/dist/op.d.ts +10 -1
  90. package/dist/op.js +1 -1
  91. package/dist/op.js.map +1 -1
  92. package/dist/outline.js +13 -4
  93. package/dist/outline.js.map +1 -1
  94. package/dist/paths.d.ts +18 -0
  95. package/dist/paths.js +21 -3
  96. package/dist/paths.js.map +1 -1
  97. package/dist/plugin.d.ts +0 -11
  98. package/dist/plugin.js +3 -18
  99. package/dist/plugin.js.map +1 -1
  100. package/dist/policy.d.ts +2 -0
  101. package/dist/policy.js.map +1 -1
  102. package/dist/resource.d.ts +27 -4
  103. package/dist/resource.js +49 -4
  104. package/dist/resource.js.map +1 -1
  105. package/dist/resources.d.ts +33 -76
  106. package/dist/resources.js +219 -227
  107. package/dist/resources.js.map +1 -1
  108. package/dist/run.d.ts +2 -0
  109. package/dist/run.js.map +1 -1
  110. package/dist/sandbox.d.ts +1 -1
  111. package/dist/sandbox.js +7 -3
  112. package/dist/sandbox.js.map +1 -1
  113. package/dist/scenario.d.ts +7 -0
  114. package/dist/scenario.js +33 -3
  115. package/dist/scenario.js.map +1 -1
  116. package/dist/scenarios.js +7 -1
  117. package/dist/scenarios.js.map +1 -1
  118. package/dist/schema.js +8 -0
  119. package/dist/schema.js.map +1 -1
  120. package/dist/secret-store-check.d.ts +11 -0
  121. package/dist/secret-store-check.js +76 -0
  122. package/dist/secret-store-check.js.map +1 -0
  123. package/dist/secret-store.d.ts +106 -0
  124. package/dist/secret-store.js +228 -0
  125. package/dist/secret-store.js.map +1 -0
  126. package/dist/shared.d.ts +17 -11
  127. package/dist/shared.js +34 -7
  128. package/dist/shared.js.map +1 -1
  129. package/dist/sites.d.ts +4 -93
  130. package/dist/sites.js +61 -84
  131. package/dist/sites.js.map +1 -1
  132. package/dist/source.d.ts +6 -0
  133. package/dist/source.js +13 -0
  134. package/dist/source.js.map +1 -1
  135. package/dist/steps.d.ts +3 -1
  136. package/dist/steps.js.map +1 -1
  137. package/dist/version.d.ts +2 -1
  138. package/dist/version.js +2 -1
  139. package/dist/version.js.map +1 -1
  140. package/dist/wakeup-driver.js +15 -6
  141. package/dist/wakeup-driver.js.map +1 -1
  142. package/dist/worker.js +12 -8
  143. package/dist/worker.js.map +1 -1
  144. package/dist/writer.d.ts +53 -14
  145. package/dist/writer.js +113 -43
  146. package/dist/writer.js.map +1 -1
  147. package/oxlint.json +0 -5
  148. package/package.json +6 -2
  149. package/src/apply-steps.ts +5 -2
  150. package/src/apply.ts +70 -29
  151. package/src/approvals.ts +7 -1
  152. package/src/apps.ts +54 -85
  153. package/src/ast.ts +6 -6
  154. package/src/authentication.ts +74 -0
  155. package/src/call-workflow.ts +5 -4
  156. package/src/call.ts +53 -9
  157. package/src/cedar.ts +14 -1
  158. package/src/change-steps.ts +7 -4
  159. package/src/change.ts +10 -0
  160. package/src/client.ts +108 -41
  161. package/src/collection.ts +10 -2
  162. package/src/config.ts +72 -13
  163. package/src/connection.ts +446 -0
  164. package/src/credentials.ts +94 -281
  165. package/src/cucumber.ts +16 -3
  166. package/src/db.ts +21 -2
  167. package/src/define.ts +7 -2
  168. package/src/definitions.ts +31 -0
  169. package/src/deployment-key.ts +23 -0
  170. package/src/describe.ts +102 -230
  171. package/src/description.ts +426 -0
  172. package/src/direct.ts +3 -0
  173. package/src/drift.ts +10 -2
  174. package/src/env.ts +4 -2
  175. package/src/index.ts +42 -1
  176. package/src/ledger.ts +3 -1
  177. package/src/lint.ts +1 -16
  178. package/src/load.ts +437 -0
  179. package/src/lockfile.ts +10 -3
  180. package/src/op.ts +10 -1
  181. package/src/outline.ts +18 -5
  182. package/src/paths.ts +24 -2
  183. package/src/plugin.ts +3 -24
  184. package/src/policy.ts +2 -0
  185. package/src/resource.ts +67 -6
  186. package/src/resources.ts +246 -301
  187. package/src/run.ts +2 -0
  188. package/src/sandbox.ts +11 -3
  189. package/src/scenario.ts +45 -3
  190. package/src/scenarios.ts +7 -1
  191. package/src/schema.ts +10 -0
  192. package/src/secret-store-check.ts +93 -0
  193. package/src/secret-store.ts +314 -0
  194. package/src/shared.ts +35 -10
  195. package/src/sites.ts +70 -180
  196. package/src/source.ts +14 -0
  197. package/src/steps.ts +3 -1
  198. package/src/version.ts +2 -1
  199. package/src/wakeup-driver.ts +22 -6
  200. package/src/worker.ts +12 -8
  201. package/src/writer.ts +145 -56
  202. package/dist/datafile.d.ts +0 -97
  203. package/dist/datafile.js +0 -479
  204. package/dist/datafile.js.map +0 -1
  205. package/src/datafile.ts +0 -601
@@ -1,296 +1,109 @@
1
- import { createCipheriv, createDecipheriv, randomBytes } from "node:crypto";
2
- import { setTimeout as sleep } from "node:timers/promises";
3
- import { Client } from "pg";
4
- import { credentialsOf } from "./env.ts";
5
- import { CREDENTIALS_TABLE as TABLE, type Db, prepareDatabase } from "./db.ts";
6
- import { info, warn } from "./log.ts";
7
- import type { Driver } from "./op.ts";
8
- import type { Secrets } from "./secret.ts";
9
- import { errorMessage } from "./shared.ts";
1
+ import { createCipheriv, createDecipheriv, randomBytes, randomUUID } from "node:crypto";
2
+ import { CREDENTIALS_TABLE as TABLE, type Db } from "./db.ts";
3
+ import {
4
+ SecretAccess,
5
+ SecretStoreError,
6
+ type SecretAddress,
7
+ type SecretConfiguration,
8
+ type SecretStore,
9
+ type SecretValue,
10
+ } from "./secret-store.ts";
11
+ import { deploymentKey } from "./deployment-key.ts";
10
12
 
11
- // Where the credentials set from the app live: one table in the config's database, beside DBOS's
12
- // own (made by `prepareDatabase` in db.ts). A value is read here only, by the worker to load it
13
- // into its environment or hand it to a driver (`storedSecrets`) and by the client to check it,
14
- // and leaves none of them. The write (`storeCredential`, `ensureCredential`) and the read
15
- // (`storedCredentials`) are the only places that touch `value`, which holds it encrypted
16
- // (`encrypt`) under `SANOMA_SECRETS_KEY`.
17
-
18
- /** Where a change is announced, with the variable's name as the payload. */
19
- const CHANNEL = "sanoma_credentials";
20
-
21
- /** The variable holding the key the stored values are encrypted with: 32 bytes, base64. */
22
13
  export const SECRETS_KEY = "SANOMA_SECRETS_KEY";
23
-
24
- /** What starts an encrypted value; a value without it is a plaintext one stored before encryption, read as it is. */
25
14
  const V1 = "v1:";
26
- const CIPHER = "aes-256-gcm";
27
- const TAG_BYTES = 16;
28
-
29
- /** The key from the environment, or an error naming the variable. */
30
- function secretsKey(): Buffer {
31
- const text = process.env[SECRETS_KEY];
32
- if (!text) {
33
- throw new Error(
34
- `${SECRETS_KEY} is not set: it encrypts the stored credentials; set it to 32 random bytes, base64 (\`openssl rand -base64 32\`)`,
35
- );
36
- }
37
- const key = Buffer.from(text, "base64");
38
- if (key.length !== 32) throw new Error(`${SECRETS_KEY} must be 32 bytes, base64; it is ${key.length} bytes`);
39
- return key;
40
- }
41
15
 
42
- /**
43
- * `name`'s value encrypted for the table: `v1:<iv, base64>:<ciphertext and tag, base64>`,
44
- * AES-256-GCM, with the name as associated data, so a value moved to another row does not decrypt.
45
- */
46
- export function encrypt(name: string, value: string): string {
47
- const iv = randomBytes(12);
48
- const cipher = createCipheriv(CIPHER, secretsKey(), iv).setAAD(Buffer.from(name));
16
+ /** AES-256-GCM authenticated to the complete namespace/path identity. No plaintext format. */
17
+ export function encrypt(identity: string, value: string): string {
18
+ const nonce = randomBytes(12);
19
+ const cipher = createCipheriv("aes-256-gcm", deploymentKey(SECRETS_KEY), nonce).setAAD(Buffer.from(identity));
49
20
  const sealed = Buffer.concat([cipher.update(value, "utf8"), cipher.final(), cipher.getAuthTag()]);
50
- return `${V1}${iv.toString("base64")}:${sealed.toString("base64")}`;
21
+ return `${V1}${nonce.toString("base64")}:${sealed.toString("base64")}`;
51
22
  }
52
23
 
53
- /** The value `name`'s row holds: decrypted, or a plaintext one as it is (it is encrypted on its next write). */
54
- export function decrypt(name: string, stored: string): string {
55
- if (!stored.startsWith(V1)) return stored;
56
- const key = secretsKey();
57
- const [iv = "", body = ""] = stored.slice(V1.length).split(":");
58
- const sealed = Buffer.from(body, "base64");
24
+ export function decrypt(identity: string, stored: string): string {
25
+ if (!stored.startsWith(V1)) throw new SecretStoreError("invalid_value");
26
+ const key = deploymentKey(SECRETS_KEY);
59
27
  try {
60
- const decipher = createDecipheriv(CIPHER, key, Buffer.from(iv, "base64")).setAAD(Buffer.from(name));
61
- decipher.setAuthTag(sealed.subarray(-TAG_BYTES));
62
- return Buffer.concat([decipher.update(sealed.subarray(0, -TAG_BYTES)), decipher.final()]).toString("utf8");
63
- } catch (err) {
64
- throw new Error(
65
- `the stored ${name} cannot be decrypted: ${SECRETS_KEY} is not the key it was stored with, or the row was not stored as ${name}`,
66
- { cause: err },
67
- );
28
+ const parts = stored.slice(V1.length).split(":");
29
+ if (parts.length !== 2) throw new Error("format");
30
+ const nonce = Buffer.from(parts[0]!, "base64");
31
+ const sealed = Buffer.from(parts[1]!, "base64");
32
+ if (nonce.length !== 12 || sealed.length < 16) throw new Error("format");
33
+ const decipher = createDecipheriv("aes-256-gcm", key, nonce).setAAD(Buffer.from(identity));
34
+ decipher.setAuthTag(sealed.subarray(-16));
35
+ return Buffer.concat([decipher.update(sealed.subarray(0, -16)), decipher.final()]).toString("utf8");
36
+ } catch {
37
+ throw new SecretStoreError("invalid_value");
68
38
  }
69
39
  }
70
40
 
71
- /** The stored rows of these names, values included: for loading into an environment or checking, never for showing. */
72
- export async function storedCredentials(
73
- db: Db,
74
- names: readonly string[],
75
- ): Promise<Map<string, { value: string; setBy: string; setAt: string }>> {
76
- const { rows } = await db.query<{ name: string; value: string; set_by: string; set_at: Date }>(
77
- `SELECT name, value, set_by, set_at FROM ${TABLE} WHERE name = ANY($1)`,
78
- [names],
79
- );
80
- return new Map(
81
- rows.map((r) => [r.name, { value: decrypt(r.name, r.value), setBy: r.set_by, setAt: r.set_at.toISOString() }]),
82
- );
83
- }
84
-
85
- /** Upserts the value and announces it, in one statement, so a worker never hears of a change it cannot read. */
86
- export async function storeCredential(
87
- db: Db,
88
- { name, value, setBy }: { name: string; value: string; setBy: string },
89
- ): Promise<void> {
90
- await db.query(
91
- `WITH stored AS (INSERT INTO ${TABLE} (name, value, set_by) VALUES ($1, $2, $3) ` +
92
- "ON CONFLICT (name) DO UPDATE SET value = EXCLUDED.value, set_by = EXCLUDED.set_by, set_at = now() " +
93
- `RETURNING name) SELECT pg_notify('${CHANNEL}', name) FROM stored`,
94
- [name, encrypt(name, value), setBy],
95
- );
96
- }
97
-
98
- /**
99
- * The stored value of `name`; when there is none, `make()`'s, stored first and announced. Of two
100
- * at once, the first stored wins, and both return it.
101
- */
102
- export async function ensureCredential(
103
- db: Db,
104
- { name, make, setBy }: { name: string; make: () => string; setBy: string },
105
- ): Promise<string> {
106
- const stored = (await storedCredentials(db, [name])).get(name);
107
- if (stored) return stored.value;
108
- await db.query(
109
- `WITH stored AS (INSERT INTO ${TABLE} (name, value, set_by) VALUES ($1, $2, $3) ON CONFLICT (name) DO NOTHING ` +
110
- `RETURNING name) SELECT pg_notify('${CHANNEL}', name) FROM stored`,
111
- [name, encrypt(name, make()), setBy],
112
- );
113
- return (await storedCredentials(db, [name])).get(name)!.value;
114
- }
115
-
116
- /**
117
- * The secrets store a live driver is given (`CallContext.secrets`): a variable the environment
118
- * sets wins, as it does for a driver's `env`; else the stored value. `ensure` stores what it
119
- * makes as `setBy`.
120
- */
121
- export function storedSecrets(db: () => Promise<Db>, setBy: string): Secrets {
41
+ type Row = { value: string; version: string; set_by: string; set_at: Date };
42
+ const identity = ({ namespace, path }: SecretAddress) => JSON.stringify([namespace, path]);
43
+ const decoded = (address: SecretAddress, row: Row): SecretValue => ({
44
+ value: decrypt(identity(address), row.value),
45
+ version: row.version,
46
+ updatedBy: row.set_by,
47
+ updatedAt: row.set_at.toISOString(),
48
+ });
49
+
50
+ /** One company's database connection supplies authority; namespace separates deployments within it. */
51
+ export function postgresSecretStore(db: () => Promise<Db>): SecretStore {
122
52
  return {
123
- get: async (name) => process.env[name] || (await storedCredentials(await db(), [name])).get(name)?.value,
124
- ensure: async (name, make) => process.env[name] || ensureCredential(await db(), { name, make, setBy }),
125
- };
126
- }
127
-
128
- /** Deletes the row, announcing it when there was one. */
129
- export async function deleteCredential(db: Db, name: string): Promise<void> {
130
- await db.query(
131
- `WITH gone AS (DELETE FROM ${TABLE} WHERE name = $1 RETURNING name) SELECT pg_notify('${CHANNEL}', name) FROM gone`,
132
- [name],
133
- );
134
- }
135
-
136
- /** Stops a worker's credentials listener. */
137
- export interface CredentialsWatch {
138
- close(): Promise<void>;
139
- }
140
-
141
- /** The longest wait between two attempts to reconnect the listener, and between two warnings that one failed. */
142
- const RETRY_MAX_MS = 30_000;
143
-
144
- /**
145
- * Loads the stored values of the declared variables the environment does not set into
146
- * `process.env`, then keeps them current: on each change announced, and on reconnecting, it
147
- * loads them again, so a value set replaces the one before and a value cleared is deleted. A
148
- * name the environment set when this started is never touched, and the names it did set are
149
- * deleted on `close`. Logs, per vendor, how many variables each load changed, never a value, and
150
- * warns of a reloaded value its schema refuses. A listener that drops reconnects, waiting longer
151
- * after each failure, up to 30 s, until it is closed. With no such variable, it connects to nothing.
152
- */
153
- export async function watchCredentials(
154
- databaseUrl: string,
155
- drivers: ReadonlyMap<string, Driver>,
156
- ): Promise<CredentialsWatch> {
157
- const vendors = new Map<string, string>();
158
- for (const [vendor, list] of credentialsOf(drivers, () => undefined)) {
159
- for (const { name } of list) if (!process.env[name] && !vendors.has(name)) vendors.set(name, vendor);
160
- }
161
- const names = [...vendors.keys()];
162
- if (!names.length) return { close: async () => undefined };
163
- /** The listener's connection, from when it connects until it drops or closes. */
164
- let db: Client | undefined;
165
- let closed = false;
166
- let reconnecting = false;
167
- // One load at a time, so close() can wait for it; the changes announced during one make one more.
168
- let loading: Promise<void> | undefined;
169
- let stale = false;
170
-
171
- async function load(first: boolean) {
172
- const conn = db;
173
- if (closed || !conn) return;
174
- const rows = await storedCredentials(conn, names);
175
- // Nothing touches the environment once closed: a worker or an app started after may own it.
176
- if (closed) return;
177
- const changed = names.filter((name) => rows.get(name)?.value !== process.env[name]);
178
- const counts = new Map<string, number>();
179
- for (const name of changed) {
180
- const value = rows.get(name)?.value;
181
- if (value === undefined) delete process.env[name];
182
- else process.env[name] = value;
183
- const vendor = vendors.get(name)!;
184
- counts.set(vendor, (counts.get(vendor) ?? 0) + 1);
185
- }
186
- const verb = first ? "loaded" : "reloaded";
187
- for (const [vendor, n] of counts) info(`credentials ${verb} for ${vendor} (${n} variable${n === 1 ? "" : "s"})`);
188
- // At start, startWorker warns of an invalid one, naming it.
189
- if (first) return;
190
- for (const list of credentialsOf(drivers, (name) =>
191
- changed.includes(name) ? process.env[name] : undefined,
192
- ).values()) {
193
- for (const c of list) {
194
- if (c.status === "invalid")
195
- warn(`the stored ${c.name} is invalid (${c.problem}): calls that read it will fail`);
196
- }
197
- }
198
- }
199
-
200
- function reload(first = false): Promise<void> {
201
- if (loading) {
202
- stale = true;
203
- return loading;
204
- }
205
- loading = (async () => {
206
- try {
207
- do {
208
- stale = false;
209
- await load(first);
210
- first = false;
211
- } while (stale);
212
- } finally {
213
- loading = undefined;
214
- }
215
- })();
216
- return loading;
217
- }
218
-
219
- async function open(first: boolean) {
220
- const conn = new Client({ connectionString: databaseUrl, keepAlive: true, connectionTimeoutMillis: 10_000 });
221
- // Before anything can fail: an error nobody listens for ends the process.
222
- conn.on("error", (err) => lost(conn, err));
223
- // Before LISTEN, so no change announced from then on is missed.
224
- conn.on("notification", () => {
225
- if (!closed && conn === db) {
226
- reload().catch((err: unknown) => warn(`could not reload the credentials: ${errorMessage(err)}`));
227
- }
228
- });
229
- try {
230
- if (first) await prepareDatabase(databaseUrl);
231
- await conn.connect();
232
- if (closed) {
233
- await conn.end();
234
- return;
235
- }
236
- db = conn;
237
- await conn.query(`LISTEN ${CHANNEL}`);
238
- await reload(first);
239
- } catch (err) {
240
- if (db === conn) db = undefined;
241
- await conn.end().catch(() => undefined);
242
- throw err;
243
- }
244
- }
245
-
246
- /** A connection that dropped: the one listening is replaced; one still connecting fails its own open. */
247
- function lost(conn: Client, err: unknown) {
248
- if (closed || conn !== db) return;
249
- db = undefined;
250
- void conn.end().catch(() => undefined);
251
- warn(`the credentials listener failed (${errorMessage(err)}); reconnecting`);
252
- void reconnect();
253
- }
254
-
255
- async function reconnect() {
256
- if (reconnecting) return;
257
- reconnecting = true;
258
- let wait = 1_000;
259
- let warnedAt = 0;
260
- try {
261
- for (;;) {
262
- await sleep(wait, undefined, { ref: false });
263
- if (closed) return;
264
- try {
265
- await open(false);
266
- return;
267
- } catch (err) {
268
- if (Date.now() - warnedAt >= RETRY_MAX_MS) {
269
- warnedAt = Date.now();
270
- warn(`could not reconnect the credentials listener (${errorMessage(err)}); trying again`);
271
- }
272
- wait = Math.min(wait * 2, RETRY_MAX_MS);
273
- }
274
- }
275
- } finally {
276
- reconnecting = false;
277
- }
278
- }
279
-
280
- try {
281
- await open(true);
282
- } catch (err) {
283
- closed = true;
284
- throw err;
285
- }
286
- return {
287
- async close() {
288
- closed = true;
289
- await loading?.catch(() => undefined);
290
- for (const name of names) delete process.env[name];
291
- const conn = db;
292
- db = undefined;
293
- await conn?.end();
53
+ id: "postgres",
54
+ capabilities: Object.freeze({
55
+ writable: true,
56
+ maxBytes: 65_536,
57
+ conditionalWrites: "atomic",
58
+ deletion: "destroy",
59
+ changeDetection: "read",
60
+ }),
61
+ async validate(namespace) {
62
+ if (!namespace) throw new SecretStoreError("invalid_configuration");
63
+ deploymentKey(SECRETS_KEY);
64
+ await (await db()).query(`SELECT namespace FROM ${TABLE} LIMIT 0`);
65
+ },
66
+ async read(address) {
67
+ const { rows } = await (
68
+ await db()
69
+ ).query<Row>(`SELECT value, version, set_by, set_at FROM ${TABLE} WHERE namespace = $1 AND name = $2`, [
70
+ address.namespace,
71
+ address.path,
72
+ ]);
73
+ return rows[0] && decoded(address, rows[0]);
74
+ },
75
+ async write(address, value, { expectedVersion, by }) {
76
+ if (Buffer.byteLength(value) > 65_536) throw new SecretStoreError("too_large");
77
+ const version = randomUUID();
78
+ const sealed = encrypt(identity(address), value);
79
+ const query =
80
+ expectedVersion === null
81
+ ? `INSERT INTO ${TABLE} (namespace,name,value,version,set_by) VALUES ($1,$2,$3,$4,$5) ON CONFLICT (namespace,name) DO NOTHING RETURNING value,version,set_by,set_at`
82
+ : `UPDATE ${TABLE} SET value=$3,version=$4,set_by=$5,set_at=now() WHERE namespace=$1 AND name=$2 AND version=$6 RETURNING value,version,set_by,set_at`;
83
+ const params = [
84
+ address.namespace,
85
+ address.path,
86
+ sealed,
87
+ version,
88
+ by,
89
+ ...(expectedVersion === null ? [] : [expectedVersion]),
90
+ ];
91
+ const { rows } = await (await db()).query<Row>(query, params);
92
+ if (!rows[0]) throw new SecretStoreError("conflict");
93
+ return decoded(address, rows[0]);
94
+ },
95
+ async delete(address, { expectedVersion }) {
96
+ const { rowCount } = await (
97
+ await db()
98
+ ).query(`DELETE FROM ${TABLE} WHERE namespace=$1 AND name=$2 AND version=$3`, [
99
+ address.namespace,
100
+ address.path,
101
+ expectedVersion,
102
+ ]);
103
+ if (!rowCount) throw new SecretStoreError("conflict");
294
104
  },
295
105
  };
296
106
  }
107
+
108
+ export const configuredSecrets = (config: SecretConfiguration, db: () => Promise<Db>): SecretAccess =>
109
+ new SecretAccess(config, postgresSecretStore(db));
package/src/cucumber.ts CHANGED
@@ -173,7 +173,8 @@ const literal = (path: string) => path.replaceAll(/[*?[\]()+@]/g, "[$&]").replac
173
173
  * examples row at that line. `makeWorld` makes each scenario's World, given the report so far
174
174
  * (every file and pickle, read before the first scenario starts). A dry run matches the steps
175
175
  * and runs none. A step's error that is a bug in code (`isBug`) is rethrown once the run is
176
- * over, rather than reported as the step's failure.
176
+ * over, rather than reported as the step's failure. `timeoutMs` is how long a step may take
177
+ * (Cucumber's 5 s by default).
177
178
  */
178
179
  export async function runFeatures(
179
180
  library: ISupportCodeLibrary,
@@ -184,7 +185,15 @@ export async function runFeatures(
184
185
  line,
185
186
  dryRun = false,
186
187
  isBug,
187
- }: { cwd: string; files: string[]; line?: number; dryRun?: boolean; isBug: (err: unknown) => boolean },
188
+ timeoutMs,
189
+ }: {
190
+ cwd: string;
191
+ files: string[];
192
+ line?: number;
193
+ dryRun?: boolean;
194
+ isBug: (err: unknown) => boolean;
195
+ timeoutMs?: number;
196
+ },
188
197
  ): Promise<Report> {
189
198
  const report: Report = { query: new Query(), texts: new Map(), parseErrors: [] };
190
199
  let bug: unknown;
@@ -200,7 +209,11 @@ export async function runFeatures(
200
209
  }
201
210
  const configuration: IRunOptions = {
202
211
  sources: { defaultDialect: "en", paths: files.map(literal), names: [], tagExpression: "", order: "defined" },
203
- support: { ...library, World } as ISupportCodeLibrary,
212
+ support: {
213
+ ...library,
214
+ World,
215
+ ...(timeoutMs !== undefined && { defaultTimeout: timeoutMs }),
216
+ } as ISupportCodeLibrary,
204
217
  runtime: {
205
218
  dryRun,
206
219
  failFast: false,
package/src/db.ts CHANGED
@@ -31,10 +31,29 @@ export const CHAT_MESSAGES_TABLE = "sanoma_chat_messages";
31
31
 
32
32
  /** The runtime's tables, each with the word the messages name it by. */
33
33
  const TABLES: readonly [what: string, ddl: string][] = [
34
+ [
35
+ "connections",
36
+ `CREATE TABLE IF NOT EXISTS sanoma_connections (
37
+ id text PRIMARY KEY, vendor text NOT NULL, method text NOT NULL, owner text, rule text,
38
+ account text NOT NULL, scopes jsonb NOT NULL, revision text NOT NULL, definition text NOT NULL,
39
+ credential text, status text NOT NULL DEFAULT 'connected', updated_by text NOT NULL,
40
+ updated_at timestamptz NOT NULL DEFAULT now())`,
41
+ ],
34
42
  [
35
43
  "credentials",
36
- `CREATE TABLE IF NOT EXISTS ${CREDENTIALS_TABLE} (name text PRIMARY KEY, value text NOT NULL, ` +
37
- "set_by text NOT NULL, set_at timestamptz NOT NULL DEFAULT now())",
44
+ // A table from before 0.10.0 (one row per name, each value sealed to its name alone) holds
45
+ // nothing 0.10.0 can read: it goes, and its credentials are set again.
46
+ // One table for the look and the drop: the one the name resolves to.
47
+ `DO $$ BEGIN
48
+ IF to_regclass('${CREDENTIALS_TABLE}') IS NOT NULL AND NOT EXISTS (
49
+ SELECT FROM pg_attribute
50
+ WHERE attrelid = to_regclass('${CREDENTIALS_TABLE}') AND attname = 'namespace' AND NOT attisdropped
51
+ ) THEN
52
+ DROP TABLE ${CREDENTIALS_TABLE};
53
+ END IF;
54
+ END $$; ` +
55
+ `CREATE TABLE IF NOT EXISTS ${CREDENTIALS_TABLE} (namespace text NOT NULL, name text NOT NULL, value text NOT NULL, ` +
56
+ "version text NOT NULL, set_by text NOT NULL, set_at timestamptz NOT NULL DEFAULT now(), PRIMARY KEY(namespace, name))",
38
57
  ],
39
58
  [
40
59
  "ledger",
package/src/define.ts CHANGED
@@ -1,3 +1,5 @@
1
+ import type { ConnectionRef } from "./connection.ts";
2
+ import type { WorkflowEntry } from "./description.ts";
1
3
  import { fileURLToPath } from "node:url";
2
4
  import { getCallSites } from "node:util";
3
5
  import { z } from "zod";
@@ -24,7 +26,8 @@ export const Principal: z.ZodType<Principal> = z.object({
24
26
  onBehalfOf: z.string().regex(/\S/, "onBehalfOf must not be blank").optional(),
25
27
  });
26
28
 
27
- export type Builtin = "approval" | "sleep" | "all";
29
+ /** A built-in a workflow may call, as its description lists them. */
30
+ export type Builtin = WorkflowEntry["builtins"][number];
28
31
  export type Use = Op | Builtin;
29
32
 
30
33
  /** Who may decide an approval: one person, by `Principal.id`, or anyone in a group, by `Principal.groups`. */
@@ -77,6 +80,8 @@ export const ApprovalRequestSchema = z.object(
77
80
 
78
81
  /** One approval in a run, as the run sees it. Published as the run's "approvals" event. */
79
82
  export interface ApprovalState extends Omit<ApprovalRequest, "covers"> {
83
+ /** Connection binding revision approved by this policy hold. */
84
+ connection?: string;
80
85
  id: string;
81
86
  title: string;
82
87
  /** Who asked: the workflow (`ctx.approval`), or the policy holding an operation call. */
@@ -179,7 +184,7 @@ type VendorCtx<O extends Op, V> = {
179
184
  O,
180
185
  { vendor: V; resource: R; name: N }
181
186
  > extends Op<any, any, any, infer I, infer Out>
182
- ? (input: I, options?: StepOptions) => Promise<Out>
187
+ ? (input: I, options?: StepOptions & { connection?: ConnectionRef<Extract<V, string>> }) => Promise<Out>
183
188
  : never;
184
189
  };
185
190
  };
@@ -0,0 +1,31 @@
1
+ // What an app's `app.ts` and a site's `site.ts` declare themselves with. Dependency-free: the
2
+ // loader (`load.ts`) serves these to those files as `sanoma` and `sanoma/site`, the browser-safe
3
+ // entry (`shared.ts`) re-exports `defineSite`, and the app's `sanoma/site` calls it.
4
+
5
+ /** What `app.ts` declares: the source repository's URL, when the app was taken from one. */
6
+ export interface AppDefinition {
7
+ source?: string;
8
+ }
9
+
10
+ /**
11
+ * Declares an app in its folder's `app.ts`, its default export: `defineApp({ source:
12
+ * "https://github.com/acme/crm" })`, the repository it was taken from; `defineApp({})` for an app
13
+ * the company made itself.
14
+ */
15
+ export function defineApp(definition: AppDefinition): AppDefinition {
16
+ return Object.freeze({ ...definition });
17
+ }
18
+
19
+ /** What a site's `site.ts` declares, as its default export; the app's `sanoma/site` types `icon` as a Lucide icon's name. */
20
+ export interface SiteDefinition {
21
+ title?: string;
22
+ icon?: string;
23
+ public?: boolean;
24
+ login?: string;
25
+ locales?: readonly [string, ...string[]];
26
+ }
27
+
28
+ /** Declares a site in its folder's `site.ts`, its default export: `defineSite({ title: "Help desk" })`. */
29
+ export function defineSite<S extends SiteDefinition>(site: S): Readonly<S> {
30
+ return Object.freeze({ ...site });
31
+ }
@@ -0,0 +1,23 @@
1
+ import { readFileSync } from "node:fs";
2
+
3
+ /** Bootstrap only: never resolves through the secret store that the key unlocks. */
4
+ export function deploymentKey(
5
+ name: "SANOMA_SECRETS_KEY" | "SANOMA_SIGNING_KEY",
6
+ env: NodeJS.ProcessEnv = process.env,
7
+ ): Buffer {
8
+ const value = env[name];
9
+ const file = env[`${name}_FILE`];
10
+ if (value && file) throw new Error(`Set only one of ${name} and ${name}_FILE`);
11
+ let encoded = value;
12
+ if (file) {
13
+ try {
14
+ encoded = readFileSync(file, "utf8").trim();
15
+ } catch {
16
+ throw new Error(`${name}_FILE could not be read`);
17
+ }
18
+ }
19
+ if (!encoded || !/^[A-Za-z0-9+/]{43}=$/.test(encoded) || Buffer.from(encoded, "base64").length !== 32) {
20
+ throw new Error(`${name} must be 32 random bytes in base64; supply ${name} or ${name}_FILE`);
21
+ }
22
+ return Buffer.from(encoded, "base64");
23
+ }