@fluidgrids/cli 2026.1021.1 → 2026.1028.2

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 (134) hide show
  1. package/README.md +157 -5
  2. package/dist/auth/device-login.d.ts +31 -0
  3. package/dist/auth/device-login.d.ts.map +1 -0
  4. package/dist/auth/device-login.js +75 -0
  5. package/dist/auth/device-login.js.map +1 -0
  6. package/dist/auth/token-auth.d.ts +49 -0
  7. package/dist/auth/token-auth.d.ts.map +1 -0
  8. package/dist/auth/token-auth.js +279 -0
  9. package/dist/auth/token-auth.js.map +1 -0
  10. package/dist/cli.d.ts +4 -5
  11. package/dist/cli.d.ts.map +1 -1
  12. package/dist/cli.js +18 -32
  13. package/dist/cli.js.map +1 -1
  14. package/dist/code-first/api.d.ts +357 -0
  15. package/dist/code-first/api.d.ts.map +1 -0
  16. package/dist/code-first/api.js +288 -0
  17. package/dist/code-first/api.js.map +1 -0
  18. package/dist/code-first/code-upload.d.ts +52 -0
  19. package/dist/code-first/code-upload.d.ts.map +1 -0
  20. package/dist/code-first/code-upload.js +161 -0
  21. package/dist/code-first/code-upload.js.map +1 -0
  22. package/dist/code-first/commands/codegen.d.ts +20 -0
  23. package/dist/code-first/commands/codegen.d.ts.map +1 -0
  24. package/dist/code-first/commands/codegen.js +50 -0
  25. package/dist/code-first/commands/codegen.js.map +1 -0
  26. package/dist/code-first/commands/diff.d.ts +28 -0
  27. package/dist/code-first/commands/diff.d.ts.map +1 -0
  28. package/dist/code-first/commands/diff.js +73 -0
  29. package/dist/code-first/commands/diff.js.map +1 -0
  30. package/dist/code-first/commands/hotfix.d.ts +54 -0
  31. package/dist/code-first/commands/hotfix.d.ts.map +1 -0
  32. package/dist/code-first/commands/hotfix.js +225 -0
  33. package/dist/code-first/commands/hotfix.js.map +1 -0
  34. package/dist/code-first/commands/import.d.ts +40 -0
  35. package/dist/code-first/commands/import.d.ts.map +1 -0
  36. package/dist/code-first/commands/import.js +235 -0
  37. package/dist/code-first/commands/import.js.map +1 -0
  38. package/dist/code-first/commands/init.d.ts +33 -0
  39. package/dist/code-first/commands/init.d.ts.map +1 -0
  40. package/dist/code-first/commands/init.js +177 -0
  41. package/dist/code-first/commands/init.js.map +1 -0
  42. package/dist/code-first/commands/interface.d.ts +12 -0
  43. package/dist/code-first/commands/interface.d.ts.map +1 -0
  44. package/dist/code-first/commands/interface.js +21 -0
  45. package/dist/code-first/commands/interface.js.map +1 -0
  46. package/dist/code-first/commands/pull.d.ts +63 -0
  47. package/dist/code-first/commands/pull.d.ts.map +1 -0
  48. package/dist/code-first/commands/pull.js +266 -0
  49. package/dist/code-first/commands/pull.js.map +1 -0
  50. package/dist/code-first/commands/push.d.ts +97 -0
  51. package/dist/code-first/commands/push.d.ts.map +1 -0
  52. package/dist/code-first/commands/push.js +313 -0
  53. package/dist/code-first/commands/push.js.map +1 -0
  54. package/dist/code-first/commands/replay.d.ts +44 -0
  55. package/dist/code-first/commands/replay.d.ts.map +1 -0
  56. package/dist/code-first/commands/replay.js +238 -0
  57. package/dist/code-first/commands/replay.js.map +1 -0
  58. package/dist/code-first/commands/runs.d.ts +94 -0
  59. package/dist/code-first/commands/runs.d.ts.map +1 -0
  60. package/dist/code-first/commands/runs.js +304 -0
  61. package/dist/code-first/commands/runs.js.map +1 -0
  62. package/dist/code-first/commands/validate.d.ts +38 -0
  63. package/dist/code-first/commands/validate.d.ts.map +1 -0
  64. package/dist/code-first/commands/validate.js +140 -0
  65. package/dist/code-first/commands/validate.js.map +1 -0
  66. package/dist/code-first/commands/versions.d.ts +14 -0
  67. package/dist/code-first/commands/versions.d.ts.map +1 -0
  68. package/dist/code-first/commands/versions.js +30 -0
  69. package/dist/code-first/commands/versions.js.map +1 -0
  70. package/dist/code-first/connections.d.ts +55 -0
  71. package/dist/code-first/connections.d.ts.map +1 -0
  72. package/dist/code-first/connections.js +180 -0
  73. package/dist/code-first/connections.js.map +1 -0
  74. package/dist/code-first/durable-operations.d.ts +42 -0
  75. package/dist/code-first/durable-operations.d.ts.map +1 -0
  76. package/dist/code-first/durable-operations.js +136 -0
  77. package/dist/code-first/durable-operations.js.map +1 -0
  78. package/dist/code-first/history.d.ts +30 -0
  79. package/dist/code-first/history.d.ts.map +1 -0
  80. package/dist/code-first/history.js +139 -0
  81. package/dist/code-first/history.js.map +1 -0
  82. package/dist/code-first/imports.d.ts +22 -0
  83. package/dist/code-first/imports.d.ts.map +1 -0
  84. package/dist/code-first/imports.js +67 -0
  85. package/dist/code-first/imports.js.map +1 -0
  86. package/dist/code-first/index.d.ts +17 -0
  87. package/dist/code-first/index.d.ts.map +1 -0
  88. package/dist/code-first/index.js +35 -0
  89. package/dist/code-first/index.js.map +1 -0
  90. package/dist/code-first/lowering.d.ts +81 -0
  91. package/dist/code-first/lowering.d.ts.map +1 -0
  92. package/dist/code-first/lowering.js +225 -0
  93. package/dist/code-first/lowering.js.map +1 -0
  94. package/dist/code-first/operations.d.ts +57 -0
  95. package/dist/code-first/operations.d.ts.map +1 -0
  96. package/dist/code-first/operations.js +167 -0
  97. package/dist/code-first/operations.js.map +1 -0
  98. package/dist/code-first/presigned.d.ts +21 -0
  99. package/dist/code-first/presigned.d.ts.map +1 -0
  100. package/dist/code-first/presigned.js +85 -0
  101. package/dist/code-first/presigned.js.map +1 -0
  102. package/dist/code-first/project.d.ts +123 -0
  103. package/dist/code-first/project.d.ts.map +1 -0
  104. package/dist/code-first/project.js +301 -0
  105. package/dist/code-first/project.js.map +1 -0
  106. package/dist/code-first/python.d.ts +81 -0
  107. package/dist/code-first/python.d.ts.map +1 -0
  108. package/dist/code-first/python.js +249 -0
  109. package/dist/code-first/python.js.map +1 -0
  110. package/dist/code-first/register.d.ts +27 -0
  111. package/dist/code-first/register.d.ts.map +1 -0
  112. package/dist/code-first/register.js +270 -0
  113. package/dist/code-first/register.js.map +1 -0
  114. package/dist/code-first/remote.d.ts +58 -0
  115. package/dist/code-first/remote.d.ts.map +1 -0
  116. package/dist/code-first/remote.js +126 -0
  117. package/dist/code-first/remote.js.map +1 -0
  118. package/dist/code-first/replay.d.ts +36 -0
  119. package/dist/code-first/replay.d.ts.map +1 -0
  120. package/dist/code-first/replay.js +52 -0
  121. package/dist/code-first/replay.js.map +1 -0
  122. package/dist/code-first/shared.d.ts +51 -0
  123. package/dist/code-first/shared.d.ts.map +1 -0
  124. package/dist/code-first/shared.js +93 -0
  125. package/dist/code-first/shared.js.map +1 -0
  126. package/dist/modules.d.ts +4 -0
  127. package/dist/modules.d.ts.map +1 -1
  128. package/dist/modules.js +6 -0
  129. package/dist/modules.js.map +1 -1
  130. package/dist/program.d.ts +20 -0
  131. package/dist/program.d.ts.map +1 -0
  132. package/dist/program.js +43 -0
  133. package/dist/program.js.map +1 -0
  134. package/package.json +3 -1
package/README.md CHANGED
@@ -7,12 +7,20 @@ It is a **thin shell over [`@burdenoff/cli-sdk`](https://www.npmjs.com/package/@
7
7
  like the VibeControls CLI. The FluidGrids commands live in the shared
8
8
  `fluidgrids` module, and the shell also mounts the shared platform modules
9
9
  (workspaces, organizations, tags, files, billing, notifications, support, store,
10
- integrations, devportal and more).
10
+ integrations, devportal and more). The code-first workflow commands (`init`,
11
+ `codegen`, `pull`, `push`, `diff`, `validate`, `import`, `interface`) live in
12
+ this repo under `src/code-first/`, because they depend on
13
+ [`@fluidgrids/workflows`](https://www.npmjs.com/package/@fluidgrids/workflows),
14
+ which the other product CLIs built on cli-sdk should not pull in.
11
15
 
12
16
  ## Installation
13
17
 
14
- > **Not on npm yet.** `@fluidgrids/cli` is not published, so
15
- > `npm install -g @fluidgrids/cli` will 404. Build from source until it ships.
18
+ ```bash
19
+ npm install -g @fluidgrids/cli
20
+ fluidgrids --version
21
+ ```
22
+
23
+ From source:
16
24
 
17
25
  ```bash
18
26
  git clone https://github.com/algoshred/fluidgrids-cli.git
@@ -36,6 +44,30 @@ fluidgrids auth status
36
44
 
37
45
  For automation, sign in as an app with `fluidgrids auth login --client-credentials`.
38
46
 
47
+ ### Token mode (CI and the doctor)
48
+
49
+ When `FLUIDGRIDS_TOKEN` (or `--token <token>`) is set, the CLI uses that platform
50
+ access token for the run and never reads or writes the stored login. Prefer the
51
+ variable: a `--token` value is visible in the process list.
52
+
53
+ | Variable | Purpose |
54
+ |---|---|
55
+ | `FLUIDGRIDS_TOKEN` | Platform access token |
56
+ | `FLUIDGRIDS_WORKSPACE_TOKEN` | Workspace token to use as is, or |
57
+ | `FLUIDGRIDS_WORKSPACE_ID` | Workspace to issue a workspace token for (in memory, re-issued before it expires) |
58
+ | `FLUIDGRIDS_ORG_ID` | Organization, sent as `x-org-id` (optional; the platform derives it from the workspace) |
59
+ | `FLUIDGRIDS_CF_ACCESS_CLIENT_ID` / `_SECRET` | Cloudflare Access service-token headers, which the alpha gateways need |
60
+
61
+ ```bash
62
+ FLUIDGRIDS_TOKEN=… FLUIDGRIDS_WORKSPACE_ID=… fluidgrids diff --exit-code
63
+ ```
64
+
65
+ Queries are retried up to three times on network and 5xx errors. Mutations are
66
+ sent once: after a server error the CLI cannot tell whether a version was
67
+ created, and a retry could create it twice. With only
68
+ `FLUIDGRIDS_WORKSPACE_TOKEN`, the CLI does not know which workspace the token is
69
+ for, so set `FLUIDGRIDS_WORKSPACE_ID` as well to keep the project workspace check.
70
+
39
71
  ## Workflows and runs
40
72
 
41
73
  ```bash
@@ -59,6 +91,120 @@ fluidgrids runs resume <runId> --payload '{"approved":true}'
59
91
  fluidgrids runs retry-node <runId> <graphNodeId>
60
92
  ```
61
93
 
94
+ ## Code-first workflows
95
+
96
+ Workflows can be kept as TypeScript or Python in a project (spec
97
+ `fluidgrids-specs/product/specs/code-first`, Phase A). Tier-1 code *constructs*
98
+ a canvas workflow: the canvas and the code are two views of one definition, and
99
+ the CLI lifts and lowers between them with `@fluidgrids/workflows`.
100
+
101
+ ```
102
+ my-automations/
103
+ fluidgrids.config.json language, workspace, default task queue, Python interpreter
104
+ package.json (TypeScript) @fluidgrids/workflows, @fluidgrids/cli
105
+ pyproject.toml (Python) fluidgrids-workflows
106
+ .fluidgrids/nodes.ts|py typed node clients (fluidgrids codegen; commit it)
107
+ workflows/<key>.ts|py tier-1 source, with <key>.layout.json (and <key>.pinned.json)
108
+ workflows/<key>.json a workflow kept as the JSON export envelope
109
+ activities/ code workflows import
110
+ lock.json registry snapshot, node versions, SDK version, pulled versions
111
+ ```
112
+
113
+ ```bash
114
+ fluidgrids init --lang ts # scaffold; signs in (device code) when signed out at a terminal
115
+ fluidgrids codegen # .fluidgrids/nodes.ts from the workspace's node registry
116
+ fluidgrids pull lead-enrichment # workflows/lead-enrichment.ts + layout sidecar
117
+ fluidgrids pull --as py # every tracked workflow as Python (`--format py` works too)
118
+ fluidgrids pull --check # print the fidelity report; exit 1 when an export is lossy
119
+ fluidgrids validate --strict # IR v2 rules plus the strict rules (add --remote for the service)
120
+ fluidgrids diff --against active # IR diff of the local workflows against a stored version
121
+ fluidgrids push --dry-run # what would change
122
+ fluidgrids push -m "Route big leads" # a new version per changed workflow, with workflowVersionDiff
123
+ fluidgrids import workflows/new-flow.ts # a NEW workflow through the service's import (it lowers the TypeScript)
124
+ fluidgrids interface lead-enrichment # the typed interface of the ACTIVE (else newest) version
125
+ ```
126
+
127
+ - **Fidelity** is computed by lowering the lifted code and comparing `irHash`,
128
+ never by heuristics. `--server` on `pull` asks the service to render instead.
129
+ - **Push** lowers the whole project locally once, validates every workflow, and
130
+ creates a version only for workflows whose `irHash` changed
131
+ (`createWorkflowVersion`; a key new to the workspace goes through
132
+ `importWorkflow` as a DRAFT). Stored pinned TEST data is kept when the code has none.
133
+ When a workflow got a newer version in the workspace after it was pulled (a
134
+ canvas edit, another push), `push` refuses rather than silently revert it:
135
+ pull again and re-apply the edit, or pass `--force`.
136
+ - **Workspace.** `init --workspace <id>` records the workspace in
137
+ `fluidgrids.config.json`. While it is recorded, `pull`, `push`, `diff`,
138
+ `validate`, `codegen` and `import` refuse to run against another workspace
139
+ (switch with `fluidgrids workspace set <id>` or `FLUIDGRIDS_WORKSPACE_ID`).
140
+ Without `workspaceId` the project works with whichever workspace is selected.
141
+ - **Connections** are written by name in code. Names resolve against the
142
+ workspace's connections at push time; a name that does not resolve stops the
143
+ push before anything is written, with what to do about it. Only the
144
+ connections a workflow uses are sent to the service (`pull --server`,
145
+ `import` of TypeScript).
146
+ - **Python** projects need Python 3.11+ with the `fluidgrids-workflows` package.
147
+ `pull` and `codegen` write `.py` without it; `push`, `diff`, `validate` and
148
+ `import` run `python -m fluidgrids_workflows lower` and stop with an install
149
+ hint when the package is missing. The interpreter is `FLUIDGRIDS_PYTHON`, then
150
+ `"python"` in `fluidgrids.config.json`, then `.venv/`, then `python3`.
151
+ - The workspace needs the `fluidgrids.code-first` feature for the code-first
152
+ service operations (`exportWorkflow` as code, `importWorkflow` from source,
153
+ `validateWorkflowDefinition`, `workflowInterface`, and saving a definition
154
+ that uses IR version 2 fields such as `authoring`).
155
+
156
+ ## Durable functions
157
+
158
+ Tier-2 code (`workflow()` exports in `workflows/*.ts`) runs as managed durable
159
+ functions: the code itself is the workflow, replayed from its event history
160
+ (spec `code-first` 02, 04, 05 and 06; BOFF-9905 Phase B). A tier-1 graph can run
161
+ one as a step with `wf.codeWorkflow`.
162
+
163
+ ```bash
164
+ fluidgrids push # uploads the code bundle once, links it to each new version
165
+ fluidgrids runs start approvals --input '{"orderId": 7}' --wait
166
+ fluidgrids runs describe <runId> # kind, function, build, history length, failing task
167
+ fluidgrids history <runId> --out run.history.json # the run's event history (also `runs history`)
168
+ fluidgrids signal <runId> approve --payload '{"by":"ana"}' # also `runs signal`
169
+ fluidgrids runs stack <runId> # where the code is waiting (__stack_trace)
170
+ fluidgrids runs terminate <runId> --reason stuck # `runs cancel` asks the code to cancel instead
171
+ fluidgrids replay run.history.json --isolate # replay against the local code; fails on non-determinism
172
+ fluidgrids test --replay histories/ # the project tests, then every *.history.json
173
+ fluidgrids push --hotfix v3 --replay-sample 20 # replace the code of v3 (replay-verified by the service)
174
+ fluidgrids versions list approvals # versions with the bundle each one runs
175
+ fluidgrids run lead-enrichment --wait # trigger a canvas workflow from its trigger node
176
+ ```
177
+
178
+ - **Push.** The bundle is one ES module built with the pinned esbuild, so its
179
+ `buildId` (`sha256` of the bytes) is the one the service computes for the same
180
+ files. `push` asks `prepareWorkflowCodeUpload` for presigned uploads, sends the
181
+ bundle only when the workspace does not have it yet, sends the source archive
182
+ (the workflow modules and the files they import, the lockfile and vendored
183
+ pure-ESM `dependencies`), and creates the version with `codeBundle`. Test
184
+ files such as `workflows/*.spec.ts`, and `activities/` modules no workflow
185
+ imports, are neither bundled nor archived. The bundle and archive size caps
186
+ are checked before the first version is written, and on `--dry-run`.
187
+ `lock.json` records the bundle's `buildId`, `sourceHash` and SDK version.
188
+ - **Refusals.** Features that arrive in Phase C (user activities and task
189
+ queues, custom queries and updates, search attributes, interceptors and
190
+ sinks, Python durable functions) and activity node types a durable run cannot
191
+ run stop the push before anything is written. `validate` reports the same
192
+ findings as errors.
193
+ - **Hotfix.** `push --hotfix <version>` replaces the code of an existing version
194
+ when the graph, the exported functions and their interfaces are unchanged.
195
+ `--replay-sample N` replays the N latest durable runs of that version locally
196
+ first (it scans the newest 500 runs of the key, warns when it finds fewer than
197
+ N and refuses when it finds none); the service then replays up to 100 runs
198
+ and ends `REPLACED` or `REJECTED`. The result, with the job id and any
199
+ violations, is printed before a rejection or a timeout exits non-zero.
200
+ `--no-verify-replay` skips the service check and is audited.
201
+ - Presigned URLs (uploads, offloaded history payloads) must be https, and
202
+ neither they nor the storage service's error bodies are printed; only an S3
203
+ error's code and message are.
204
+ - The workspace needs the `fluidgrids.durable-functions` feature for uploads,
205
+ hotfixes, `runs start` and signals to durable runs. When it is off, runs that
206
+ already exist keep running and can still be cancelled and terminated.
207
+
62
208
  ## Credentials, webhooks, scheduled jobs
63
209
 
64
210
  A credential is an integration connection. Creating one is a two-step flow:
@@ -112,8 +258,14 @@ bun run test
112
258
  bun run sanity # format:check + lint + type-check + test + build
113
259
  ```
114
260
 
115
- Changes to command behaviour belong in `cli-sdk` (`src/modules/fluidgrids/`);
116
- this repo only picks modules and product defaults.
261
+ Changes to the shared command behaviour belong in `cli-sdk`
262
+ (`src/modules/fluidgrids/`). This repo picks modules and product defaults, and
263
+ holds the code-first commands (`src/code-first/`) and token mode (`src/auth/`).
264
+
265
+ The code-first GraphQL documents are validated against the vendored supergraph
266
+ `schema/wspace.graphql` (`bun run schema:pull` refreshes it) and, until the
267
+ code-first service release is on the Hive CDN, against
268
+ `schema/code-first.pending.graphql`.
117
269
 
118
270
  ## License
119
271
 
@@ -0,0 +1,31 @@
1
+ /**
2
+ * The OAuth2 device-code login that `fluidgrids init` runs when the CLI is not
3
+ * signed in (spec 07 §7). It is the same flow as `fluidgrids auth login`, built
4
+ * from the `@burdenoff/cli-sdk/core` primitives, with one difference: it never
5
+ * prompts. The workspace comes from `--workspace`, or is the caller's only
6
+ * workspace; with several and none named, the platform login is stored and
7
+ * `fluidgrids workspace set <id>` picks one.
8
+ */
9
+ import { fetchWorkspaces, issueWorkspaceToken, openBrowser, pollForToken, startDeviceCodeFlow, type CLIContext } from '@burdenoff/cli-sdk/core';
10
+ /** The device-code primitives; tests substitute them. */
11
+ export interface DeviceLoginDeps {
12
+ startDeviceCodeFlow: typeof startDeviceCodeFlow;
13
+ pollForToken: typeof pollForToken;
14
+ fetchWorkspaces: typeof fetchWorkspaces;
15
+ issueWorkspaceToken: typeof issueWorkspaceToken;
16
+ openBrowser: typeof openBrowser;
17
+ }
18
+ export declare const defaultDeviceLoginDeps: DeviceLoginDeps;
19
+ export interface DeviceLoginResult {
20
+ /** The selected workspace, or null when the caller has to pick one. */
21
+ workspaceId: string | null;
22
+ /** Workspaces to choose from when none was selected. */
23
+ choices: Array<{
24
+ id: string;
25
+ name: string;
26
+ }>;
27
+ }
28
+ export declare function deviceCodeLogin(ctx: CLIContext, options?: {
29
+ workspaceId?: string;
30
+ }, deps?: DeviceLoginDeps): Promise<DeviceLoginResult>;
31
+ //# sourceMappingURL=device-login.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"device-login.d.ts","sourceRoot":"","sources":["../../src/auth/device-login.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAEH,OAAO,EACL,eAAe,EACf,mBAAmB,EACnB,WAAW,EACX,YAAY,EACZ,mBAAmB,EAEnB,KAAK,UAAU,EAEhB,MAAM,yBAAyB,CAAC;AAEjC,yDAAyD;AACzD,MAAM,WAAW,eAAe;IAC9B,mBAAmB,EAAE,OAAO,mBAAmB,CAAC;IAChD,YAAY,EAAE,OAAO,YAAY,CAAC;IAClC,eAAe,EAAE,OAAO,eAAe,CAAC;IACxC,mBAAmB,EAAE,OAAO,mBAAmB,CAAC;IAChD,WAAW,EAAE,OAAO,WAAW,CAAC;CACjC;AAED,eAAO,MAAM,sBAAsB,EAAE,eAMpC,CAAC;AAEF,MAAM,WAAW,iBAAiB;IAChC,uEAAuE;IACvE,WAAW,EAAE,MAAM,GAAG,IAAI,CAAC;IAC3B,wDAAwD;IACxD,OAAO,EAAE,KAAK,CAAC;QAAE,EAAE,EAAE,MAAM,CAAC;QAAC,IAAI,EAAE,MAAM,CAAA;KAAE,CAAC,CAAC;CAC9C;AAED,wBAAsB,eAAe,CACnC,GAAG,EAAE,UAAU,EACf,OAAO,GAAE;IAAE,WAAW,CAAC,EAAE,MAAM,CAAA;CAAO,EACtC,IAAI,GAAE,eAAwC,GAC7C,OAAO,CAAC,iBAAiB,CAAC,CAkE5B"}
@@ -0,0 +1,75 @@
1
+ /**
2
+ * The OAuth2 device-code login that `fluidgrids init` runs when the CLI is not
3
+ * signed in (spec 07 §7). It is the same flow as `fluidgrids auth login`, built
4
+ * from the `@burdenoff/cli-sdk/core` primitives, with one difference: it never
5
+ * prompts. The workspace comes from `--workspace`, or is the caller's only
6
+ * workspace; with several and none named, the platform login is stored and
7
+ * `fluidgrids workspace set <id>` picks one.
8
+ */
9
+ import { fetchWorkspaces, issueWorkspaceToken, openBrowser, pollForToken, startDeviceCodeFlow, CliUserError, } from '@burdenoff/cli-sdk/core';
10
+ export const defaultDeviceLoginDeps = {
11
+ startDeviceCodeFlow,
12
+ pollForToken,
13
+ fetchWorkspaces,
14
+ issueWorkspaceToken,
15
+ openBrowser,
16
+ };
17
+ export async function deviceCodeLogin(ctx, options = {}, deps = defaultDeviceLoginDeps) {
18
+ const config = ctx.config.read();
19
+ const oidc = ctx.config.resolveOIDC();
20
+ const { output } = ctx;
21
+ output.printInfo('Starting device code authentication...');
22
+ const flow = await deps.startDeviceCodeFlow(oidc);
23
+ console.log('');
24
+ console.log(` Open: ${flow.verificationUri}`);
25
+ console.log(` Code: ${flow.userCode}`);
26
+ console.log('');
27
+ if (!(await deps.openBrowser(flow.verificationUriComplete ?? flow.verificationUri))) {
28
+ output.printWarning('Could not open a browser; open the URL above.');
29
+ }
30
+ output.printInfo('Waiting for authorization...');
31
+ const token = await deps.pollForToken(flow.deviceCode, flow.interval, oidc);
32
+ const platform = {
33
+ accessToken: token.accessToken,
34
+ refreshToken: token.refreshToken,
35
+ expiresAt: Date.now() + token.expiresIn * 1000,
36
+ authMethod: 'device_code',
37
+ };
38
+ const workspaces = await deps.fetchWorkspaces(config.globalEndpoint, token.accessToken);
39
+ const selected = options.workspaceId
40
+ ? workspaces.find((workspace) => workspace.id === options.workspaceId)
41
+ : workspaces.length === 1
42
+ ? workspaces[0]
43
+ : undefined;
44
+ if (options.workspaceId && !selected) {
45
+ ctx.auth.write(platform);
46
+ ctx.gql.reset();
47
+ throw new CliUserError(`You are not a member of workspace ${options.workspaceId}.`, {
48
+ hint: workspaces.length > 0
49
+ ? `Your workspaces: ${workspaces.map((workspace) => `${workspace.name} (${workspace.id})`).join(', ')}`
50
+ : 'Your account has no workspaces yet.',
51
+ });
52
+ }
53
+ if (!selected) {
54
+ ctx.auth.write(platform);
55
+ ctx.gql.reset();
56
+ output.printSuccess('Authentication successful');
57
+ return {
58
+ workspaceId: null,
59
+ choices: workspaces.map((workspace) => ({ id: workspace.id, name: workspace.name })),
60
+ };
61
+ }
62
+ const issued = await deps.issueWorkspaceToken(config.workspaceEndpoint, token.accessToken, selected.id, selected.organizationId);
63
+ const workspaceTokenExpiresAt = Date.parse(issued.expiresAt);
64
+ ctx.auth.write({
65
+ ...platform,
66
+ workspaceToken: issued.token,
67
+ ...(Number.isFinite(workspaceTokenExpiresAt) ? { workspaceTokenExpiresAt } : {}),
68
+ workspaceId: selected.id,
69
+ organizationId: selected.organizationId,
70
+ });
71
+ ctx.gql.reset();
72
+ output.printSuccess(`Authentication successful; using workspace ${selected.name}`);
73
+ return { workspaceId: selected.id, choices: [] };
74
+ }
75
+ //# sourceMappingURL=device-login.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"device-login.js","sourceRoot":"","sources":["../../src/auth/device-login.ts"],"names":[],"mappings":"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"}
@@ -0,0 +1,49 @@
1
+ /**
2
+ * Non-interactive authentication for CI and the doctor (BOFF-9904, plan D6).
3
+ *
4
+ * When `FLUIDGRIDS_TOKEN` (or `--token <token>`) is set, the CLI uses that
5
+ * platform access token instead of the stored device-code login, and never
6
+ * writes a token to disk. The workspace token comes from
7
+ * `FLUIDGRIDS_WORKSPACE_TOKEN`, or is issued in memory for
8
+ * `FLUIDGRIDS_WORKSPACE_ID` (and re-issued shortly before it expires).
9
+ * `FLUIDGRIDS_ORG_ID` is optional: the platform derives the organization from
10
+ * the workspace, and the CLI sends it as `x-org-id` when it is set. `FLUIDGRIDS_CF_ACCESS_CLIENT_ID` / `_SECRET` add Cloudflare
11
+ * Access service-token headers, which alpha gateways require.
12
+ *
13
+ * Prefer the environment variable: a `--token` value is visible in the
14
+ * process list.
15
+ */
16
+ import { type RequestDocument } from 'graphql-request';
17
+ import { type AuthStore, type CLIContext, type ConfigStore, type GqlClients } from '@burdenoff/cli-sdk/core';
18
+ export declare const TOKEN_FLAG = "--token";
19
+ export interface TokenAuthSettings {
20
+ accessToken: string;
21
+ workspaceToken?: string;
22
+ workspaceId?: string;
23
+ organizationId?: string;
24
+ cfAccess?: {
25
+ clientId: string;
26
+ clientSecret: string;
27
+ };
28
+ }
29
+ /** The `--token` value from argv, if given; `undefined` when the flag is absent. */
30
+ export declare function tokenFromArgv(argv: readonly string[]): string | undefined;
31
+ /** Token mode settings, or null for the normal stored login. */
32
+ export declare function readTokenAuthSettings(argv: readonly string[], env: Readonly<Record<string, string | undefined>>, prefix?: string): TokenAuthSettings | null;
33
+ /** The `exp` claim of a JWT in milliseconds, when the token is a readable JWT. */
34
+ export declare function jwtExpiry(token: string): number | undefined;
35
+ /** An in-memory AuthStore over the injected tokens; `write` never touches the disk. */
36
+ export declare function createTokenAuthStore(settings: TokenAuthSettings): AuthStore;
37
+ /**
38
+ * True when the document holds a mutation. A server error after a mutation
39
+ * does not say whether it was applied, so retrying it could, for example,
40
+ * create a workflow version twice. A document that does not parse is left to
41
+ * the server to refuse.
42
+ */
43
+ export declare function isMutation(document: RequestDocument): boolean;
44
+ export declare const ISSUE_WORKSPACE_TOKEN = "\n mutation FluidgridsTokenModeIssueWorkspaceToken($input: IssueWorkspaceTokenInput!) {\n issueWorkspaceToken(input: $input) {\n success token expiresAt\n error { code message }\n }\n }\n";
45
+ /** GraphQL clients for token mode: static tokens, Cloudflare Access headers, no refresh. */
46
+ export declare function createTokenGqlClients(config: ConfigStore, auth: AuthStore, settings: TokenAuthSettings): GqlClients;
47
+ /** The context with token-mode auth and clients in place of the stored login. */
48
+ export declare function applyTokenAuth(ctx: CLIContext, settings: TokenAuthSettings): CLIContext;
49
+ //# sourceMappingURL=token-auth.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"token-auth.d.ts","sourceRoot":"","sources":["../../src/auth/token-auth.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAGH,OAAO,EAAiB,KAAK,eAAe,EAAkB,MAAM,iBAAiB,CAAC;AAEtF,OAAO,EAGL,KAAK,SAAS,EACd,KAAK,UAAU,EACf,KAAK,WAAW,EAEhB,KAAK,UAAU,EAEhB,MAAM,yBAAyB,CAAC;AAEjC,eAAO,MAAM,UAAU,YAAY,CAAC;AAEpC,MAAM,WAAW,iBAAiB;IAChC,WAAW,EAAE,MAAM,CAAC;IACpB,cAAc,CAAC,EAAE,MAAM,CAAC;IACxB,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,cAAc,CAAC,EAAE,MAAM,CAAC;IACxB,QAAQ,CAAC,EAAE;QAAE,QAAQ,EAAE,MAAM,CAAC;QAAC,YAAY,EAAE,MAAM,CAAA;KAAE,CAAC;CACvD;AAYD,oFAAoF;AACpF,wBAAgB,aAAa,CAAC,IAAI,EAAE,SAAS,MAAM,EAAE,GAAG,MAAM,GAAG,SAAS,CAoBzE;AAED,gEAAgE;AAChE,wBAAgB,qBAAqB,CACnC,IAAI,EAAE,SAAS,MAAM,EAAE,EACvB,GAAG,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,SAAS,CAAC,CAAC,EACjD,MAAM,SAAe,GACpB,iBAAiB,GAAG,IAAI,CAmB1B;AAED,kFAAkF;AAClF,wBAAgB,SAAS,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS,CAa3D;AAED,uFAAuF;AACvF,wBAAgB,oBAAoB,CAAC,QAAQ,EAAE,iBAAiB,GAAG,SAAS,CAgC3E;AAgBD;;;;;GAKG;AACH,wBAAgB,UAAU,CAAC,QAAQ,EAAE,eAAe,GAAG,OAAO,CAc7D;AAkCD,eAAO,MAAM,qBAAqB,kNAOjC,CAAC;AAEF,4FAA4F;AAC5F,wBAAgB,qBAAqB,CACnC,MAAM,EAAE,WAAW,EACnB,IAAI,EAAE,SAAS,EACf,QAAQ,EAAE,iBAAiB,GAC1B,UAAU,CA4FZ;AAED,iFAAiF;AACjF,wBAAgB,cAAc,CAAC,GAAG,EAAE,UAAU,EAAE,QAAQ,EAAE,iBAAiB,GAAG,UAAU,CAGvF"}
@@ -0,0 +1,279 @@
1
+ /**
2
+ * Non-interactive authentication for CI and the doctor (BOFF-9904, plan D6).
3
+ *
4
+ * When `FLUIDGRIDS_TOKEN` (or `--token <token>`) is set, the CLI uses that
5
+ * platform access token instead of the stored device-code login, and never
6
+ * writes a token to disk. The workspace token comes from
7
+ * `FLUIDGRIDS_WORKSPACE_TOKEN`, or is issued in memory for
8
+ * `FLUIDGRIDS_WORKSPACE_ID` (and re-issued shortly before it expires).
9
+ * `FLUIDGRIDS_ORG_ID` is optional: the platform derives the organization from
10
+ * the workspace, and the CLI sends it as `x-org-id` when it is set. `FLUIDGRIDS_CF_ACCESS_CLIENT_ID` / `_SECRET` add Cloudflare
11
+ * Access service-token headers, which alpha gateways require.
12
+ *
13
+ * Prefer the environment variable: a `--token` value is visible in the
14
+ * process list.
15
+ */
16
+ import { Kind, parse } from 'graphql';
17
+ import { GraphQLClient } from 'graphql-request';
18
+ import { CliUserError, extractGqlErrorMessage, } from '@burdenoff/cli-sdk/core';
19
+ export const TOKEN_FLAG = '--token';
20
+ const REQUEST_TIMEOUT_MS = 30_000;
21
+ const MAX_ATTEMPTS = 3;
22
+ const RETRY_DELAY_MS = 1_000;
23
+ /** Re-issue a minted workspace token this long before it expires. */
24
+ const WORKSPACE_TOKEN_BUFFER_MS = 60_000;
25
+ function nonEmpty(value) {
26
+ return value !== undefined && value.trim() !== '' ? value.trim() : undefined;
27
+ }
28
+ /** The `--token` value from argv, if given; `undefined` when the flag is absent. */
29
+ export function tokenFromArgv(argv) {
30
+ for (let index = 0; index < argv.length; index++) {
31
+ const arg = argv[index];
32
+ if (arg === '--')
33
+ return undefined;
34
+ if (arg === TOKEN_FLAG) {
35
+ const value = argv[index + 1];
36
+ if (value === undefined || value.startsWith('-') || value.trim() === '') {
37
+ throw new CliUserError(`${TOKEN_FLAG} needs a value.`, {
38
+ hint: 'Prefer the FLUIDGRIDS_TOKEN environment variable.',
39
+ });
40
+ }
41
+ return value.trim();
42
+ }
43
+ if (arg?.startsWith(`${TOKEN_FLAG}=`)) {
44
+ const value = arg.slice(TOKEN_FLAG.length + 1);
45
+ if (value.trim() === '')
46
+ throw new CliUserError(`${TOKEN_FLAG} needs a value.`);
47
+ return value.trim();
48
+ }
49
+ }
50
+ return undefined;
51
+ }
52
+ /** Token mode settings, or null for the normal stored login. */
53
+ export function readTokenAuthSettings(argv, env, prefix = 'FLUIDGRIDS') {
54
+ const accessToken = tokenFromArgv(argv) ?? nonEmpty(env[`${prefix}_TOKEN`]);
55
+ if (!accessToken)
56
+ return null;
57
+ const settings = { accessToken };
58
+ const workspaceToken = nonEmpty(env[`${prefix}_WORKSPACE_TOKEN`]);
59
+ const workspaceId = nonEmpty(env[`${prefix}_WORKSPACE_ID`]);
60
+ const organizationId = nonEmpty(env[`${prefix}_ORG_ID`]);
61
+ if (workspaceToken)
62
+ settings.workspaceToken = workspaceToken;
63
+ if (workspaceId)
64
+ settings.workspaceId = workspaceId;
65
+ if (organizationId)
66
+ settings.organizationId = organizationId;
67
+ const clientId = nonEmpty(env[`${prefix}_CF_ACCESS_CLIENT_ID`]);
68
+ const clientSecret = nonEmpty(env[`${prefix}_CF_ACCESS_CLIENT_SECRET`]);
69
+ if ((clientId === undefined) !== (clientSecret === undefined)) {
70
+ throw new CliUserError(`Set both ${prefix}_CF_ACCESS_CLIENT_ID and ${prefix}_CF_ACCESS_CLIENT_SECRET, or neither.`);
71
+ }
72
+ if (clientId && clientSecret)
73
+ settings.cfAccess = { clientId, clientSecret };
74
+ return settings;
75
+ }
76
+ /** The `exp` claim of a JWT in milliseconds, when the token is a readable JWT. */
77
+ export function jwtExpiry(token) {
78
+ const payload = token.split('.')[1];
79
+ if (!payload)
80
+ return undefined;
81
+ try {
82
+ const claims = JSON.parse(Buffer.from(payload, 'base64url').toString('utf8'));
83
+ if (typeof claims === 'object' && claims !== null && 'exp' in claims) {
84
+ const exp = claims.exp;
85
+ return typeof exp === 'number' && Number.isFinite(exp) ? exp * 1000 : undefined;
86
+ }
87
+ }
88
+ catch {
89
+ return undefined;
90
+ }
91
+ return undefined;
92
+ }
93
+ /** An in-memory AuthStore over the injected tokens; `write` never touches the disk. */
94
+ export function createTokenAuthStore(settings) {
95
+ const initial = () => {
96
+ const auth = { accessToken: settings.accessToken, refreshToken: '' };
97
+ const expiresAt = jwtExpiry(settings.accessToken);
98
+ if (expiresAt !== undefined)
99
+ auth.expiresAt = expiresAt;
100
+ if (settings.workspaceToken) {
101
+ auth.workspaceToken = settings.workspaceToken;
102
+ const workspaceExpiry = jwtExpiry(settings.workspaceToken);
103
+ if (workspaceExpiry !== undefined)
104
+ auth.workspaceTokenExpiresAt = workspaceExpiry;
105
+ }
106
+ if (settings.workspaceId)
107
+ auth.workspaceId = settings.workspaceId;
108
+ if (settings.organizationId)
109
+ auth.organizationId = settings.organizationId;
110
+ return auth;
111
+ };
112
+ let current = initial();
113
+ const expired = (at, bufferMs = 0) => at !== undefined && Date.now() + bufferMs >= at;
114
+ return {
115
+ read: () => (current ? { ...current } : null),
116
+ write: (auth) => {
117
+ current = { ...auth };
118
+ },
119
+ clear: () => {
120
+ current = null;
121
+ },
122
+ isTokenExpired: () => expired(current?.expiresAt),
123
+ isTokenExpiringSoon: () => expired(current?.expiresAt),
124
+ isWorkspaceTokenExpired: () => expired(current?.workspaceTokenExpiresAt),
125
+ isWorkspaceTokenExpiringSoon: () => expired(current?.workspaceTokenExpiresAt, WORKSPACE_TOKEN_BUFFER_MS),
126
+ isAuthenticated: () => !!current?.accessToken && !expired(current.expiresAt),
127
+ };
128
+ }
129
+ function sleep(ms) {
130
+ return new Promise((resolve) => setTimeout(resolve, ms));
131
+ }
132
+ function statusOf(error) {
133
+ if (error && typeof error === 'object' && 'response' in error) {
134
+ const response = error.response;
135
+ if (response && typeof response === 'object' && 'status' in response) {
136
+ return typeof response.status === 'number' ? response.status : undefined;
137
+ }
138
+ }
139
+ return undefined;
140
+ }
141
+ /**
142
+ * True when the document holds a mutation. A server error after a mutation
143
+ * does not say whether it was applied, so retrying it could, for example,
144
+ * create a workflow version twice. A document that does not parse is left to
145
+ * the server to refuse.
146
+ */
147
+ export function isMutation(document) {
148
+ let ast;
149
+ try {
150
+ ast =
151
+ typeof document === 'object' && 'definitions' in document
152
+ ? document
153
+ : parse(String(document));
154
+ }
155
+ catch {
156
+ return false;
157
+ }
158
+ return ast.definitions.some((definition) => definition.kind === Kind.OPERATION_DEFINITION && definition.operation === 'mutation');
159
+ }
160
+ /**
161
+ * One request with up to {@link MAX_ATTEMPTS} attempts on network and 5xx
162
+ * errors. Mutations get one attempt unless `retry` says they are safe to repeat.
163
+ */
164
+ async function requestWithRetry(endpoint, headers, document, variables, retry = !isMutation(document)) {
165
+ const client = new GraphQLClient(endpoint, { headers });
166
+ const attempts = retry ? MAX_ATTEMPTS : 1;
167
+ let lastError;
168
+ for (let attempt = 0; attempt < attempts; attempt++) {
169
+ const controller = new AbortController();
170
+ const timer = setTimeout(() => controller.abort(), REQUEST_TIMEOUT_MS);
171
+ try {
172
+ return await client.request({ document, variables, signal: controller.signal });
173
+ }
174
+ catch (error) {
175
+ lastError = error;
176
+ const status = statusOf(error);
177
+ const retryable = error instanceof TypeError || (status !== undefined && status >= 500);
178
+ if (!retryable || attempt === attempts - 1)
179
+ break;
180
+ await sleep(RETRY_DELAY_MS * 2 ** attempt);
181
+ }
182
+ finally {
183
+ clearTimeout(timer);
184
+ }
185
+ }
186
+ throw new Error(extractGqlErrorMessage(lastError));
187
+ }
188
+ export const ISSUE_WORKSPACE_TOKEN = `
189
+ mutation FluidgridsTokenModeIssueWorkspaceToken($input: IssueWorkspaceTokenInput!) {
190
+ issueWorkspaceToken(input: $input) {
191
+ success token expiresAt
192
+ error { code message }
193
+ }
194
+ }
195
+ `;
196
+ /** GraphQL clients for token mode: static tokens, Cloudflare Access headers, no refresh. */
197
+ export function createTokenGqlClients(config, auth, settings) {
198
+ const cfHeaders = () => settings.cfAccess
199
+ ? {
200
+ 'CF-Access-Client-Id': settings.cfAccess.clientId,
201
+ 'CF-Access-Client-Secret': settings.cfAccess.clientSecret,
202
+ }
203
+ : {};
204
+ const baseHeaders = () => {
205
+ const stored = auth.read();
206
+ const headers = { ...cfHeaders() };
207
+ if (stored?.accessToken)
208
+ headers['Authorization'] = `Bearer ${stored.accessToken}`;
209
+ if (stored?.organizationId)
210
+ headers['x-org-id'] = stored.organizationId;
211
+ return headers;
212
+ };
213
+ const withOrigin = (headers) => {
214
+ const origin = config.resolveProductOrigin();
215
+ return origin ? { ...headers, Origin: origin } : headers;
216
+ };
217
+ let minting = null;
218
+ async function mintWorkspaceToken() {
219
+ const stored = auth.read();
220
+ if (!stored?.workspaceId)
221
+ return;
222
+ const data = await requestWithRetry(config.read().workspaceEndpoint, withOrigin(baseHeaders()), ISSUE_WORKSPACE_TOKEN, {
223
+ input: {
224
+ workspaceId: stored.workspaceId,
225
+ ...(stored.organizationId ? { organizationId: stored.organizationId } : {}),
226
+ },
227
+ },
228
+ // Issuing a second token is harmless; the newest one is kept.
229
+ true);
230
+ const result = data.issueWorkspaceToken;
231
+ if (!result.success || !result.token) {
232
+ throw new CliUserError(`Issuing a workspace token failed: ${result.error?.message ?? 'no reason given'}`);
233
+ }
234
+ const next = { ...stored, workspaceToken: result.token };
235
+ const expiresAt = result.expiresAt ? Date.parse(result.expiresAt) : NaN;
236
+ if (Number.isFinite(expiresAt))
237
+ next.workspaceTokenExpiresAt = expiresAt;
238
+ auth.write(next);
239
+ }
240
+ async function ensureWorkspaceToken() {
241
+ if (settings.workspaceToken)
242
+ return;
243
+ const stored = auth.read();
244
+ const needed = !stored?.workspaceToken || auth.isWorkspaceTokenExpiringSoon();
245
+ if (!needed || !stored?.workspaceId)
246
+ return;
247
+ minting ??= mintWorkspaceToken().finally(() => {
248
+ minting = null;
249
+ });
250
+ await minting;
251
+ }
252
+ const workspace = {
253
+ async request(document, variables) {
254
+ await ensureWorkspaceToken();
255
+ const headers = withOrigin(baseHeaders());
256
+ const token = auth.read()?.workspaceToken;
257
+ if (token)
258
+ headers['X-Workspace-Authorization'] = `Bearer ${token}`;
259
+ return requestWithRetry(config.read().workspaceEndpoint, headers, document, variables);
260
+ },
261
+ };
262
+ const global = {
263
+ request(document, variables) {
264
+ return requestWithRetry(config.read().globalEndpoint, baseHeaders(), document, variables);
265
+ },
266
+ };
267
+ const workspaceAuthOnly = {
268
+ request(document, variables) {
269
+ return requestWithRetry(config.read().workspaceEndpoint, withOrigin(baseHeaders()), document, variables);
270
+ },
271
+ };
272
+ return { workspace, global, workspaceAuthOnly, reset: () => undefined };
273
+ }
274
+ /** The context with token-mode auth and clients in place of the stored login. */
275
+ export function applyTokenAuth(ctx, settings) {
276
+ const auth = createTokenAuthStore(settings);
277
+ return { ...ctx, auth, gql: createTokenGqlClients(ctx.config, auth, settings) };
278
+ }
279
+ //# sourceMappingURL=token-auth.js.map