@nathanstephenson/flow 0.1.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 (141) hide show
  1. package/README.md +641 -0
  2. package/build/workflow-runtime.cjs +213964 -0
  3. package/dist/backend/claude/async-queue.js +44 -0
  4. package/dist/backend/claude/auto-compaction.js +10 -0
  5. package/dist/backend/claude/background-calls.js +116 -0
  6. package/dist/backend/claude/enquiries.js +162 -0
  7. package/dist/backend/claude/index.js +1138 -0
  8. package/dist/backend/claude/mcp.js +55 -0
  9. package/dist/backend/claude/permissions.js +106 -0
  10. package/dist/backend/claude/streamed-message.js +120 -0
  11. package/dist/backend/claude/subagents.js +128 -0
  12. package/dist/backend/claude/workflow-parent.js +12 -0
  13. package/dist/backend/claude/workflow-processes.js +95 -0
  14. package/dist/backend/claude/workflow-subagent.js +234 -0
  15. package/dist/backend/effort.js +30 -0
  16. package/dist/backend/fake/index.js +570 -0
  17. package/dist/backend/mcp.js +190 -0
  18. package/dist/backend/pi/auto-compaction.js +16 -0
  19. package/dist/backend/pi/background-calls.js +56 -0
  20. package/dist/backend/pi/enquiries.js +63 -0
  21. package/dist/backend/pi/index.js +597 -0
  22. package/dist/backend/pi/mcp.js +35 -0
  23. package/dist/backend/pi/subagents.js +23 -0
  24. package/dist/backend/pi/work.js +104 -0
  25. package/dist/backend/pi/workflow-parent.js +21 -0
  26. package/dist/backend/pi/workflow-subagent.js +199 -0
  27. package/dist/backend/registry.js +34 -0
  28. package/dist/backend/types.js +1 -0
  29. package/dist/backend/workflow-tools.js +25 -0
  30. package/dist/build-id +1 -0
  31. package/dist/cli/application.js +397 -0
  32. package/dist/cli/bootstrap.js +535 -0
  33. package/dist/cli/host-control.js +100 -0
  34. package/dist/cli/install-guard.js +270 -0
  35. package/dist/cli/install-process.js +52 -0
  36. package/dist/cli/main.js +12 -0
  37. package/dist/cli/update.js +128 -0
  38. package/dist/client/connection.js +183 -0
  39. package/dist/client/context-usage.js +66 -0
  40. package/dist/client/diff.js +36 -0
  41. package/dist/client/enquiry.js +105 -0
  42. package/dist/client/markdown.js +192 -0
  43. package/dist/client/model-choices.js +32 -0
  44. package/dist/client/permission.js +60 -0
  45. package/dist/client/project-name.js +19 -0
  46. package/dist/client/reduce.js +463 -0
  47. package/dist/client/relative-time.js +30 -0
  48. package/dist/client/scope-kind.js +28 -0
  49. package/dist/client/search.js +136 -0
  50. package/dist/client/session-label.js +9 -0
  51. package/dist/client/status.js +84 -0
  52. package/dist/client/tool-chains.js +52 -0
  53. package/dist/client/tool-summary.js +98 -0
  54. package/dist/daemon/auth.js +590 -0
  55. package/dist/daemon/config-store.js +183 -0
  56. package/dist/daemon/config.js +687 -0
  57. package/dist/daemon/credential-redaction.js +9 -0
  58. package/dist/daemon/git.js +312 -0
  59. package/dist/daemon/host-control-routes.js +29 -0
  60. package/dist/daemon/host.js +2343 -0
  61. package/dist/daemon/http.js +19 -0
  62. package/dist/daemon/log.js +44 -0
  63. package/dist/daemon/mcp-auth.js +164 -0
  64. package/dist/daemon/models.js +85 -0
  65. package/dist/daemon/ownership.js +104 -0
  66. package/dist/daemon/projects.js +317 -0
  67. package/dist/daemon/publish.js +289 -0
  68. package/dist/daemon/pull-request.js +198 -0
  69. package/dist/daemon/runtime.js +100 -0
  70. package/dist/daemon/secret-store.js +65 -0
  71. package/dist/daemon/server.js +827 -0
  72. package/dist/daemon/shell.js +220 -0
  73. package/dist/daemon/skills.js +104 -0
  74. package/dist/daemon/stack-metadata.js +24 -0
  75. package/dist/daemon/stack.js +743 -0
  76. package/dist/daemon/store.js +130 -0
  77. package/dist/daemon/summariser.js +476 -0
  78. package/dist/daemon/workflow-execution-routes.js +105 -0
  79. package/dist/daemon/workflow-executions.js +1018 -0
  80. package/dist/daemon/workflow-mcp.js +20 -0
  81. package/dist/daemon/workflow-routes.js +102 -0
  82. package/dist/protocol/attachments.js +59 -0
  83. package/dist/protocol/commands.js +1 -0
  84. package/dist/protocol/events.js +20 -0
  85. package/dist/protocol/fonts.js +26 -0
  86. package/dist/protocol/git.js +12 -0
  87. package/dist/protocol/mcp.js +51 -0
  88. package/dist/protocol/projects.js +21 -0
  89. package/dist/protocol/publish.js +1 -0
  90. package/dist/protocol/pull-request.js +1 -0
  91. package/dist/protocol/secrets.js +4 -0
  92. package/dist/protocol/settings.js +63 -0
  93. package/dist/protocol/shells.js +8 -0
  94. package/dist/protocol/skills.js +16 -0
  95. package/dist/protocol/stack.js +41 -0
  96. package/dist/protocol/workflow-executions.js +1 -0
  97. package/dist/protocol/workflows.js +1 -0
  98. package/dist/tui/app.js +518 -0
  99. package/dist/tui/keys.js +54 -0
  100. package/dist/tui/render.js +366 -0
  101. package/dist/web/assets.js +10 -0
  102. package/dist/web/embedded.js +12 -0
  103. package/dist/web/manifest.js +70 -0
  104. package/dist/workflows/decisions.js +65 -0
  105. package/dist/workflows/executors.js +132 -0
  106. package/dist/workflows/graph.js +276 -0
  107. package/dist/workflows/json-schema.js +49 -0
  108. package/dist/workflows/loops.js +102 -0
  109. package/dist/workflows/mcp.js +18 -0
  110. package/dist/workflows/records.js +111 -0
  111. package/dist/workflows/recovery.js +25 -0
  112. package/dist/workflows/runtime-asset.js +17 -0
  113. package/dist/workflows/runtime-libs.js +1 -0
  114. package/dist/workflows/runtime-settings.js +23 -0
  115. package/dist/workflows/runtime.js +343 -0
  116. package/dist/workflows/scheduler.js +573 -0
  117. package/dist/workflows/schema.js +161 -0
  118. package/dist/workflows/store.js +93 -0
  119. package/package.json +87 -0
  120. package/web/dist/assets/__vite-browser-external-2447137e-BvRk9kiK.js +0 -0
  121. package/web/dist/assets/ghostty-vt-DOMeXDrv.wasm +0 -0
  122. package/web/dist/assets/index-BC0gLS53.js +106 -0
  123. package/web/dist/assets/index-CCeZYKES.css +2 -0
  124. package/web/dist/assets/inter-cyrillic-ext-wght-normal-BOeWTOD4.woff2 +0 -0
  125. package/web/dist/assets/inter-cyrillic-wght-normal-DqGufNeO.woff2 +0 -0
  126. package/web/dist/assets/inter-greek-ext-wght-normal-DlzME5K_.woff2 +0 -0
  127. package/web/dist/assets/inter-greek-wght-normal-CkhJZR-_.woff2 +0 -0
  128. package/web/dist/assets/inter-latin-ext-wght-normal-DO1Apj_S.woff2 +0 -0
  129. package/web/dist/assets/inter-latin-wght-normal-Dx4kXJAl.woff2 +0 -0
  130. package/web/dist/assets/inter-vietnamese-wght-normal-CBcvBZtf.woff2 +0 -0
  131. package/web/dist/assets/rolldown-runtime-B0Z9INg1.js +1 -0
  132. package/web/dist/assets/select-6i3wxovH.js +1 -0
  133. package/web/dist/assets/settings-mcp-CcT0ADJR.js +1 -0
  134. package/web/dist/assets/settings-secrets-CK4uF7fd.js +1 -0
  135. package/web/dist/assets/settings-workflows-CrbZF-nM.js +23 -0
  136. package/web/dist/assets/switch-ftZleVB8.js +6 -0
  137. package/web/dist/assets/workflow-editors-naPqAmYO.js +65 -0
  138. package/web/dist/assets/workflows-D4T4Gy_7.css +1 -0
  139. package/web/dist/assets/workflows-hh6ioeEA.js +7 -0
  140. package/web/dist/assets/workflows-pane-Db-MHf7Z.js +1 -0
  141. package/web/dist/index.html +31 -0
@@ -0,0 +1,590 @@
1
+ import { randomBytes, timingSafeEqual, } from "node:crypto";
2
+ import { chmodSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync, } from "node:fs";
3
+ import { join } from "node:path";
4
+ import { createRemoteJWKSet, jwtVerify, customFetch as joseCustomFetch } from "jose";
5
+ import * as oidc from "openid-client";
6
+ export const OIDC_COOKIE = "flow_session";
7
+ const SESSION_LIFETIME_MS = 7 * 24 * 60 * 60 * 1_000;
8
+ const LOGIN_LIFETIME_MS = 10 * 60 * 1_000;
9
+ const CLOCK_SKEW_SECONDS = 60;
10
+ const LOGOUT_TOKEN_MAX_AGE_SECONDS = 10 * 60;
11
+ export class OidcConfigurationError extends Error {
12
+ }
13
+ export class OidcAuthenticationError extends Error {
14
+ }
15
+ /**
16
+ * Read the all-or-nothing OIDC environment contract.
17
+ *
18
+ * An empty configuration preserves the local bearer/cookie behaviour. Once any variable is set,
19
+ * every variable is required and every URL is checked before the daemon opens a socket. That makes
20
+ * a typo fail closed instead of accidentally falling back to the local trust model.
21
+ */
22
+ export function oidcConfigFromEnv(env = process.env) {
23
+ const values = {
24
+ issuer: env["FLOW_OIDC_ISSUER"]?.trim(),
25
+ clientId: env["FLOW_OIDC_CLIENT_ID"]?.trim(),
26
+ clientSecret: env["FLOW_OIDC_CLIENT_SECRET"]?.trim(),
27
+ publicAppUrl: env["FLOW_OIDC_PUBLIC_APP_URL"]?.trim(),
28
+ };
29
+ const present = [
30
+ "FLOW_OIDC_ISSUER",
31
+ "FLOW_OIDC_CLIENT_ID",
32
+ "FLOW_OIDC_CLIENT_SECRET",
33
+ "FLOW_OIDC_PUBLIC_APP_URL",
34
+ ].filter((name) => env[name] !== undefined);
35
+ if (present.length === 0)
36
+ return undefined;
37
+ if (present.length !== 4 || Object.values(values).some((value) => !value)) {
38
+ throw new OidcConfigurationError("FLOW_OIDC_ISSUER, FLOW_OIDC_CLIENT_ID, FLOW_OIDC_CLIENT_SECRET and " +
39
+ "FLOW_OIDC_PUBLIC_APP_URL must be configured together");
40
+ }
41
+ const issuer = checkedUrl(values.issuer, "FLOW_OIDC_ISSUER", false);
42
+ const publicAppUrl = checkedUrl(values.publicAppUrl, "FLOW_OIDC_PUBLIC_APP_URL", true);
43
+ return {
44
+ issuer: values.issuer,
45
+ clientId: values.clientId,
46
+ clientSecret: values.clientSecret,
47
+ publicAppUrl: withoutTrailingSlash(publicAppUrl.href),
48
+ };
49
+ }
50
+ /**
51
+ * Persistent OIDC browser-session authority.
52
+ *
53
+ * Provider credentials never leave this object or its 0600 state file. Callers receive only an
54
+ * opaque random id, which is suitable for associating long-lived SSE/WebSocket connections with the
55
+ * browser session that opened them.
56
+ */
57
+ export class OidcGate {
58
+ config;
59
+ discovery;
60
+ client;
61
+ logoutKeys;
62
+ statePath;
63
+ sessions = new Map();
64
+ logoutTokens = new Map();
65
+ transactions = new Map();
66
+ refreshing = new Map();
67
+ connections = new Map();
68
+ refreshTimer;
69
+ disposed = false;
70
+ constructor(config, client, stateRoot, fetcher) {
71
+ this.config = config;
72
+ this.client = client;
73
+ this.discovery = client.serverMetadata();
74
+ this.logoutKeys = createRemoteJWKSet(new URL(this.discovery.jwks_uri), {
75
+ [joseCustomFetch]: fetcher,
76
+ });
77
+ const directory = join(stateRoot, "oidc");
78
+ this.statePath = join(directory, "sessions.json");
79
+ // The containing directory is itself credential material. Correct an existing permissive mode,
80
+ // not only a newly-created one (mkdir's mode is filtered by umask and ignored when it exists).
81
+ mkdirSync(stateRoot, { recursive: true, mode: 0o700 });
82
+ chmodSync(stateRoot, 0o700);
83
+ mkdirSync(directory, { recursive: true, mode: 0o700 });
84
+ chmodSync(directory, 0o700);
85
+ this.load();
86
+ this.expire();
87
+ this.scheduleRefresh();
88
+ }
89
+ static async create(config, stateRoot, options = {}) {
90
+ const fetcher = options.fetch ?? fetch;
91
+ let discovered;
92
+ try {
93
+ discovered = await oidc.discovery(new URL(config.issuer), config.clientId, config.clientSecret, undefined, {
94
+ [oidc.customFetch]: fetcher,
95
+ ...(new URL(config.issuer).protocol === "http:"
96
+ ? { execute: [oidc.allowInsecureRequests] }
97
+ : {}),
98
+ });
99
+ }
100
+ catch (error) {
101
+ throw new OidcConfigurationError(`OIDC discovery failed: ${error instanceof Error ? error.message : String(error)}`);
102
+ }
103
+ const discovery = discovered.serverMetadata();
104
+ validateDiscovery(config, discovery);
105
+ const clientAuthentication = selectClientAuthentication(config.clientSecret, discovery);
106
+ const client = new oidc.Configuration(discovery, config.clientId, {
107
+ client_secret: config.clientSecret,
108
+ redirect_uris: [`${config.publicAppUrl}/oauth/callback`],
109
+ [oidc.clockTolerance]: CLOCK_SKEW_SECONDS,
110
+ }, clientAuthentication);
111
+ client[oidc.customFetch] = fetcher;
112
+ if (new URL(config.issuer).protocol === "http:")
113
+ oidc.allowInsecureRequests(client);
114
+ return new OidcGate(config, client, stateRoot, fetcher);
115
+ }
116
+ callbackUrl() {
117
+ return `${this.config.publicAppUrl}/oauth/callback`;
118
+ }
119
+ backchannelLogoutUrl() {
120
+ return `${this.config.publicAppUrl}/oauth/backchannel`;
121
+ }
122
+ async beginLogin(returnTo) {
123
+ this.pruneTransactions();
124
+ while (this.transactions.size >= 128)
125
+ this.transactions.delete(this.transactions.keys().next().value);
126
+ const state = oidc.randomState();
127
+ const verifier = oidc.randomPKCECodeVerifier();
128
+ const nonce = oidc.randomNonce();
129
+ this.transactions.set(state, {
130
+ verifier,
131
+ nonce,
132
+ returnTo: safeReturnTo(returnTo, this.config.publicAppUrl),
133
+ expiresAt: Date.now() + LOGIN_LIFETIME_MS,
134
+ });
135
+ return oidc.buildAuthorizationUrl(this.client, {
136
+ redirect_uri: this.callbackUrl(),
137
+ response_type: "code",
138
+ scope: "openid offline_access",
139
+ prompt: "consent",
140
+ state,
141
+ nonce,
142
+ code_challenge: await oidc.calculatePKCECodeChallenge(verifier),
143
+ code_challenge_method: "S256",
144
+ }).href;
145
+ }
146
+ async completeLogin(url) {
147
+ const state = url.searchParams.get("state") ?? "";
148
+ const transaction = this.transactions.get(state);
149
+ // Consume before doing network I/O: retries and duplicated callbacks cannot exchange one code
150
+ // twice, even when the first token request is still in flight.
151
+ if (state)
152
+ this.transactions.delete(state);
153
+ if (!transaction || transaction.expiresAt <= Date.now()) {
154
+ throw new OidcAuthenticationError("The sign-in request is invalid or has expired.");
155
+ }
156
+ if (url.searchParams.has("error")) {
157
+ throw new OidcAuthenticationError("The identity provider did not complete sign-in.");
158
+ }
159
+ const code = url.searchParams.get("code");
160
+ if (!code)
161
+ throw new OidcAuthenticationError("The identity provider returned no code.");
162
+ let tokens;
163
+ try {
164
+ tokens = await oidc.authorizationCodeGrant(this.client, new URL(`${this.callbackUrl()}${url.search}`), {
165
+ expectedState: state,
166
+ expectedNonce: transaction.nonce,
167
+ pkceCodeVerifier: transaction.verifier,
168
+ idTokenExpected: true,
169
+ }, { redirect_uri: this.callbackUrl() });
170
+ }
171
+ catch {
172
+ throw new OidcAuthenticationError("The identity provider refused or returned an invalid sign-in response.");
173
+ }
174
+ const claims = tokens.claims();
175
+ if (!claims?.sub)
176
+ throw new OidcAuthenticationError("The ID token has no subject.");
177
+ const now = Date.now();
178
+ const id = opaqueToken();
179
+ const session = {
180
+ id,
181
+ sub: claims.sub,
182
+ ...(typeof claims.sid === "string" ? { providerSid: claims.sid } : {}),
183
+ expiresAt: now + SESSION_LIFETIME_MS,
184
+ tokenExpiresAt: tokenExpiry(tokens, claims, now),
185
+ ...(tokens.refresh_token ? { refreshToken: tokens.refresh_token } : {}),
186
+ };
187
+ this.sessions.set(id, session);
188
+ this.persist();
189
+ this.scheduleRefresh();
190
+ return { cookie: this.sessionCookie(id), location: transaction.returnTo };
191
+ }
192
+ /**
193
+ * Authenticate a browser cookie and refresh provider tokens when they expire.
194
+ *
195
+ * Concurrent requests for one browser session share one refresh promise. Rotation is persisted
196
+ * before the requests proceed, so a crash cannot resurrect the old refresh token.
197
+ */
198
+ async authenticate(cookieHeader) {
199
+ const id = cookieValue(cookieHeader, OIDC_COOKIE);
200
+ if (!id)
201
+ return undefined;
202
+ const session = this.sessions.get(id);
203
+ if (!session)
204
+ return undefined;
205
+ if (session.expiresAt <= Date.now()) {
206
+ this.invalidate(id);
207
+ return undefined;
208
+ }
209
+ if (session.tokenExpiresAt <= Date.now()) {
210
+ if (!(await this.refresh(id)))
211
+ return undefined;
212
+ }
213
+ return id;
214
+ }
215
+ logout(cookieHeader) {
216
+ const id = cookieValue(cookieHeader, OIDC_COOKIE);
217
+ if (id)
218
+ this.invalidate(id);
219
+ }
220
+ clearCookie() {
221
+ return `${OIDC_COOKIE}=; HttpOnly; SameSite=Lax; Path=/; Max-Age=0${this.secureCookie()}`;
222
+ }
223
+ /**
224
+ * Validate and consume an OIDC Back-Channel Logout token.
225
+ *
226
+ * The signed token replay marker is durable. Matching `sid` sessions are preferred, while a
227
+ * subject-only notice revokes every Flow
228
+ * browser session for that provider subject, as the specification requires.
229
+ */
230
+ async backchannelLogout(logoutToken) {
231
+ let claims;
232
+ try {
233
+ const verified = await jwtVerify(logoutToken, this.logoutKeys, {
234
+ issuer: this.config.issuer,
235
+ audience: this.config.clientId,
236
+ ...(this.discovery.id_token_signing_alg_values_supported
237
+ ? { algorithms: this.discovery.id_token_signing_alg_values_supported }
238
+ : {}),
239
+ clockTolerance: CLOCK_SKEW_SECONDS,
240
+ maxTokenAge: LOGOUT_TOKEN_MAX_AGE_SECONDS,
241
+ requiredClaims: ["iat", "exp", "jti"],
242
+ });
243
+ claims = verified.payload;
244
+ }
245
+ catch {
246
+ throw new OidcAuthenticationError("Invalid logout token.");
247
+ }
248
+ const event = claims.events?.["http://schemas.openid.net/event/backchannel-logout"];
249
+ if (!event || typeof event !== "object" || Array.isArray(event) || claims.nonce !== undefined) {
250
+ throw new OidcAuthenticationError("Invalid logout token.");
251
+ }
252
+ const providerSid = typeof claims.sid === "string" ? claims.sid : undefined;
253
+ const sub = typeof claims.sub === "string" ? claims.sub : undefined;
254
+ if (!providerSid && !sub)
255
+ throw new OidcAuthenticationError("Logout token has no session or subject.");
256
+ if (typeof claims.jti !== "string" || claims.jti.length === 0) {
257
+ throw new OidcAuthenticationError("Logout token has no valid identifier.");
258
+ }
259
+ const replayKey = claims.jti;
260
+ if (this.logoutTokens.has(replayKey)) {
261
+ throw new OidcAuthenticationError("Logout token was already used.");
262
+ }
263
+ this.logoutTokens.set(replayKey, Math.min(claims.exp * 1_000, Date.now() + SESSION_LIFETIME_MS));
264
+ const matches = [...this.sessions.values()].filter((session) => providerSid ? session.providerSid === providerSid : session.sub === sub);
265
+ for (const session of matches)
266
+ this.invalidate(session.id, false);
267
+ this.persist();
268
+ return matches.length;
269
+ }
270
+ registerConnection(sessionId, close) {
271
+ if (!this.sessions.has(sessionId)) {
272
+ close();
273
+ return () => undefined;
274
+ }
275
+ let active = true;
276
+ const set = this.connections.get(sessionId) ?? new Set();
277
+ set.add(close);
278
+ this.connections.set(sessionId, set);
279
+ return () => {
280
+ if (!active)
281
+ return;
282
+ active = false;
283
+ set.delete(close);
284
+ if (set.size === 0)
285
+ this.connections.delete(sessionId);
286
+ };
287
+ }
288
+ dispose() {
289
+ this.disposed = true;
290
+ if (this.refreshTimer)
291
+ clearTimeout(this.refreshTimer);
292
+ this.refreshTimer = undefined;
293
+ }
294
+ sessionCookie(id) {
295
+ return `${OIDC_COOKIE}=${id}; HttpOnly; SameSite=Lax; Path=/; Max-Age=${SESSION_LIFETIME_MS / 1_000}${this.secureCookie()}`;
296
+ }
297
+ secureCookie() {
298
+ return new URL(this.config.publicAppUrl).protocol === "https:" ? "; Secure" : "";
299
+ }
300
+ refresh(id) {
301
+ const inFlight = this.refreshing.get(id);
302
+ if (inFlight)
303
+ return inFlight;
304
+ const work = this.performRefresh(id).finally(() => this.refreshing.delete(id));
305
+ this.refreshing.set(id, work);
306
+ return work;
307
+ }
308
+ async performRefresh(id) {
309
+ const session = this.sessions.get(id);
310
+ if (!session?.refreshToken) {
311
+ this.invalidate(id);
312
+ return false;
313
+ }
314
+ try {
315
+ const tokens = await oidc.refreshTokenGrant(this.client, session.refreshToken);
316
+ const claims = tokens.claims();
317
+ if (claims) {
318
+ if (claims.sub !== session.sub ||
319
+ (session.providerSid && claims.sid && claims.sid !== session.providerSid)) {
320
+ throw new OidcAuthenticationError("Refreshed identity changed.");
321
+ }
322
+ }
323
+ const current = this.sessions.get(id);
324
+ if (!current)
325
+ return false;
326
+ const now = Date.now();
327
+ this.sessions.set(id, {
328
+ ...current,
329
+ refreshToken: tokens.refresh_token ?? session.refreshToken,
330
+ tokenExpiresAt: tokenExpiry(tokens, claims, now),
331
+ ...(typeof claims?.sid === "string" ? { providerSid: claims.sid } : {}),
332
+ });
333
+ this.persist();
334
+ this.scheduleRefresh();
335
+ return true;
336
+ }
337
+ catch {
338
+ this.invalidate(id);
339
+ return false;
340
+ }
341
+ }
342
+ invalidate(id, persist = true) {
343
+ if (!this.sessions.delete(id))
344
+ return;
345
+ // Copy before invoking: close handlers synchronously unregister themselves in both Node's SSE
346
+ // response and ws, and mutating a Set while iterating it is needlessly subtle.
347
+ for (const close of [...(this.connections.get(id) ?? [])]) {
348
+ try {
349
+ close();
350
+ }
351
+ catch {
352
+ // Revocation remains durable even if a socket was already gone.
353
+ }
354
+ }
355
+ this.connections.delete(id);
356
+ if (persist)
357
+ this.persist();
358
+ }
359
+ scheduleRefresh() {
360
+ if (this.disposed)
361
+ return;
362
+ if (this.refreshTimer)
363
+ clearTimeout(this.refreshTimer);
364
+ const now = Date.now();
365
+ const next = Math.min(...[...this.sessions.values()].map((session) => Math.min(session.expiresAt, session.tokenExpiresAt)), Infinity);
366
+ if (!Number.isFinite(next))
367
+ return;
368
+ this.refreshTimer = setTimeout(() => {
369
+ this.refreshTimer = undefined;
370
+ void this.refreshDueSessions();
371
+ }, Math.max(0, next - now));
372
+ this.refreshTimer.unref();
373
+ }
374
+ async refreshDueSessions() {
375
+ this.expire();
376
+ const now = Date.now();
377
+ const due = [...this.sessions.values()]
378
+ .filter((session) => session.expiresAt > now && session.tokenExpiresAt <= now)
379
+ .map((session) => session.id);
380
+ await Promise.all(due.map((id) => this.refresh(id)));
381
+ this.scheduleRefresh();
382
+ }
383
+ expire() {
384
+ const now = Date.now();
385
+ let dirty = false;
386
+ for (const session of [...this.sessions.values()]) {
387
+ if (session.expiresAt <= now) {
388
+ this.invalidate(session.id, false);
389
+ dirty = true;
390
+ }
391
+ }
392
+ for (const [jti, expiresAt] of this.logoutTokens) {
393
+ if (expiresAt <= now) {
394
+ this.logoutTokens.delete(jti);
395
+ dirty = true;
396
+ }
397
+ }
398
+ this.pruneTransactions();
399
+ if (dirty)
400
+ this.persist();
401
+ }
402
+ pruneTransactions() {
403
+ const now = Date.now();
404
+ for (const [state, transaction] of this.transactions) {
405
+ if (transaction.expiresAt <= now)
406
+ this.transactions.delete(state);
407
+ }
408
+ }
409
+ load() {
410
+ let stored;
411
+ try {
412
+ stored = JSON.parse(readFileSync(this.statePath, "utf8"));
413
+ chmodSync(this.statePath, 0o600);
414
+ }
415
+ catch {
416
+ return;
417
+ }
418
+ if (stored.version !== 2 || stored.issuer !== this.config.issuer ||
419
+ stored.clientId !== this.config.clientId || !Array.isArray(stored.sessions))
420
+ return;
421
+ for (const session of stored.sessions) {
422
+ if (validStoredSession(session))
423
+ this.sessions.set(session.id, session);
424
+ }
425
+ for (const [jti, expiresAt] of Object.entries(stored.logoutTokens ?? {})) {
426
+ if (typeof expiresAt === "number")
427
+ this.logoutTokens.set(jti, expiresAt);
428
+ }
429
+ }
430
+ persist() {
431
+ const state = {
432
+ version: 2,
433
+ issuer: this.config.issuer,
434
+ clientId: this.config.clientId,
435
+ sessions: [...this.sessions.values()],
436
+ logoutTokens: Object.fromEntries(this.logoutTokens),
437
+ };
438
+ const temporary = `${this.statePath}.${process.pid}.${opaqueToken(8)}.tmp`;
439
+ try {
440
+ writeFileSync(temporary, `${JSON.stringify(state)}\n`, { mode: 0o600, flag: "wx" });
441
+ chmodSync(temporary, 0o600);
442
+ renameSync(temporary, this.statePath);
443
+ chmodSync(this.statePath, 0o600);
444
+ }
445
+ finally {
446
+ rmSync(temporary, { force: true });
447
+ }
448
+ }
449
+ }
450
+ export async function createOidcGateFromEnv(stateRoot, env = process.env) {
451
+ const config = oidcConfigFromEnv(env);
452
+ return config ? OidcGate.create(config, stateRoot) : undefined;
453
+ }
454
+ /**
455
+ * The Session Host's bearer token (ADR 0004).
456
+ *
457
+ * Tools are pre-approved, so an authenticated client can run arbitrary commands as the user. The
458
+ * token is therefore treated as a credential: 0600 on disk, and compared in constant time.
459
+ */
460
+ export function readOrCreateToken(stateRoot) {
461
+ const path = join(stateRoot, "token");
462
+ try {
463
+ const existing = readFileSync(path, "utf8").trim();
464
+ if (existing) {
465
+ chmodSync(path, 0o600);
466
+ return existing;
467
+ }
468
+ }
469
+ catch {
470
+ // No token yet.
471
+ }
472
+ const token = randomBytes(32).toString("base64url");
473
+ mkdirSync(stateRoot, { recursive: true, mode: 0o700 });
474
+ chmodSync(stateRoot, 0o700);
475
+ writeFileSync(path, `${token}\n`, { mode: 0o600 });
476
+ chmodSync(path, 0o600);
477
+ return token;
478
+ }
479
+ export function tokenMatches(expected, presented) {
480
+ if (!presented)
481
+ return false;
482
+ const a = Buffer.from(expected);
483
+ const b = Buffer.from(presented);
484
+ if (a.length !== b.length)
485
+ return false;
486
+ return timingSafeEqual(a, b);
487
+ }
488
+ function checkedUrl(raw, name, requireOrigin, allowQuery = false) {
489
+ let url;
490
+ try {
491
+ url = new URL(raw);
492
+ }
493
+ catch {
494
+ throw new OidcConfigurationError(`${name} must be an absolute URL`);
495
+ }
496
+ if (url.username || url.password || (!allowQuery && url.search) || url.hash) {
497
+ throw new OidcConfigurationError(`${name} must not contain credentials${allowQuery ? " or a fragment" : ", a query or a fragment"}`);
498
+ }
499
+ if (url.protocol !== "https:" && !(url.protocol === "http:" && localHostname(url.hostname))) {
500
+ throw new OidcConfigurationError(`${name} must use HTTPS (HTTP is allowed only on localhost)`);
501
+ }
502
+ if (requireOrigin && url.pathname !== "/") {
503
+ throw new OidcConfigurationError(`${name} must be an origin without a path`);
504
+ }
505
+ return url;
506
+ }
507
+ function localHostname(hostname) {
508
+ return hostname === "localhost" || hostname === "127.0.0.1" || hostname === "[::1]" || hostname === "::1";
509
+ }
510
+ function withoutTrailingSlash(value) {
511
+ return value.endsWith("/") ? value.slice(0, -1) : value;
512
+ }
513
+ function validateDiscovery(config, discovery) {
514
+ if (discovery.issuer !== config.issuer) {
515
+ throw new OidcConfigurationError("OIDC discovery issuer does not exactly match FLOW_OIDC_ISSUER");
516
+ }
517
+ if (discovery.response_types_supported && !discovery.response_types_supported.includes("code")) {
518
+ throw new OidcConfigurationError("OIDC provider does not advertise the authorization-code flow");
519
+ }
520
+ if (!discovery.code_challenge_methods_supported?.includes("S256")) {
521
+ throw new OidcConfigurationError("OIDC provider does not advertise S256 PKCE");
522
+ }
523
+ if (!discovery.id_token_signing_alg_values_supported?.some((alg) => alg !== "none")) {
524
+ throw new OidcConfigurationError("OIDC provider does not advertise a signing algorithm");
525
+ }
526
+ for (const [name, value] of [
527
+ ["authorization_endpoint", discovery.authorization_endpoint],
528
+ ["token_endpoint", discovery.token_endpoint],
529
+ ["jwks_uri", discovery.jwks_uri],
530
+ ]) {
531
+ if (typeof value !== "string")
532
+ throw new OidcConfigurationError(`OIDC discovery has no ${name}`);
533
+ checkedEndpointUrl(value, `OIDC ${name}`);
534
+ }
535
+ }
536
+ function checkedEndpointUrl(raw, name) {
537
+ return checkedUrl(raw, name, false, true);
538
+ }
539
+ function selectClientAuthentication(secret, discovery) {
540
+ const methods = discovery.token_endpoint_auth_methods_supported ?? ["client_secret_basic"];
541
+ if (methods.includes("client_secret_basic"))
542
+ return oidc.ClientSecretBasic(secret);
543
+ if (methods.includes("client_secret_post"))
544
+ return oidc.ClientSecretPost(secret);
545
+ throw new OidcConfigurationError("OIDC provider does not support client_secret_basic or client_secret_post");
546
+ }
547
+ function safeReturnTo(value, publicAppUrl) {
548
+ if (!value)
549
+ return "/";
550
+ try {
551
+ const url = new URL(value, publicAppUrl);
552
+ if (url.origin !== new URL(publicAppUrl).origin)
553
+ return "/";
554
+ return `${url.pathname}${url.search}${url.hash}`;
555
+ }
556
+ catch {
557
+ return "/";
558
+ }
559
+ }
560
+ function opaqueToken(bytes = 32) {
561
+ return randomBytes(bytes).toString("base64url");
562
+ }
563
+ function cookieValue(header, name) {
564
+ if (!header)
565
+ return undefined;
566
+ for (const pair of header.split(";")) {
567
+ const index = pair.indexOf("=");
568
+ if (index === -1 || pair.slice(0, index).trim() !== name)
569
+ continue;
570
+ const value = pair.slice(index + 1).trim();
571
+ return value || undefined;
572
+ }
573
+ return undefined;
574
+ }
575
+ function tokenExpiry(tokens, claims, now) {
576
+ if (typeof tokens.expires_in === "number" && Number.isFinite(tokens.expires_in) && tokens.expires_in > 0) {
577
+ return now + tokens.expires_in * 1_000;
578
+ }
579
+ if (typeof claims?.exp === "number")
580
+ return claims.exp * 1_000;
581
+ // Some providers omit both values on refresh. Retry later rather than spinning immediately.
582
+ return now + 5 * 60 * 1_000;
583
+ }
584
+ function validStoredSession(value) {
585
+ return typeof value?.id === "string" &&
586
+ typeof value.sub === "string" &&
587
+ typeof value.expiresAt === "number" &&
588
+ typeof value.tokenExpiresAt === "number" &&
589
+ (value.refreshToken === undefined || typeof value.refreshToken === "string");
590
+ }