@astrale-os/cli 0.4.0-alpha.13

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 (219) hide show
  1. package/.check-workspace.cjs +40 -0
  2. package/README.md +151 -0
  3. package/dist/astrale.js +59749 -0
  4. package/package.json +90 -0
  5. package/src/command.ts +40 -0
  6. package/src/commands/__tests__/admin-instance.test.ts +73 -0
  7. package/src/commands/__tests__/auth-login.test.ts +178 -0
  8. package/src/commands/__tests__/auth-token.test.ts +223 -0
  9. package/src/commands/__tests__/call.test.ts +72 -0
  10. package/src/commands/__tests__/domain-list.test.ts +74 -0
  11. package/src/commands/__tests__/help-contract.test.ts +136 -0
  12. package/src/commands/__tests__/install-identity-override.test.ts +65 -0
  13. package/src/commands/__tests__/instance-bookmark.test.ts +101 -0
  14. package/src/commands/__tests__/instance-create-hosts.test.ts +29 -0
  15. package/src/commands/__tests__/instance-list-rows.test.ts +63 -0
  16. package/src/commands/__tests__/logs.test.ts +117 -0
  17. package/src/commands/__tests__/ls.test.ts +25 -0
  18. package/src/commands/__tests__/setup-plan.test.ts +61 -0
  19. package/src/commands/admin/status.ts +61 -0
  20. package/src/commands/admin/use.ts +77 -0
  21. package/src/commands/auth/login.ts +82 -0
  22. package/src/commands/auth/logout.ts +50 -0
  23. package/src/commands/auth/status.ts +86 -0
  24. package/src/commands/auth/token.ts +162 -0
  25. package/src/commands/browser.ts +207 -0
  26. package/src/commands/call.ts +300 -0
  27. package/src/commands/describe.ts +182 -0
  28. package/src/commands/domain/install.ts +420 -0
  29. package/src/commands/domain/list.ts +154 -0
  30. package/src/commands/domain/publish.ts +155 -0
  31. package/src/commands/get.ts +60 -0
  32. package/src/commands/identity/create.ts +26 -0
  33. package/src/commands/identity/delete.ts +18 -0
  34. package/src/commands/identity/export.ts +66 -0
  35. package/src/commands/identity/import.ts +101 -0
  36. package/src/commands/identity/list.ts +56 -0
  37. package/src/commands/identity/register.ts +170 -0
  38. package/src/commands/identity/sync.ts +32 -0
  39. package/src/commands/identity/unsync.ts +24 -0
  40. package/src/commands/identity/use.ts +18 -0
  41. package/src/commands/identity/whoami.ts +34 -0
  42. package/src/commands/idp/add.ts +150 -0
  43. package/src/commands/idp/list.ts +57 -0
  44. package/src/commands/idp/refresh.ts +38 -0
  45. package/src/commands/idp/remove.ts +36 -0
  46. package/src/commands/idp/show.ts +29 -0
  47. package/src/commands/instance/active.ts +64 -0
  48. package/src/commands/instance/bookmark.ts +72 -0
  49. package/src/commands/instance/create.ts +69 -0
  50. package/src/commands/instance/delete.ts +72 -0
  51. package/src/commands/instance/forget.ts +26 -0
  52. package/src/commands/instance/list.ts +149 -0
  53. package/src/commands/instance/status.ts +42 -0
  54. package/src/commands/instance/use.ts +210 -0
  55. package/src/commands/logs.ts +347 -0
  56. package/src/commands/ls.ts +229 -0
  57. package/src/commands/query.ts +32 -0
  58. package/src/commands/setup.ts +54 -0
  59. package/src/commands/status.ts +60 -0
  60. package/src/commands/studio.ts +401 -0
  61. package/src/commands/token.ts +77 -0
  62. package/src/commands/update.ts +267 -0
  63. package/src/commands/use.ts +87 -0
  64. package/src/errors.ts +65 -0
  65. package/src/kernel/__tests__/auth.test.ts +77 -0
  66. package/src/kernel/__tests__/errors.test.ts +43 -0
  67. package/src/kernel/__tests__/remote-routing.test.ts +70 -0
  68. package/src/kernel/auth.ts +234 -0
  69. package/src/kernel/ca-fetch.ts +119 -0
  70. package/src/kernel/client.ts +191 -0
  71. package/src/kernel/errors.ts +280 -0
  72. package/src/kernel/expand.ts +217 -0
  73. package/src/kernel/index.ts +14 -0
  74. package/src/kernel/options.ts +22 -0
  75. package/src/kernel/remote-routing.ts +88 -0
  76. package/src/kernel/run.ts +63 -0
  77. package/src/kernel/types.ts +14 -0
  78. package/src/lib/__tests__/admin-target.test.ts +112 -0
  79. package/src/lib/__tests__/binary.test.ts +56 -0
  80. package/src/lib/__tests__/command-dx.test.ts +58 -0
  81. package/src/lib/__tests__/concurrency.test.ts +62 -0
  82. package/src/lib/__tests__/config.test.ts +53 -0
  83. package/src/lib/__tests__/design.test.ts +99 -0
  84. package/src/lib/__tests__/domain-identity.test.ts +60 -0
  85. package/src/lib/__tests__/format.test.ts +22 -0
  86. package/src/lib/__tests__/fs-atomic.test.ts +104 -0
  87. package/src/lib/__tests__/identity.test.ts +79 -0
  88. package/src/lib/__tests__/idp-session.driver.ts +53 -0
  89. package/src/lib/__tests__/idp-session.test.ts +357 -0
  90. package/src/lib/__tests__/idp.test.ts +385 -0
  91. package/src/lib/__tests__/instance-candidates.test.ts +73 -0
  92. package/src/lib/__tests__/instance-target.test.ts +183 -0
  93. package/src/lib/__tests__/instance.test.ts +136 -0
  94. package/src/lib/__tests__/keys.test.ts +129 -0
  95. package/src/lib/__tests__/local-status.test.ts +202 -0
  96. package/src/lib/__tests__/output.test.ts +150 -0
  97. package/src/lib/__tests__/panel.test.ts +40 -0
  98. package/src/lib/__tests__/port.test.ts +44 -0
  99. package/src/lib/__tests__/prompt.test.ts +25 -0
  100. package/src/lib/__tests__/sdk-deps.test.ts +68 -0
  101. package/src/lib/__tests__/self.test.ts +272 -0
  102. package/src/lib/__tests__/studio-server-deps.test.ts +74 -0
  103. package/src/lib/__tests__/table.test.ts +53 -0
  104. package/src/lib/__tests__/update.test.ts +246 -0
  105. package/src/lib/__tests__/use-target.test.ts +56 -0
  106. package/src/lib/__tests__/validation.test.ts +34 -0
  107. package/src/lib/admin-domain.ts +25 -0
  108. package/src/lib/admin-instance.ts +26 -0
  109. package/src/lib/admin-target.ts +217 -0
  110. package/src/lib/binary.ts +131 -0
  111. package/src/lib/browser.ts +150 -0
  112. package/src/lib/command-dx.ts +161 -0
  113. package/src/lib/concurrency.ts +31 -0
  114. package/src/lib/config.ts +45 -0
  115. package/src/lib/domain-identity.ts +49 -0
  116. package/src/lib/env.ts +49 -0
  117. package/src/lib/format.ts +4 -0
  118. package/src/lib/fs-atomic.ts +126 -0
  119. package/src/lib/identity.ts +256 -0
  120. package/src/lib/idp-session.ts +134 -0
  121. package/src/lib/idp.ts +876 -0
  122. package/src/lib/instance-candidates.ts +49 -0
  123. package/src/lib/instance-target.ts +182 -0
  124. package/src/lib/instance.ts +395 -0
  125. package/src/lib/keys.ts +294 -0
  126. package/src/lib/local-status.ts +152 -0
  127. package/src/lib/log.ts +116 -0
  128. package/src/lib/login-flow.ts +164 -0
  129. package/src/lib/meta.ts +86 -0
  130. package/src/lib/output.ts +222 -0
  131. package/src/lib/panel.ts +61 -0
  132. package/src/lib/paths.ts +11 -0
  133. package/src/lib/port.ts +41 -0
  134. package/src/lib/proc.ts +82 -0
  135. package/src/lib/prompt.ts +136 -0
  136. package/src/lib/provision-instance.ts +170 -0
  137. package/src/lib/sdk-deps.ts +104 -0
  138. package/src/lib/self.ts +166 -0
  139. package/src/lib/skills.ts +171 -0
  140. package/src/lib/table.ts +62 -0
  141. package/src/lib/update.ts +315 -0
  142. package/src/lib/use-target.ts +24 -0
  143. package/src/lib/validation.ts +59 -0
  144. package/src/program.ts +200 -0
  145. package/src/registry.ts +59 -0
  146. package/src/setup/__tests__/util.test.ts +29 -0
  147. package/src/setup/engine.ts +83 -0
  148. package/src/setup/render.ts +109 -0
  149. package/src/setup/steps/admin.ts +78 -0
  150. package/src/setup/steps/agent-browser.ts +81 -0
  151. package/src/setup/steps/auth.ts +54 -0
  152. package/src/setup/steps/domain.ts +68 -0
  153. package/src/setup/steps/index.ts +18 -0
  154. package/src/setup/steps/instance.ts +119 -0
  155. package/src/setup/steps/skills-bridge.ts +70 -0
  156. package/src/setup/steps/skills.ts +59 -0
  157. package/src/setup/types.ts +61 -0
  158. package/src/setup/util.ts +34 -0
  159. package/src/test-utils.ts +18 -0
  160. package/studio/client/dist/assets/index-DOwzZAEK.css +1 -0
  161. package/studio/client/dist/assets/index-wtU0Zxhy.js +183 -0
  162. package/studio/client/dist/index.html +13 -0
  163. package/studio/package.json +62 -0
  164. package/studio/server/agent/ask.ts +68 -0
  165. package/studio/server/agent/bridge-mcp.ts +182 -0
  166. package/studio/server/agent/bridge.ts +188 -0
  167. package/studio/server/agent/claude.ts +666 -0
  168. package/studio/server/agent/mock.ts +186 -0
  169. package/studio/server/agent/prompt.ts +202 -0
  170. package/studio/server/agent/registry.ts +29 -0
  171. package/studio/server/agent/runner.ts +484 -0
  172. package/studio/server/agent/schema-map.ts +112 -0
  173. package/studio/server/agent/types.ts +120 -0
  174. package/studio/server/api.ts +574 -0
  175. package/studio/server/cache.ts +138 -0
  176. package/studio/server/detect.ts +81 -0
  177. package/studio/server/domain.ts +70 -0
  178. package/studio/server/index.ts +136 -0
  179. package/studio/server/introspect/anatomy-extras.ts +398 -0
  180. package/studio/server/introspect/anatomy.ts +108 -0
  181. package/studio/server/introspect/bundle.ts +57 -0
  182. package/studio/server/introspect/core-extractor.ts +119 -0
  183. package/studio/server/introspect/core.ts +44 -0
  184. package/studio/server/introspect/diff.ts +133 -0
  185. package/studio/server/introspect/extractor.ts +102 -0
  186. package/studio/server/introspect/hash.ts +21 -0
  187. package/studio/server/introspect/overlay-tsmorph.ts +874 -0
  188. package/studio/server/introspect/overlay.ts +57 -0
  189. package/studio/server/introspect/runtime.ts +99 -0
  190. package/studio/server/introspect/schema-refs.ts +46 -0
  191. package/studio/server/lifecycle.ts +38 -0
  192. package/studio/server/sse.ts +57 -0
  193. package/studio/server/state/baseline.ts +211 -0
  194. package/studio/server/state/catalog.ts +117 -0
  195. package/studio/server/state/comments.ts +321 -0
  196. package/studio/server/state/context.ts +167 -0
  197. package/studio/server/state/copy.ts +156 -0
  198. package/studio/server/state/create.ts +156 -0
  199. package/studio/server/state/documents.ts +70 -0
  200. package/studio/server/state/env.ts +161 -0
  201. package/studio/server/state/git.ts +75 -0
  202. package/studio/server/state/handoff.ts +55 -0
  203. package/studio/server/state/harness-gateway.ts +181 -0
  204. package/studio/server/state/harness-token.ts +0 -0
  205. package/studio/server/state/instance.ts +244 -0
  206. package/studio/server/state/integrations.ts +55 -0
  207. package/studio/server/state/layout.ts +55 -0
  208. package/studio/server/state/settings.ts +39 -0
  209. package/studio/server/state/store.ts +97 -0
  210. package/studio/server/state/updates.ts +63 -0
  211. package/studio/server/state/usage.ts +37 -0
  212. package/studio/server/state/views.ts +138 -0
  213. package/studio/server/state/visibility.ts +33 -0
  214. package/studio/server/watch.ts +81 -0
  215. package/studio/server/workspace-state.ts +26 -0
  216. package/studio/server/workspace-watch.ts +101 -0
  217. package/studio/shared/types.ts +873 -0
  218. package/studio/tsconfig.json +23 -0
  219. package/tsconfig.json +14 -0
@@ -0,0 +1,234 @@
1
+ import type { AstraleConfig } from '../lib/config'
2
+
3
+ import { AuthError } from '../errors'
4
+ import { getDefault, getIdentity, type Identity } from '../lib/identity'
5
+ import {
6
+ accessTokenForAudience,
7
+ classifyRefreshFailure,
8
+ IdpAudienceMismatchError,
9
+ } from '../lib/idp'
10
+ import {
11
+ ensureFreshSession,
12
+ IdpSessionMissingError,
13
+ IdpSessionNoRefreshTokenError,
14
+ } from '../lib/idp-session'
15
+ import { signAs } from '../lib/keys'
16
+ import { KEYS_DIR } from '../lib/paths'
17
+
18
+ export type KeyIdentityAuthOptions = {
19
+ issuer: string
20
+ subject?: string
21
+ audience: string
22
+ }
23
+
24
+ /**
25
+ * Resolve a signed JWT credential from CLI options.
26
+ *
27
+ * The **audience** is passed in explicitly by the caller because transport URL
28
+ * and kernel issuer can differ for remote deployments.
29
+ *
30
+ * Three cases, in order of priority:
31
+ * 1. `opts.creds` — pre-signed credential, returned as-is.
32
+ * 2. `opts.as` — sign as a named local identity.
33
+ * 3. Default — sign as the active local identity. If the identity has a
34
+ * registration for the target instance, use that target-issued `(iss, sub)`.
35
+ */
36
+ export async function resolveCredential(
37
+ opts: { as?: string; creds?: string; defaultIdentity?: string },
38
+ config: AstraleConfig,
39
+ audience: string = config.issuer,
40
+ instanceSlug?: string,
41
+ ): Promise<string> {
42
+ if (opts.creds) return opts.creds
43
+ // Track the resolved identity so the catch block can tailor its hint: an
44
+ // IdP-backed identity whose session lapsed needs `astrale auth login`, not
45
+ // the `astrale identity create` keypair hint that suits local key identities.
46
+ let resolvedIdentity: Identity | undefined
47
+ let resolvedName: string | undefined
48
+ try {
49
+ const identityName = opts.as ?? opts.defaultIdentity
50
+ // Explicit `--as` wins: sign with that identity's key. When the identity
51
+ // has a registration record for the targeted instance (populated by
52
+ // `astrale identity register`), use the kernel-derived `(iss, sub)` so the
53
+ // JWT matches what the kernel published under its issuer store.
54
+ if (identityName) {
55
+ const identity = await getIdentity(identityName)
56
+ resolvedIdentity = identity
57
+ resolvedName = identityName
58
+ if ((identity.source ?? 'key') === 'idp')
59
+ return await resolveIdpAccessToken(identityName, identity, audience)
60
+ return await signAs(
61
+ identity.subject,
62
+ KEYS_DIR,
63
+ resolveKeyIdentityAuthOptions(identity, config, audience, instanceSlug),
64
+ )
65
+ }
66
+
67
+ const identity = await getDefault()
68
+ resolvedIdentity = identity
69
+ resolvedName = identity.name
70
+ if ((identity.source ?? 'key') === 'idp') {
71
+ return await resolveIdpAccessToken(identity.name, identity, audience)
72
+ }
73
+
74
+ return await signAs(
75
+ identity.subject,
76
+ KEYS_DIR,
77
+ resolveKeyIdentityAuthOptions(identity, config, audience, instanceSlug),
78
+ )
79
+ } catch (e) {
80
+ const message = e instanceof Error ? e.message : 'Failed to resolve credentials'
81
+ const hint = resolveCredentialHint(opts, resolvedIdentity, resolvedName, e)
82
+ throw new AuthError(message, hint)
83
+ }
84
+ }
85
+
86
+ function resolveCredentialHint(
87
+ opts: { as?: string; defaultIdentity?: string },
88
+ identity: Identity | undefined,
89
+ name: string | undefined,
90
+ error?: unknown,
91
+ ): string {
92
+ // Audience mismatch: the IdP minted a token for a different `aud` than the
93
+ // target requires (e.g. WorkOS stamps a fixed API audience and ignores the
94
+ // requested one). Re-login mints the *same* aud again, so don't suggest it —
95
+ // point at targeting an instance whose audience matches what the IdP issues.
96
+ if (error instanceof IdpAudienceMismatchError) {
97
+ return error.actual
98
+ ? `The IdP issues tokens for audience ${error.actual}, not the target's ${error.requested}. Target an instance whose URL/issuer is ${error.actual} (re-login won't change the audience).`
99
+ : `The IdP did not mint a token for the target audience ${error.requested}, and re-login won't change it. Target an instance whose audience the IdP issues, or reconfigure the bookmark/IdP.`
100
+ }
101
+ // Org-membership rejection: the session is healthy; the org we scoped the
102
+ // token to doesn't hold this user. Re-login can never fix it.
103
+ if (error instanceof IdpOrgMembershipError) {
104
+ return 'This instance might belong to a different account.'
105
+ }
106
+ // Transient IdP outage: the cached session is still valid — retrying is the
107
+ // fix, not re-login.
108
+ if (error instanceof IdpRefreshTransientError) {
109
+ return 'The IdP could not be reached. Check the network and retry — the cached session is likely still valid.'
110
+ }
111
+ // IdP-backed identities fail when the cached session expires or the upstream
112
+ // session is terminated (e.g. WorkOS "Session has already ended"). Re-login,
113
+ // don't recreate keys.
114
+ if (identity && (identity.source ?? 'key') === 'idp' && name) {
115
+ const idpFlag = identity.idp ? ` --idp ${identity.idp}` : ''
116
+ return `IdP session for "${name}" has expired. Run: astrale auth login --name ${name}${idpFlag}`
117
+ }
118
+ if (opts.as) {
119
+ return 'Check identity name. Available identities: astrale identity list'
120
+ }
121
+ if (opts.defaultIdentity) {
122
+ return `Check bookmark default identity "${opts.defaultIdentity}". Available identities: astrale identity list`
123
+ }
124
+ return 'Run `astrale identity create <name>` to set up keys'
125
+ }
126
+
127
+ export function resolveKeyIdentityAuthOptions(
128
+ identity: Identity,
129
+ config: AstraleConfig,
130
+ audience: string = config.issuer,
131
+ instanceSlug?: string,
132
+ ): KeyIdentityAuthOptions {
133
+ const registration = instanceSlug ? identity.registrations?.[instanceSlug] : undefined
134
+ return {
135
+ issuer:
136
+ registration?.iss ?? identity.issuer ?? systemIdentityIssuer(identity, audience, config),
137
+ subject: registration?.sub,
138
+ audience,
139
+ }
140
+ }
141
+
142
+ function systemIdentityIssuer(identity: Identity, audience: string, config: AstraleConfig): string {
143
+ // Imported kernel bootstrap keys are subject=system and are published by the
144
+ // target kernel's JWKS. Without a stored issuer, signing them as the
145
+ // placeholder CLI issuer makes the kernel try OIDC discovery for a
146
+ // non-resolving host — use the audience (the target kernel) instead.
147
+ return identity.subject === 'system' ? audience : config.issuer
148
+ }
149
+
150
+ async function resolveIdpAccessToken(
151
+ identityName: string,
152
+ identity: Identity,
153
+ audience: string,
154
+ ): Promise<string> {
155
+ let resolved
156
+ try {
157
+ resolved = await ensureFreshSession(identityName, { audience })
158
+ } catch (e) {
159
+ if (e instanceof IdpSessionMissingError) {
160
+ throw new Error(
161
+ `No cached IdP session for "${identityName}". Run: astrale auth login --idp ${identity.idp ?? '<idp>'}`,
162
+ )
163
+ }
164
+ if (e instanceof IdpSessionNoRefreshTokenError) {
165
+ throw new Error(wrongAudienceHint(identityName, identity, audience))
166
+ }
167
+ // An audience mismatch means the session is healthy but the IdP won't
168
+ // mint this audience — re-login is futile, so propagate it verbatim for
169
+ // the hint logic to handle.
170
+ if (e instanceof IdpAudienceMismatchError) throw e
171
+ throw refreshFailureError(identityName, identity, e)
172
+ }
173
+
174
+ const token = accessTokenForAudience(resolved, audience)
175
+ if (!token) {
176
+ throw new Error(
177
+ `IdP token for "${identityName}" was not minted for target audience ${audience}. ` +
178
+ `Run: astrale auth login --name ${identityName} --idp ${identity.idp ?? '<idp>'} --audience ${audience}`,
179
+ )
180
+ }
181
+
182
+ return token
183
+ }
184
+
185
+ /** A refresh attempt failed for a reason that re-login will NOT fix. */
186
+ export class IdpRefreshTransientError extends Error {
187
+ constructor(message: string) {
188
+ super(message)
189
+ this.name = 'IdpRefreshTransientError'
190
+ }
191
+ }
192
+
193
+ /** The IdP refused to scope the session to the target's organization. */
194
+ export class IdpOrgMembershipError extends Error {
195
+ constructor(message: string) {
196
+ super(message)
197
+ this.name = 'IdpOrgMembershipError'
198
+ }
199
+ }
200
+
201
+ function refreshFailureError(identityName: string, identity: Identity, cause: unknown): Error {
202
+ const reason = cause instanceof Error ? cause.message : String(cause)
203
+ const idpFlag = identity.idp ? ` --idp ${identity.idp}` : ''
204
+ // Only a definitively dead grant (invalid_grant: WorkOS idle/absolute
205
+ // timeout, logout elsewhere, reuse-detection revocation) warrants a
206
+ // re-login. Network failures and IdP 5xx leave the cached session valid —
207
+ // telling the user to re-login for those would burn a perfectly good
208
+ // session.
209
+ switch (classifyRefreshFailure(cause)) {
210
+ case 'transient':
211
+ return new IdpRefreshTransientError(
212
+ `Could not reach the IdP to refresh the session for "${identityName}" (${reason}). ` +
213
+ 'The cached session is likely still valid — retry the command.',
214
+ )
215
+ case 'org-rejected':
216
+ // Healthy session, wrong org — re-login can never fix it.
217
+ return new IdpOrgMembershipError(
218
+ `The IdP refused to scope "${identityName}" to this instance's organization (${reason}).`,
219
+ )
220
+ default:
221
+ return new Error(
222
+ `IdP session for "${identityName}" could not be refreshed (${reason}). ` +
223
+ `The cached session has expired or ended — run: astrale auth login --name ${identityName}${idpFlag}`,
224
+ )
225
+ }
226
+ }
227
+
228
+ function wrongAudienceHint(identityName: string, identity: Identity, audience: string): string {
229
+ return (
230
+ `IdP token for "${identityName}" was not minted for target audience ${audience}, ` +
231
+ 'and the cached session cannot be refreshed. ' +
232
+ `Run: astrale auth login --name ${identityName} --idp ${identity.idp ?? '<idp>'} --audience ${audience}`
233
+ )
234
+ }
@@ -0,0 +1,119 @@
1
+ import type { IncomingHttpHeaders, request as httpRequest } from 'node:http'
2
+
3
+ import { Buffer } from 'node:buffer'
4
+ import { readFileSync } from 'node:fs'
5
+ import { request as httpsRequest } from 'node:https'
6
+
7
+ export function fetchWithCaFile(
8
+ caFile: string,
9
+ fallback: typeof fetch = globalThis.fetch,
10
+ ): typeof fetch {
11
+ const ca = readFileSync(caFile)
12
+ const fallbackFetch = fallback.bind(globalThis)
13
+
14
+ return (async (input: RequestInfo | URL, init?: RequestInit): Promise<Response> => {
15
+ const url = requestUrl(input)
16
+ if (url.protocol !== 'https:') return fallbackFetch(input, init)
17
+ return fetchWithNode(url, init, ca)
18
+ }) as typeof fetch
19
+ }
20
+
21
+ function requestUrl(input: RequestInfo | URL): URL {
22
+ if (input instanceof URL) return input
23
+ if (typeof input === 'string') return new URL(input)
24
+ return new URL(input.url)
25
+ }
26
+
27
+ function fetchWithNode(url: URL, init: RequestInit | undefined, ca: Buffer): Promise<Response> {
28
+ return new Promise((resolve, reject) => {
29
+ const headers = headersInitToRecord(init?.headers)
30
+ const request = httpsRequest(
31
+ url,
32
+ {
33
+ method: init?.method ?? 'GET',
34
+ headers,
35
+ ca,
36
+ },
37
+ (response) => {
38
+ const chunks: Buffer[] = []
39
+ response.on('data', (chunk) =>
40
+ chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk)),
41
+ )
42
+ response.on('end', () => {
43
+ resolve(
44
+ new Response(Buffer.concat(chunks), {
45
+ status: response.statusCode ?? 0,
46
+ statusText: response.statusMessage,
47
+ headers: responseHeaders(response.headers),
48
+ }),
49
+ )
50
+ })
51
+ },
52
+ )
53
+
54
+ request.on('error', reject)
55
+ if (init?.signal) {
56
+ if (init.signal.aborted)
57
+ request.destroy(new DOMException('The operation was aborted.', 'AbortError'))
58
+ init.signal.addEventListener(
59
+ 'abort',
60
+ () => request.destroy(new DOMException('The operation was aborted.', 'AbortError')),
61
+ { once: true },
62
+ )
63
+ }
64
+
65
+ writeBody(request, init?.body)
66
+ .then(() => request.end())
67
+ .catch((error) => request.destroy(error))
68
+ })
69
+ }
70
+
71
+ async function writeBody(
72
+ request: ReturnType<typeof httpRequest>,
73
+ body: BodyInit | null | undefined,
74
+ ): Promise<void> {
75
+ if (body === undefined || body === null) return
76
+ if (typeof body === 'string') {
77
+ request.write(body)
78
+ return
79
+ }
80
+ if (body instanceof Uint8Array) {
81
+ request.write(body)
82
+ return
83
+ }
84
+ if (body instanceof ArrayBuffer) {
85
+ request.write(Buffer.from(body))
86
+ return
87
+ }
88
+ if (body instanceof Blob) {
89
+ request.write(Buffer.from(await body.arrayBuffer()))
90
+ return
91
+ }
92
+ throw new Error(`Unsupported request body type for CA-backed fetch`)
93
+ }
94
+
95
+ function headersInitToRecord(headers: HeadersInit | undefined): Record<string, string> {
96
+ if (!headers) return {}
97
+ if (headers instanceof Headers) {
98
+ const out: Record<string, string> = {}
99
+ headers.forEach((value, key) => {
100
+ out[key] = value
101
+ })
102
+ return out
103
+ }
104
+ if (Array.isArray(headers)) return Object.fromEntries(headers.map(([key, value]) => [key, value]))
105
+ return Object.fromEntries(Object.entries(headers).map(([key, value]) => [key, String(value)]))
106
+ }
107
+
108
+ function responseHeaders(headers: IncomingHttpHeaders): Headers {
109
+ const out = new Headers()
110
+ for (const [key, value] of Object.entries(headers)) {
111
+ if (value === undefined) continue
112
+ if (Array.isArray(value)) {
113
+ for (const entry of value) out.append(key, entry)
114
+ } else {
115
+ out.set(key, value)
116
+ }
117
+ }
118
+ return out
119
+ }
@@ -0,0 +1,191 @@
1
+ import { KernelClient, type FnMap } from '@astrale-os/kernel-client'
2
+ import { ClientSession } from '@astrale-os/kernel-client/session'
3
+
4
+ import type { AdminTargetCommandOpts } from '../lib/admin-target'
5
+ import type { KernelCommandOpts } from './types'
6
+
7
+ import { AstraleError } from '../errors'
8
+ import { ADMIN_INSTANCE, type InstanceInfo } from '../lib/admin-instance'
9
+ import { readConfig } from '../lib/config'
10
+ import { resolveInstanceTarget, type ResolvedInstanceTarget } from '../lib/instance-target'
11
+ import { resolveCredential } from './auth'
12
+ import { fetchWithCaFile } from './ca-fetch'
13
+ import { mintRemoteCredential } from './remote-routing'
14
+
15
+ const DEFAULT_TIMEOUT_MS = 30_000
16
+
17
+ export type ClientContext = {
18
+ /** High-level call surface — bound to `credential` via ClientSession.identity. */
19
+ client: ClientSession<FnMap>
20
+ credential: string
21
+ url: string
22
+ config: Awaited<ReturnType<typeof readConfig>>
23
+ }
24
+
25
+ type ResolvedKernelTarget = {
26
+ url: string
27
+ audience: string
28
+ slug?: string
29
+ defaultIdentity?: string
30
+ caFile?: string
31
+ }
32
+
33
+ /**
34
+ * Connect to a kernel instance, run `fn`, then disconnect.
35
+ * The new client is lazy: construction does no I/O. We only need to
36
+ * release sockets on the way out.
37
+ */
38
+ export async function withKernelClient<T>(
39
+ opts: KernelCommandOpts,
40
+ fn: (ctx: ClientContext) => Promise<T>,
41
+ ): Promise<T> {
42
+ const config = await readConfig()
43
+ // Ad-hoc `--url` — unknown kernel. Stamp the URL itself as audience,
44
+ // no slug for per-instance signing.
45
+ let target: ResolvedKernelTarget
46
+ if (opts.url && !opts.instance) {
47
+ const resolved = await resolveInstanceTarget(
48
+ { source: 'url', url: opts.url },
49
+ { config, admin: adminLookupOpts(opts) },
50
+ )
51
+ target = resolvedToKernelTarget(resolved)
52
+ } else {
53
+ const resolved = await resolveInstanceTarget(
54
+ opts.instance ? { source: 'name', name: opts.instance } : { source: 'active' },
55
+ {
56
+ config,
57
+ admin: adminLookupOpts(opts),
58
+ managed: (slug) => lookupManagedInstance(slug, opts),
59
+ },
60
+ )
61
+ target = resolvedToKernelTarget(resolved, opts.url)
62
+ }
63
+
64
+ return withResolvedKernelClient(opts, config, target, fn)
65
+ }
66
+
67
+ async function lookupManagedInstance(slug: string, opts: KernelCommandOpts): Promise<InstanceInfo> {
68
+ return await withAdminKernelClient(
69
+ adminLookupOpts(opts),
70
+ async (ctx) => (await ctx.client.call(`${ADMIN_INSTANCE}/info`, { id: slug })) as InstanceInfo,
71
+ )
72
+ }
73
+
74
+ function adminLookupOpts(opts: KernelCommandOpts): KernelCommandOpts & AdminTargetCommandOpts {
75
+ return {
76
+ as: opts.as,
77
+ creds: opts.creds,
78
+ timeout: opts.timeout,
79
+ debug: opts.debug,
80
+ }
81
+ }
82
+
83
+ function resolvedToKernelTarget(
84
+ target: ResolvedInstanceTarget,
85
+ urlOverride?: string,
86
+ ): ResolvedKernelTarget {
87
+ return {
88
+ url: urlOverride ?? target.url,
89
+ audience: target.issuer,
90
+ slug: target.name,
91
+ defaultIdentity: target.defaultIdentity,
92
+ caFile: target.caFile,
93
+ }
94
+ }
95
+
96
+ export async function withAdminKernelClient<T>(
97
+ opts: KernelCommandOpts & AdminTargetCommandOpts,
98
+ fn: (ctx: ClientContext) => Promise<T>,
99
+ ): Promise<T> {
100
+ const config = await readConfig()
101
+ const target = await resolveInstanceTarget({ source: 'admin' }, { config, admin: opts })
102
+ return withResolvedKernelClient(
103
+ opts,
104
+ config,
105
+ {
106
+ url: target.url,
107
+ audience: target.issuer,
108
+ slug: target.name,
109
+ defaultIdentity: target.defaultIdentity,
110
+ caFile: target.caFile,
111
+ },
112
+ fn,
113
+ )
114
+ }
115
+
116
+ async function withResolvedKernelClient<T>(
117
+ opts: KernelCommandOpts,
118
+ config: Awaited<ReturnType<typeof readConfig>>,
119
+ target: ResolvedKernelTarget,
120
+ fn: (ctx: ClientContext) => Promise<T>,
121
+ ): Promise<T> {
122
+ const credential = await resolveCredential(
123
+ { ...opts, defaultIdentity: target.defaultIdentity },
124
+ config,
125
+ target.audience,
126
+ target.slug,
127
+ )
128
+
129
+ // CLI is short-lived and one-shot per command. Skip the WS upgrade
130
+ // (saves up to 5s on hangs) and disable HTTP retries (saves ~7s of
131
+ // exponential backoff on ECONNREFUSED / 5xx). The user can re-run.
132
+ const requestTimeout = resolveTimeoutMs(opts.timeout)
133
+ const fetchImpl = target.caFile ? fetchWithCaFile(target.caFile) : undefined
134
+ // The delegation mint references `client` lazily — it only fires on a cache
135
+ // miss during an actual remote call, long after this binding is initialised,
136
+ // so the self-reference inside the closure is safe.
137
+ const client: ClientSession<FnMap> = new ClientSession<FnMap>({
138
+ default: target.url,
139
+ identity: credential,
140
+ // Remote-bound functions redirect to a worker that verifies `aud` against
141
+ // its own identity. The session follows the redirect and mints a worker-
142
+ // scoped delegation here, for the audience the kernel carries on the
143
+ // redirect (`redirection.iss`, surfaced by the default iss-aware policy).
144
+ delegation: {
145
+ mint: async (audience) => ({
146
+ credential: await mintRemoteCredential(client, audience, credential),
147
+ ttl: 3600,
148
+ }),
149
+ ttl: 3600,
150
+ },
151
+ pool: {
152
+ clientFactory: (u) =>
153
+ new KernelClient<FnMap>({
154
+ url: u,
155
+ requestTimeout,
156
+ defaultTransport: 'http',
157
+ retry: { maxAttempts: 1 },
158
+ ...(fetchImpl ? { fetch: fetchImpl } : {}),
159
+ }),
160
+ },
161
+ })
162
+ await client.ready()
163
+
164
+ try {
165
+ return await fn({ client, credential, url: target.url, config })
166
+ } catch (error) {
167
+ // Attach url so formatKernelError can display it in connection errors
168
+ if (error instanceof Error) (error as Error & { url?: string }).url = target.url
169
+ throw error
170
+ } finally {
171
+ client.disconnect()
172
+ }
173
+ }
174
+
175
+ function resolveTimeoutMs(raw: string | undefined): number {
176
+ if (raw === undefined) return DEFAULT_TIMEOUT_MS
177
+ if (!/^\d+$/.test(raw)) {
178
+ throw new AstraleError(
179
+ 'INVALID_FLAG',
180
+ `Invalid --timeout value "${raw}" — expected a positive integer (milliseconds)`,
181
+ )
182
+ }
183
+ const n = Number.parseInt(raw, 10)
184
+ if (!Number.isFinite(n) || n <= 0) {
185
+ throw new AstraleError(
186
+ 'INVALID_FLAG',
187
+ `Invalid --timeout value "${raw}" — must be a positive integer`,
188
+ )
189
+ }
190
+ return n
191
+ }