@sanoma-ai/workflows 0.10.2 → 0.10.3

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 (118) hide show
  1. package/README.md +43 -11
  2. package/dist/apply.js +1 -1
  3. package/dist/apply.js.map +1 -1
  4. package/dist/call.d.ts +5 -2
  5. package/dist/call.js +65 -20
  6. package/dist/call.js.map +1 -1
  7. package/dist/change.d.ts +5 -6
  8. package/dist/change.js +6 -9
  9. package/dist/change.js.map +1 -1
  10. package/dist/client.d.ts +18 -0
  11. package/dist/client.js +35 -3
  12. package/dist/client.js.map +1 -1
  13. package/dist/config.d.ts +42 -4
  14. package/dist/config.js +71 -10
  15. package/dist/config.js.map +1 -1
  16. package/dist/db.d.ts +2 -0
  17. package/dist/db.js +7 -0
  18. package/dist/db.js.map +1 -1
  19. package/dist/deadlines.d.ts +26 -13
  20. package/dist/deadlines.js +50 -11
  21. package/dist/deadlines.js.map +1 -1
  22. package/dist/define.d.ts +22 -0
  23. package/dist/define.js +2 -0
  24. package/dist/define.js.map +1 -1
  25. package/dist/deployment-key.d.ts +20 -1
  26. package/dist/deployment-key.js +28 -3
  27. package/dist/deployment-key.js.map +1 -1
  28. package/dist/describe.js +28 -1
  29. package/dist/describe.js.map +1 -1
  30. package/dist/description.d.ts +3 -0
  31. package/dist/description.js +2 -0
  32. package/dist/description.js.map +1 -1
  33. package/dist/host.d.ts +13 -4
  34. package/dist/host.js +14 -5
  35. package/dist/host.js.map +1 -1
  36. package/dist/index.d.ts +10 -6
  37. package/dist/index.js +8 -5
  38. package/dist/index.js.map +1 -1
  39. package/dist/ledger.d.ts +30 -1
  40. package/dist/ledger.js +31 -0
  41. package/dist/ledger.js.map +1 -1
  42. package/dist/login-code.d.ts +17 -0
  43. package/dist/login-code.js +32 -0
  44. package/dist/login-code.js.map +1 -0
  45. package/dist/op.d.ts +78 -10
  46. package/dist/op.js +20 -0
  47. package/dist/op.js.map +1 -1
  48. package/dist/outline.js +3 -3
  49. package/dist/outline.js.map +1 -1
  50. package/dist/resource.d.ts +6 -4
  51. package/dist/resource.js +8 -5
  52. package/dist/resource.js.map +1 -1
  53. package/dist/resources.d.ts +4 -2
  54. package/dist/resources.js +15 -6
  55. package/dist/resources.js.map +1 -1
  56. package/dist/run.d.ts +3 -0
  57. package/dist/run.js.map +1 -1
  58. package/dist/runtime-ops.d.ts +123 -0
  59. package/dist/runtime-ops.js +222 -0
  60. package/dist/runtime-ops.js.map +1 -0
  61. package/dist/seal.d.ts +27 -0
  62. package/dist/seal.js +76 -0
  63. package/dist/seal.js.map +1 -0
  64. package/dist/secret-store.d.ts +6 -4
  65. package/dist/secret-store.js +11 -6
  66. package/dist/secret-store.js.map +1 -1
  67. package/dist/secret.d.ts +7 -0
  68. package/dist/secret.js +13 -1
  69. package/dist/secret.js.map +1 -1
  70. package/dist/shared.d.ts +15 -4
  71. package/dist/shared.js +27 -7
  72. package/dist/shared.js.map +1 -1
  73. package/dist/ssh-key.d.ts +11 -0
  74. package/dist/ssh-key.js +44 -0
  75. package/dist/ssh-key.js.map +1 -0
  76. package/dist/tokens.d.ts +35 -0
  77. package/dist/tokens.js +71 -0
  78. package/dist/tokens.js.map +1 -0
  79. package/dist/wakeup-service.js +2 -7
  80. package/dist/wakeup-service.js.map +1 -1
  81. package/dist/wakeup.d.ts +18 -0
  82. package/dist/wakeup.js +15 -0
  83. package/dist/wakeup.js.map +1 -1
  84. package/dist/worker.d.ts +2 -2
  85. package/dist/worker.js +17 -9
  86. package/dist/worker.js.map +1 -1
  87. package/oxlint.json +1 -1
  88. package/package.json +1 -1
  89. package/src/apply.ts +1 -1
  90. package/src/call.ts +88 -18
  91. package/src/change.ts +9 -20
  92. package/src/client.ts +48 -7
  93. package/src/config.ts +111 -17
  94. package/src/db.ts +8 -1
  95. package/src/deadlines.ts +66 -20
  96. package/src/define.ts +25 -0
  97. package/src/deployment-key.ts +34 -8
  98. package/src/describe.ts +39 -2
  99. package/src/description.ts +2 -0
  100. package/src/host.ts +22 -6
  101. package/src/index.ts +18 -1
  102. package/src/ledger.ts +52 -1
  103. package/src/login-code.ts +52 -0
  104. package/src/op.ts +84 -11
  105. package/src/outline.ts +3 -3
  106. package/src/resource.ts +8 -5
  107. package/src/resources.ts +13 -4
  108. package/src/run.ts +3 -0
  109. package/src/runtime-ops.ts +234 -0
  110. package/src/seal.ts +95 -0
  111. package/src/secret-store.ts +12 -9
  112. package/src/secret.ts +16 -1
  113. package/src/shared.ts +31 -7
  114. package/src/ssh-key.ts +48 -0
  115. package/src/tokens.ts +100 -0
  116. package/src/wakeup-service.ts +2 -8
  117. package/src/wakeup.ts +21 -0
  118. package/src/worker.ts +29 -11
package/src/config.ts CHANGED
@@ -53,14 +53,25 @@ import {
53
53
  import { type CedarPolicySource, policyAt } from "./cedar.ts";
54
54
  import type { Policy } from "./policy.ts";
55
55
  import { type Resource, resourceTypesOf, withoutWriteOnly } from "./resource.ts";
56
- import { APPLY_WORKFLOW, BUILT_IN_WORKFLOWS, CALL_WORKFLOW, CHANGE_WORKFLOW, DATA_VENDOR } from "./shared.ts";
56
+ import { CODE_MAIL, loginCodeWorkflow } from "./login-code.ts";
57
+ import {
58
+ APPLY_WORKFLOW,
59
+ BUILT_IN_WORKFLOWS,
60
+ CALL_WORKFLOW,
61
+ CHANGE_WORKFLOW,
62
+ DATA_VENDOR,
63
+ LOGIN_CODE_WORKFLOW,
64
+ } from "./shared.ts";
57
65
  import { fakeSourceDriver, type RemoteHalf, SOURCE_RESOLVE, sourceDriver, sourceOps } from "./source.ts";
58
66
  import { appsListDriver, appsListOps } from "./apps-list.ts";
67
+ import { runtimeDriver, sandboxRuntimeDriver, sanoma } from "./runtime-ops.ts";
68
+ import { tokenStore } from "./tokens.ts";
59
69
  import type { Steps } from "./steps.ts";
60
70
  import { checkSchedule } from "./schedules.ts";
61
71
  import { changeCodeOf, computeVersion } from "./version.ts";
62
- import type { DeclaredResource } from "./resources.ts";
63
- import { checkWakeupOps, type DeclaredWakeup } from "./wakeup.ts";
72
+ import type { DeclaredResource, ResourceProblem } from "./resources.ts";
73
+ import { checkWakeupOps, type DeclaredWakeup, type EnvWakeup, HOST_URL } from "./wakeup.ts";
74
+ import { instanceUrl, WAKEUP_TOKEN } from "./wakeup-service.ts";
64
75
  import { sanomaWakeupDriver, wakeupSteps } from "./wakeup-driver.ts";
65
76
  import { wakeupOps } from "./wakeup-type.ts";
66
77
  import { checkDatabaseOps } from "./database.ts";
@@ -131,6 +142,13 @@ export interface SanomaConfig {
131
142
  * that sets it and declares a wakeup of its own.
132
143
  */
133
144
  wakeup?: true;
145
+ /**
146
+ * How the staff and visitor logins send a sign-in code: `sender`, an operation of a connector in
147
+ * `connectors` with the effect `send` that takes `{ to, subject, text }`, such as
148
+ * `resend.emails.send`. With it, the runtime registers the built-in `login-code` workflow,
149
+ * which the runtime's agent `login` runs; without it, nobody signs in by code.
150
+ */
151
+ login?: { sender: Op };
134
152
  }
135
153
 
136
154
  /** A config, checked, with everything a worker, client or app derives from it. */
@@ -150,9 +168,12 @@ export interface ResolvedConfig {
150
168
  changeCode: string;
151
169
  /** The DBOS queue runs are started on: `sanoma:<appName>`. */
152
170
  queueName: string;
171
+ /** The config's `login`, checked (`checkSender`); the built-in `login-code` workflow sends through its `sender`. */
172
+ login?: { sender: Op };
153
173
  /**
154
174
  * The operations the connectors declare, by id, the built-in `sanoma.change.*` (`changeOps`, in
155
- * every config), `sanoma.source.resolve` and `sanoma.wakeup`'s when one declares a host type,
175
+ * every config) and the runtime's own a workflow may use (`sanoma`, runtime-ops.ts, in every
176
+ * config), `sanoma.source.resolve` and `sanoma.wakeup`'s when one declares a host type,
156
177
  * and the collections' (`data.<name>.<op>`).
157
178
  */
158
179
  ops: Map<string, Op>;
@@ -177,6 +198,11 @@ export interface ResolvedConfig {
177
198
  * declares a host type.
178
199
  */
179
200
  hosts(): Promise<string[]>;
201
+ /**
202
+ * The objects the data files under `root` declare, read at each call: what a workflow's change
203
+ * operation may not aim at, since only apply changes a declared object.
204
+ */
205
+ declaredObjects(): Promise<DeclaredObjects>;
180
206
  /**
181
207
  * `root`, as a `file:` URL, when `scenarios/` or an app's `apps/<app>/scenarios/` in it is a
182
208
  * directory: the feature files under those, each named by its path from the root.
@@ -310,12 +336,14 @@ export function resolveConfig(config: SanomaConfig): ResolvedConfig {
310
336
  const declared = [...collections.values()];
311
337
  const dataStore = declared.length ? lazyPool(databaseUrl, "data") : undefined;
312
338
  // Built-in, in every config: a change's operations, which the template's policy names
313
- // (`sanoma.change.merge`), and the listing of apps a page may call (`sanoma.apps.list`).
339
+ // (`sanoma.change.merge`), the listing of apps a page may call (`sanoma.apps.list`), and what a
340
+ // workflow asks the runtime to do for it (`sanoma`, runtime-ops.ts).
314
341
  const ops = indexConnectors([
315
342
  ...running,
316
343
  changeOps,
317
344
  connectionOps,
318
345
  appsListOps,
346
+ sanoma,
319
347
  ...(hostTyped ? [sourceOps] : []),
320
348
  ...(dataStore ? [collectionsConnector(declared)] : []),
321
349
  ]);
@@ -329,6 +357,7 @@ export function resolveConfig(config: SanomaConfig): ResolvedConfig {
329
357
  changeDriver(remotes),
330
358
  connectionDriver(connections),
331
359
  appsListDriver,
360
+ runtimeDriver({ tokens: tokenStore(() => connectionPool.db()) }),
332
361
  ...(hostTyped ? [sourceDriver] : []),
333
362
  ...(dataStore ? [collectionsDriver(declared, dataStore)] : []),
334
363
  ],
@@ -342,7 +371,7 @@ export function resolveConfig(config: SanomaConfig): ResolvedConfig {
342
371
  if (BUILT_IN_WORKFLOWS.has(wf.name)) {
343
372
  throw new Error(`A workflow is named "${wf.name}", the name of a built-in workflow; name it otherwise`);
344
373
  }
345
- checkUses(wf, ops, drivers, types);
374
+ checkUses(wf, ops, drivers);
346
375
  checkSchedule(wf);
347
376
  const other = names.get(wf.name);
348
377
  if (other && other !== wf) {
@@ -368,9 +397,13 @@ export function resolveConfig(config: SanomaConfig): ResolvedConfig {
368
397
  const hosts = async () =>
369
398
  (await read()).resources.filter((r) => types.get(`${r.vendor}.${r.type}`)?.host).map((r) => r.id);
370
399
  names.set(CHANGE_WORKFLOW, changeWorkflow(changeOps, changeSteps({ remotes, hosts })));
400
+ const declaredObjects = () => readDeclaredObjects(root, connectors, declarable);
371
401
  // Built-in: a direct call the policy holds for an approval, made a run, when any operation may be called directly.
372
402
  const call = callWorkflow(ops, drivers, types);
373
403
  if (call.uses.length) names.set(CALL_WORKFLOW, call);
404
+ // Built-in: sending a sign-in code, when the config names how.
405
+ const login = config.login && { sender: checkSender(config.login, ops, drivers) };
406
+ if (login) names.set(LOGIN_CODE_WORKFLOW, loginCodeWorkflow(login.sender, appName));
374
407
  const { policy, policies, problems: policyProblems } = policyAt(root, { ops, workflows: names, collections });
375
408
  return {
376
409
  secrets: config.secrets ?? {},
@@ -382,6 +415,7 @@ export function resolveConfig(config: SanomaConfig): ResolvedConfig {
382
415
  version: computeVersion({ appName, workflows: [...names.values()] }),
383
416
  changeCode: changeCodeOf(names.get(CHANGE_WORKFLOW)!),
384
417
  queueName: `sanoma:${appName}`,
418
+ ...(login && { login }),
385
419
  ops,
386
420
  drivers,
387
421
  driversByVendor,
@@ -390,6 +424,7 @@ export function resolveConfig(config: SanomaConfig): ResolvedConfig {
390
424
  models: makersOf(config.connectors, "model"),
391
425
  remotes,
392
426
  hosts,
427
+ declaredObjects,
393
428
  ...(scenarios && { scenarios }),
394
429
  types,
395
430
  steps: [...new Set([...running.flatMap((c) => setupOf(c).steps ?? []), ...(config.steps ?? [])])],
@@ -404,6 +439,26 @@ export function resolveConfig(config: SanomaConfig): ResolvedConfig {
404
439
  };
405
440
  }
406
441
 
442
+ /**
443
+ * The config's `login.sender`, as the config's operations have it: refused unless it is an
444
+ * operation of a connector in `connectors`, with the effect `send`, a driver, and an input that
445
+ * takes `{ to, subject, text }`.
446
+ */
447
+ function checkSender(login: unknown, ops: ReadonlyMap<string, Op>, drivers: ReadonlyMap<string, unknown>): Op {
448
+ const sender: unknown = (login as { sender?: unknown } | null)?.sender;
449
+ const fix = "name a connector's send operation, such as `login: { sender: resend.emails.send }`";
450
+ if (!isOp(sender)) throw new Error(`The config's \`login.sender\` is not an operation: ${fix}`);
451
+ const op = ops.get(sender.id);
452
+ if (!op) throw new Error(`The config's \`login.sender\`, ${sender.id}, is of no connector in \`connectors\`: add it`);
453
+ if (op.effect !== "send")
454
+ throw new Error(`The config's \`login.sender\`, ${op.id}, does not send (its effect is ${op.effect}): ${fix}`);
455
+ if (!drivers.has(op.id))
456
+ throw new Error(`The config's \`login.sender\`, ${op.id}, has no driver: the connector package must attach one`);
457
+ if (!op.input.safeParse(CODE_MAIL).success)
458
+ throw new Error(`The config's \`login.sender\`, ${op.id}, does not take an email as { to, subject, text }: ${fix}`);
459
+ return op;
460
+ }
461
+
407
462
  /**
408
463
  * The config's collections by name, checked: each one `collection()` made, no two with one name,
409
464
  * and no connector of their vendor, `DATA_VENDOR`.
@@ -431,11 +486,13 @@ function collectionsOf(config: SanomaConfig): Map<string, Collection> {
431
486
  /**
432
487
  * The built-in drivers a sandbox run calls beside its fakes (`seedSandbox`), for the built-in
433
488
  * operations among `ops` that no fake implements: `sanoma.apps.list`'s own, which needs no
434
- * credentials and changes nothing (GitHub's public search), and `sanoma.source.resolve`'s fake
435
- * (`fakeSourceDriver`), for a config with a host type.
489
+ * credentials and changes nothing (GitHub's public search), the runtime's own operations over the
490
+ * run's secrets and tokens of its own (`sandboxRuntimeDriver`, made for each run), and
491
+ * `sanoma.source.resolve`'s fake (`fakeSourceDriver`), for a config with a host type.
436
492
  */
437
493
  export const sandboxDrivers = (ops: ReadonlyMap<string, unknown>): Driver[] => [
438
494
  appsListDriver,
495
+ sandboxRuntimeDriver(),
439
496
  ...(ops.has(SOURCE_RESOLVE) ? [fakeSourceDriver] : []),
440
497
  ];
441
498
 
@@ -545,6 +602,47 @@ export async function declaredWakeup(config: SanomaConfig): Promise<DeclaredWake
545
602
  };
546
603
  }
547
604
 
605
+ /**
606
+ * The wakeup `env` names (`EnvWakeup`): its host's URL, `SANOMA_HOST_URL`, as the wakeup service
607
+ * keeps one (`instanceUrl`), and its token, `SANOMA_WAKEUP_TOKEN`, when both are set and the URL is
608
+ * one; undefined otherwise. A host Sanoma Cloud made gives both to an instance that declares no
609
+ * wakeup of its own.
610
+ */
611
+ export function envWakeup(env: NodeJS.ProcessEnv): EnvWakeup | undefined {
612
+ const host = env[HOST_URL]?.trim();
613
+ const token = env[WAKEUP_TOKEN]?.trim();
614
+ const checked = host ? instanceUrl(host) : undefined;
615
+ return checked && "url" in checked && token ? { url: checked.url, token } : undefined;
616
+ }
617
+
618
+ /**
619
+ * The objects a company's data files declare, which only apply changes (`refuseDeclared` in
620
+ * `call.ts`), by `<vendor>.<type> <id or name>` to their key: each binding in the lockfile, an
621
+ * orphan's too, by its id, and each declaration by its identity (what its type's `find` made);
622
+ * and the files' problems, while which the declared objects are not known.
623
+ */
624
+ export interface DeclaredObjects {
625
+ keys: ReadonlyMap<string, string>;
626
+ problems: readonly ResourceProblem[];
627
+ }
628
+
629
+ /** The objects the data files under `root` and its lockfile declare (`DeclaredObjects`): none without a root. */
630
+ async function readDeclaredObjects(
631
+ root: string | undefined,
632
+ connectors: readonly Connector<any, any>[],
633
+ declarable: ReadonlyMap<string, Resource>,
634
+ ): Promise<DeclaredObjects> {
635
+ if (root === undefined) return { keys: new Map(), problems: [] };
636
+ // Loaded when a call asks, not with the worker.
637
+ const { loadDataFiles } = await import("./resources.ts");
638
+ const { resources, bindings, problems } = loadDataFiles(root, connectors, declarable);
639
+ const named = resources.flatMap((r) =>
640
+ r.identity === undefined ? [] : [[`${r.vendor}.${r.type} ${r.identity}`, r.id] as const],
641
+ );
642
+ const bound = Object.entries(bindings).map(([key, { type, id }]) => [`${type} ${id}`, key] as const);
643
+ return { keys: new Map([...named, ...bound]), problems };
644
+ }
645
+
548
646
  /**
549
647
  * The data files under `root` and the lockfile beside them, in one read, as a drift or apply run
550
648
  * records them: each resource with its binding, without its write-only values (a secret marker
@@ -693,19 +791,15 @@ function guarded(vendor: string, env: DriverEnv, fn: DriverFn): DriverFn {
693
791
  * Every operation a workflow uses must be one the config's connectors declare, with a driver.
694
792
  * The workflow normally imports the same connector object; a copy is accepted only if it
695
793
  * declares the same effect and retry setting, and the worker's declaration is used either way.
696
- * None may use an operation a built-in workflow alone calls (`reservedFor`): a declared resource's
697
- * change, which only apply makes, or a change's step, which only the change workflow takes.
794
+ * None may use an operation a built-in workflow alone calls (`reservedFor`): a change's step, which
795
+ * only the change workflow takes. A resource type's change operations are allowed: the call
796
+ * refuses one aimed at a declared object (`DeclaredObjects`), which only apply changes.
698
797
  */
699
- function checkUses(
700
- wf: WorkflowDefinition<any, any>,
701
- ops: Map<string, Op>,
702
- impls: Map<string, unknown>,
703
- types: ReadonlyMap<string, Resource>,
704
- ) {
798
+ function checkUses(wf: WorkflowDefinition<any, any>, ops: Map<string, Op>, impls: Map<string, unknown>) {
705
799
  const problems: string[] = [];
706
800
  for (const op of (wf.uses as readonly Use[]).filter(isOp)) {
707
801
  const known = ops.get(op.id);
708
- const reserved = known && reservedFor(known, types);
802
+ const reserved = known && reservedFor(known);
709
803
  if (!known) problems.push(`${op.id} is not declared by any connector in \`connectors\``);
710
804
  else if (reserved) {
711
805
  problems.push(`${op.id} ${reserved.does}, which only ${reserved.workflow} does: ${reserved.instead} instead`);
package/src/db.ts CHANGED
@@ -5,7 +5,7 @@ import { warn } from "./log.ts";
5
5
  import { errorMessage } from "./shared.ts";
6
6
 
7
7
  // The runtime's own tables live in the config's database, beside DBOS's: the credentials, the
8
- // ledger, the collections' records, the wakeup's row and the operator agent's chats. What they
8
+ // ledger, the collections' records, the wakeup's row, the operator agent's chats and the api tokens. What they
9
9
  // share is here: the one preparation of a database, a pool that opens once it is prepared and
10
10
  // survives a dropped connection, and a table creation two processes may race.
11
11
 
@@ -28,6 +28,8 @@ export const WAKEUP_TABLE = "sanoma_wakeup";
28
28
  export const CHATS_TABLE = "sanoma_chats";
29
29
  /** Each chat's messages, the AI SDK's UI messages as JSON, in `seq` order. */
30
30
  export const CHAT_MESSAGES_TABLE = "sanoma_chat_messages";
31
+ /** The api tokens (`tokens.ts`): each one's SHA-256, never the token, whom it acts for, its groups, and when it was revoked. */
32
+ export const API_TOKENS_TABLE = "sanoma_api_tokens";
31
33
 
32
34
  /** The runtime's tables, each with the word the messages name it by. */
33
35
  const TABLES: readonly [what: string, ddl: string][] = [
@@ -97,6 +99,11 @@ const TABLES: readonly [what: string, ddl: string][] = [
97
99
  `CREATE TABLE IF NOT EXISTS ${CHAT_MESSAGES_TABLE} (chat_id text NOT NULL REFERENCES ${CHATS_TABLE} (id) ` +
98
100
  "ON DELETE CASCADE, id text NOT NULL, seq integer NOT NULL, message jsonb NOT NULL, PRIMARY KEY (chat_id, id))",
99
101
  ],
102
+ [
103
+ "api tokens",
104
+ `CREATE TABLE IF NOT EXISTS ${API_TOKENS_TABLE} (id text PRIMARY KEY, hash text NOT NULL UNIQUE, ` +
105
+ "subject text NOT NULL, groups jsonb NOT NULL, created_at timestamptz NOT NULL DEFAULT now(), revoked_at timestamptz)",
106
+ ],
100
107
  ];
101
108
 
102
109
  /** The Postgres error code of `err`, or an empty string when it has none. */
package/src/deadlines.ts CHANGED
@@ -8,7 +8,7 @@ import { warn } from "./log.ts";
8
8
  import type { CallContext, DriverFn, Op } from "./op.ts";
9
9
  import type { Secrets } from "./secret.ts";
10
10
  import { errorMessage, WAKEUP_AGENT } from "./shared.ts";
11
- import type { WakeupRegistration } from "./wakeup.ts";
11
+ import { type EnvWakeup, WAKE_PATH, type WakeupRegistration } from "./wakeup.ts";
12
12
 
13
13
  // What a worker knows of its own runs that DBOS cannot tell it: which are executing and which are
14
14
  // blocked in a `ctx` wait, and until when. DBOS sees both as PENDING. A worker that registers a
@@ -133,15 +133,15 @@ export interface SelfStop {
133
133
  at: string | null;
134
134
  }
135
135
 
136
- /** What the stop rule acts on: the wakeup row, the wakeup's register operation, and the worker. */
136
+ /** Registers a deadline with the instance's wakeup, replacing what it held; throws when it could not. */
137
+ export type RegisterWakeup = (registration: WakeupRegistration) => Promise<void>;
138
+
139
+ /** What the stop rule acts on: the wakeup row, how a deadline is registered, and the worker. */
137
140
  export interface StopRule {
138
141
  /** The wakeup row's database. */
139
142
  db: () => Promise<Db>;
140
- /** The declared wakeup's binding, else its declaration's id: what scopes a registration's idempotency key to this instance. */
141
- wakeup: string;
142
- /** The wakeup type's register operation, and its driver (none when the connector attaches none). */
143
- register: { op: Op; fn: DriverFn | undefined };
144
- secrets: Secrets;
143
+ /** The declared wakeup's register operation (`declaredRegister`), or the host's own route (`envRegister`). */
144
+ register: RegisterWakeup;
145
145
  deadlines: Deadlines;
146
146
  idle: () => Promise<boolean>;
147
147
  everyMs: number;
@@ -174,7 +174,7 @@ export function stopWhenIdle(rule: StopRule): { close(): void } {
174
174
  const db = await rule.db();
175
175
  if (at !== null) {
176
176
  try {
177
- await registerWakeup(rule, { at });
177
+ await rule.register({ at });
178
178
  } catch (err) {
179
179
  const message = errorMessage(err);
180
180
  await recordWakeupError(db, message);
@@ -214,18 +214,64 @@ export function stopWhenIdle(rule: StopRule): { close(): void } {
214
214
  };
215
215
  }
216
216
 
217
+ /** A declared wakeup's register operation, and what its call needs. */
218
+ export interface DeclaredRegister {
219
+ /** The wakeup type's register operation. */
220
+ op: Op;
221
+ /** Its driver: none when the connector attaches none. */
222
+ fn: DriverFn | undefined;
223
+ /** The instance's secrets, which the driver reads the wakeup's token from. */
224
+ secrets: Secrets;
225
+ /** The declared wakeup's binding, else its declaration's id: what scopes a registration's idempotency key to this instance. */
226
+ wakeup: string;
227
+ }
228
+
229
+ /**
230
+ * Registers through the declared wakeup's register operation, as `SanomaClient.call` calls a
231
+ * driver: its input parsed, a `CallContext` of the runtime's, and no ledger record, which is a run's.
232
+ */
233
+ export function declaredRegister({ op, fn, secrets, wakeup }: DeclaredRegister): RegisterWakeup {
234
+ return async (registration) => {
235
+ if (!fn) throw new Error(`${op.id} has no driver: the connector package must attach one`);
236
+ // Fresh each time: a repeat of an earlier `at` after another registration must re-arm it, so no
237
+ // two registrations share a key (real drivers never dedupe on it anyway).
238
+ const key = `wakeup:${wakeup}:${randomUUID()}`;
239
+ const context: CallContext = {
240
+ idempotencyKey: key,
241
+ runId: key,
242
+ opId: op.id,
243
+ attempt: 1,
244
+ secrets,
245
+ by: WAKEUP_AGENT,
246
+ };
247
+ await fn(op.input.parse(registration), context);
248
+ };
249
+ }
250
+
217
251
  /**
218
- * Calls the wakeup's register operation, as `SanomaClient.call` calls a driver: its input parsed,
219
- * a `CallContext` of the runtime's, and no ledger record, which is a run's.
252
+ * Registers at the host's own wake route, as the environment names it (`EnvWakeup`): `PUT
253
+ * {url}/__sanoma/wake` with the token as a bearer and the registration as JSON, no driver and no
254
+ * secret store. 204 is taken; anything else fails with its status and the route's own `error`.
220
255
  */
221
- export async function registerWakeup(
222
- { register: { op, fn }, secrets, wakeup }: Pick<StopRule, "register" | "secrets" | "wakeup">,
223
- registration: WakeupRegistration,
224
- ) {
225
- if (!fn) throw new Error(`${op.id} has no driver: the connector package must attach one`);
226
- // Fresh each time: a repeat of an earlier `at` after another registration must re-arm it, so no
227
- // two registrations share a key (real drivers never dedupe on it anyway).
228
- const key = `wakeup:${wakeup}:${randomUUID()}`;
229
- const context: CallContext = { idempotencyKey: key, runId: key, opId: op.id, attempt: 1, secrets, by: WAKEUP_AGENT };
230
- await fn(op.input.parse(registration), context);
256
+ export function envRegister({ url, token }: EnvWakeup): RegisterWakeup {
257
+ return async (registration) => {
258
+ const where = `PUT ${url}${WAKE_PATH}`;
259
+ let res: Response;
260
+ try {
261
+ res = await fetch(`${url}${WAKE_PATH}`, {
262
+ method: "PUT",
263
+ headers: { authorization: `Bearer ${token}`, "content-type": "application/json" },
264
+ body: JSON.stringify(registration),
265
+ // A redirect is no answer of the host's, and would carry the token elsewhere.
266
+ redirect: "manual",
267
+ signal: AbortSignal.timeout(30_000),
268
+ });
269
+ } catch (err) {
270
+ throw new Error(`${where}: no answer (${errorMessage(err)})`, { cause: err });
271
+ }
272
+ if (res.status === 204) return;
273
+ const body: unknown = await res.json().catch(() => undefined);
274
+ const error = (body as { error?: unknown } | undefined)?.error;
275
+ throw new Error(`${where} answered ${res.status}${typeof error === "string" ? `: ${error}` : ""}`);
276
+ };
231
277
  }
package/src/define.ts CHANGED
@@ -18,14 +18,37 @@ export interface Principal {
18
18
  groups?: string[];
19
19
  /** For an agent: the id of the person whose instruction it carries. */
20
20
  onBehalfOf?: string;
21
+ /**
22
+ * For a visitor: the email their site's login verified (`LoginHalf.verify`), which the app
23
+ * passes on. Admission keeps it for a visitor alone; a run's `ctx.startedBy.email`.
24
+ */
25
+ email?: string;
26
+ /**
27
+ * For an api token (`token:<id>`): the subject its row acts for, which `SanomaClient.start`
28
+ * reads from the row, never from the caller; a run's `ctx.startedBy.subject`.
29
+ */
30
+ subject?: string;
21
31
  }
22
32
 
23
33
  export const Principal: z.ZodType<Principal> = z.object({
24
34
  id: z.string().regex(/\S/, "id must not be blank"),
25
35
  groups: z.array(z.string()).optional(),
26
36
  onBehalfOf: z.string().regex(/\S/, "onBehalfOf must not be blank").optional(),
37
+ email: z.string().optional(),
38
+ subject: z.string().optional(),
27
39
  });
28
40
 
41
+ /**
42
+ * Who started a run, as its workflow sees it (`ctx.startedBy`): the principal's id (`alice`,
43
+ * `visitor:<login>:<subject>`, `token:<id>`), with the email a visitor's login verified, and for
44
+ * an api token the subject its row acts for, so a workflow can tell whose a record is.
45
+ */
46
+ export interface StartedBy {
47
+ readonly id: string;
48
+ readonly email?: string;
49
+ readonly subject?: string;
50
+ }
51
+
29
52
  /** A built-in a workflow may call, as its description lists them. */
30
53
  export type Builtin = WorkflowEntry["builtins"][number];
31
54
  export type Use = Op | Builtin;
@@ -227,6 +250,8 @@ interface BaseCtx {
227
250
  */
228
251
  now(): Promise<number>;
229
252
  readonly runId: string;
253
+ /** Who started the run: read, never called (`StartedBy`). */
254
+ readonly startedBy: StartedBy;
230
255
  }
231
256
 
232
257
  export type Ctx<U extends readonly Use[]> = BaseCtx &
@@ -1,10 +1,12 @@
1
+ import { hkdfSync } from "node:crypto";
1
2
  import { readFileSync } from "node:fs";
2
3
 
4
+ /** The deployment's own keys: bound only to the environment or bootstrap, never written by the runtime. */
5
+ export const DEPLOYMENT_KEYS: readonly string[] = ["SANOMA_SIGNING_KEY", "SANOMA_SECRETS_KEY"];
6
+ export type DeploymentKeyName = "SANOMA_SIGNING_KEY" | "SANOMA_SECRETS_KEY";
7
+
3
8
  /** 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 {
9
+ export function deploymentKey(name: DeploymentKeyName, env: NodeJS.ProcessEnv = process.env): Buffer {
8
10
  const value = env[name];
9
11
  const file = env[`${name}_FILE`];
10
12
  if (value && file) throw new Error(`Set only one of ${name} and ${name}_FILE`);
@@ -16,8 +18,32 @@ export function deploymentKey(
16
18
  throw new Error(`${name}_FILE could not be read`);
17
19
  }
18
20
  }
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");
21
+ const key = encoded ? keyBytes(encoded) : undefined;
22
+ if (!key) throw new Error(`${name} must be 32 random bytes in base64; supply ${name} or ${name}_FILE`);
23
+ return key;
24
+ }
25
+
26
+ /**
27
+ * The 32 bytes of a key written as text: padded base64 (`sanoma key`), or base64url without
28
+ * padding (a `secret(..., { generate: true })` marker's value). Anything else is `undefined`.
29
+ */
30
+ export function keyBytes(text: string): Buffer | undefined {
31
+ if (/^[A-Za-z0-9+/]{43}=$/.test(text)) return Buffer.from(text, "base64");
32
+ if (/^[A-Za-z0-9_-]{43}$/.test(text)) return Buffer.from(text, "base64url");
33
+ return undefined;
23
34
  }
35
+
36
+ /**
37
+ * A 32-byte key of its own for `purpose`, derived from a deployment's signing key (HKDF-SHA256
38
+ * over its base64 text), as that deployment derives it from its `SANOMA_SIGNING_KEY`.
39
+ */
40
+ export const deriveSigningKey = (signingKey: Buffer, purpose: string): Buffer =>
41
+ Buffer.from(hkdfSync("sha256", signingKey.toString("base64"), "", purpose, 32));
42
+
43
+ /**
44
+ * A 32-byte key of its own for `purpose`, derived from `SANOMA_SIGNING_KEY` (`deriveSigningKey`):
45
+ * each use of the signing key (a login's cookies, the setup's state, sealed values) gets a key no
46
+ * other use shares.
47
+ */
48
+ export const signingKeyFor = (purpose: string): Buffer =>
49
+ deriveSigningKey(deploymentKey("SANOMA_SIGNING_KEY"), purpose);
package/src/describe.ts CHANGED
@@ -4,7 +4,8 @@ import { type AppEntry, appsAt } from "./apps.ts";
4
4
  import { readSource, type SourceFile } from "./ast.ts";
5
5
  import { readPolicyFiles } from "./cedar.ts";
6
6
  import { recordSchemaOf } from "./collection.ts";
7
- import { connectorsOf, resolveConfig, rootOf, type SanomaConfig } from "./config.ts";
7
+ import { decideCall } from "./call.ts";
8
+ import { connectorsOf, type ResolvedConfig, resolveConfig, rootOf, type SanomaConfig } from "./config.ts";
8
9
  import { type Builtin, jsonSchemaOf, opIdsOf, type Use } from "./define.ts";
9
10
  import {
10
11
  CAPABILITIES,
@@ -17,6 +18,7 @@ import {
17
18
  } from "./description.ts";
18
19
  import { isDirect } from "./direct.ts";
19
20
  import { type CredentialStatus, credentialsOf } from "./env.ts";
21
+ import { CODE_MAIL } from "./login-code.ts";
20
22
  import { lintWorkflow } from "./lint.ts";
21
23
  import { fresh, stampOf, stampsOf } from "./load.ts";
22
24
  import { LOCKFILE } from "./lockfile.ts";
@@ -27,7 +29,17 @@ import { allowAll, policyOpOf } from "./policy.ts";
27
29
  import { type Resource, resourceTypesOf, valueAt } from "./resource.ts";
28
30
  import { type DeclaredResource, inAppPeople, loadDataFiles, type ResourceProblem } from "./resources.ts";
29
31
  import { apiNameProblem } from "./sdk.ts";
30
- import { apiNameOf, BUILT_IN_WORKFLOWS, DATA_VENDOR, errorMessage, problemLine } from "./shared.ts";
32
+ import {
33
+ apiNameOf,
34
+ BUILT_IN_WORKFLOWS,
35
+ DATA_VENDOR,
36
+ errorMessage,
37
+ LOGIN_AGENT,
38
+ LOGIN_CODE_WORKFLOW,
39
+ type PeopleResource,
40
+ principalOf,
41
+ problemLine,
42
+ } from "./shared.ts";
31
43
  import { readSites, type SiteEntry } from "./sites.ts";
32
44
 
33
45
  // `@sanoma-ai/workflows/describe`: what a UI renders from, apart from the main entry.
@@ -282,6 +294,7 @@ export function describeConfig(config: SanomaConfig): ConfigDescription {
282
294
  ...appProblems,
283
295
  ...appClashes(apps, collections, sites),
284
296
  ...domainProblems(dataFiles.resources, resources, sites),
297
+ ...loginProblems(resolved, dataFiles.resources),
285
298
  ],
286
299
  apps,
287
300
  policy: {
@@ -291,9 +304,33 @@ export function describeConfig(config: SanomaConfig): ConfigDescription {
291
304
  files: resolved.root === undefined ? [] : readPolicyFiles(resolved.root),
292
305
  },
293
306
  sites,
307
+ ...(resolved.login && { login: { sender: resolved.login.sender.id } }),
294
308
  };
295
309
  }
296
310
 
311
+ /**
312
+ * The policy holding or denying the sign-in code: `login.sender` as the runtime's agent `login`
313
+ * in a run of `login-code` must be allowed, or nobody receives a code.
314
+ */
315
+ function loginProblems(resolved: ResolvedConfig, people: readonly PeopleResource[]): ResourceProblem[] {
316
+ if (!resolved.login || resolved.policyProblems.length) return [];
317
+ const { sender } = resolved.login;
318
+ const agent = principalOf(LOGIN_AGENT, people)!;
319
+ const run = { id: "check", workflow: LOGIN_CODE_WORKFLOW, approvals: [] };
320
+ const decision = decideCall(resolved.policy, sender, CODE_MAIL, agent, run);
321
+ if (decision.kind === "allow") return [];
322
+ const does = decision.kind === "deny" ? "denies" : "holds";
323
+ const by = decision.reasons?.length ? ` (${decision.reasons.join(", ")})` : "";
324
+ return [
325
+ {
326
+ file: "policies",
327
+ message:
328
+ `the policy ${does} ${sender.id} for the sign-in code${by}, so nobody receives one: exempt the runtime's ` +
329
+ `agent, \`unless { principal == Sanoma::Principal::"${LOGIN_AGENT}" }\``,
330
+ },
331
+ ];
332
+ }
333
+
297
334
  /** That the root's `kind` `name`, in `file`, is named as an app is. */
298
335
  const appClash = (kind: string, name: string, file: string): ResourceProblem => ({
299
336
  file,
@@ -422,5 +422,7 @@ export const ConfigDescriptionSchema = z.strictObject({
422
422
  * the config does not have as its problems; none when the root has no `sites/`.
423
423
  */
424
424
  sites: z.array(SiteEntrySchema),
425
+ /** The config's `login`: the operation its sign-in codes are sent with, by id. */
426
+ login: z.strictObject({ sender: z.string() }).optional(),
425
427
  });
426
428
  export type ConfigDescription = z.infer<typeof ConfigDescriptionSchema>;
package/src/host.ts CHANGED
@@ -46,8 +46,11 @@ export interface HostSpec {
46
46
  source: string;
47
47
  /** The branch (or tag) it runs: `main`, never a commit. */
48
48
  ref: string;
49
- /** The secrets it passes the runtime (`SANOMA_DATABASE_URL`, `SANOMA_SECRETS_KEY`): a write-only field. */
50
- secrets: string;
49
+ /**
50
+ * The secrets it passes the runtime (`SANOMA_DATABASE_URL`, `SANOMA_SECRETS_KEY`): a write-only
51
+ * field. Absent for a host that binds its own bootstrap (`bindsBootstrap`).
52
+ */
53
+ secrets?: string;
51
54
  /** The port the app listens on. */
52
55
  port: string;
53
56
  /** A public site's domain, by site name: the app serves each site at the root of its domain (`SANOMA_DOMAINS`). */
@@ -58,6 +61,11 @@ export interface HostSpec {
58
61
  * file may not declare it, so a merge to `ref` is a change to the host.
59
62
  */
60
63
  revision: string;
64
+ /**
65
+ * True for a host whose vendor mints the instance's bootstrap (its database URL, keys and
66
+ * tokens) and binds it itself, as Sanoma Cloud's does: such a type takes no `secrets`.
67
+ */
68
+ bindsBootstrap?: boolean;
61
69
  outputs: (state: Record<string, unknown>) => HostOutputs;
62
70
  }
63
71
 
@@ -83,8 +91,9 @@ function unwrap(schema: z.ZodType): z.ZodType {
83
91
 
84
92
  /**
85
93
  * Throws what is wrong with a resource type's `host`: an input or `revision` that names no field,
86
- * `secrets` that is not write-only, a `revision` that is, an unknown lifetime, a type apply cannot
87
- * change (not `writable`).
94
+ * `secrets` that is not write-only, missing (unless the host binds its own bootstrap) or given
95
+ * beside `bindsBootstrap`, a `revision` that is write-only, an unknown lifetime, a type apply
96
+ * cannot change (not `writable`).
88
97
  */
89
98
  export function checkHost(
90
99
  what: string,
@@ -96,10 +105,17 @@ export function checkHost(
96
105
  if (!LIFETIMES.includes(host.capabilities?.lifetime)) {
97
106
  problems.push(`capabilities.lifetime is one of ${LIFETIMES.join(", ")}`);
98
107
  }
99
- for (const [input, path] of [...Object.entries(host.inputs ?? {}), ["revision", host.revision] as const]) {
108
+ // An input given as undefined is one not given.
109
+ const given = Object.entries(host.inputs ?? {}).filter(([, path]) => path !== undefined);
110
+ for (const [input, path] of [...given, ["revision", host.revision] as const]) {
100
111
  if (typeof path !== "string" || !hasPath(type.schema, path)) problems.push(`${input} names no field (${path})`);
101
112
  }
102
- if (!type.fields.writeOnly.includes(host.inputs?.secrets)) problems.push("inputs.secrets must be a write-only field");
113
+ const secrets = host.inputs?.secrets;
114
+ if (host.bindsBootstrap) {
115
+ if (secrets !== undefined) problems.push("inputs.secrets is not taken by a host that binds its own bootstrap");
116
+ } else if (secrets === undefined || !type.fields.writeOnly.includes(secrets)) {
117
+ problems.push("inputs.secrets must be a write-only field, unless the host binds its own bootstrap");
118
+ }
103
119
  if (type.fields.writeOnly.includes(host.revision)) problems.push("revision must not be write-only: drift reads it");
104
120
  if (typeof host.outputs !== "function") problems.push("outputs must be a function of the state");
105
121
  if (problems.length) throw new Error(`${what}: its host: ${problems.join("; ")}`);