@astrale-os/cli 1.0.0-beta.28 → 1.0.0-beta.29

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 (50) hide show
  1. package/README.md +33 -0
  2. package/dist/astrale.js +1629 -1088
  3. package/dist/public/connect-core.js +86 -17
  4. package/dist/public/keys/index.js +69 -2
  5. package/dist/public/paths/index.js +67 -0
  6. package/dist/types/connection/session.d.ts +2 -2
  7. package/dist/types/lib/config.d.ts +6 -0
  8. package/dist/types/state/exchange-credentials.d.ts +6 -2
  9. package/dist/types/state/files.d.ts +2 -0
  10. package/dist/types/state/index.d.ts +3 -2
  11. package/dist/types/state/paths.d.ts +2 -0
  12. package/dist/types/state/session-routes.d.ts +10 -0
  13. package/package.json +2 -2
  14. package/src/commands/auth/logout.ts +2 -1
  15. package/src/commands/browser.ts +29 -0
  16. package/src/connection/.spec/architecture.md +9 -1
  17. package/src/connection/__tests__/auth.test.ts +1 -0
  18. package/src/connection/__tests__/credential.test.ts +1 -0
  19. package/src/connection/__tests__/exchange.test.ts +34 -10
  20. package/src/connection/__tests__/session.test.ts +5 -1
  21. package/src/connection/__tests__/target.test.ts +1 -0
  22. package/src/connection/exchange.ts +63 -38
  23. package/src/connection/session.ts +8 -1
  24. package/src/identity/__tests__/fixtures/registry-journey.ts +13 -1
  25. package/src/identity/__tests__/registry.test.ts +4 -0
  26. package/src/identity/registry.ts +2 -0
  27. package/src/lib/__tests__/browser-retention.test.ts +212 -0
  28. package/src/lib/__tests__/config.test.ts +27 -0
  29. package/src/lib/browser-retention.ts +210 -0
  30. package/src/lib/config.ts +12 -1
  31. package/src/state/.spec/api.d.ts +21 -2
  32. package/src/state/.spec/architecture.md +18 -4
  33. package/src/state/.spec/layout.ts +1 -0
  34. package/src/state/__tests__/exchange-credentials.test.ts +88 -42
  35. package/src/state/__tests__/files.test.ts +24 -1
  36. package/src/state/__tests__/fixtures/session-route-process.ts +93 -0
  37. package/src/state/__tests__/paths.test.ts +1 -0
  38. package/src/state/__tests__/session-routes.test.ts +138 -0
  39. package/src/state/exchange-credentials.ts +22 -9
  40. package/src/state/files.ts +41 -0
  41. package/src/state/index.ts +3 -1
  42. package/src/state/paths.ts +3 -0
  43. package/src/state/session-routes.ts +34 -0
  44. package/src/telemetry/__tests__/analyze-log.test.ts +38 -0
  45. package/src/telemetry/__tests__/retention.test.ts +88 -1
  46. package/src/telemetry/analyze.ts +24 -2
  47. package/src/telemetry/retention.ts +53 -6
  48. package/src/telemetry/store.ts +5 -0
  49. package/studio/package.json +1 -1
  50. package/viewer/dist/main.js +28 -28
@@ -0,0 +1,210 @@
1
+ /**
2
+ * Browser-profile retention.
3
+ *
4
+ * `astrale browser` keeps one persistent Chromium profile per host so the
5
+ * WorkOS cookie survives between runs. That cookie is a few kilobytes;
6
+ * everything Chromium accumulates around it is cache, and it accumulates
7
+ * without limit — a real profile here reached 373 MB, 98% of it cache.
8
+ *
9
+ * Chromium will not bound it for us. `--disk-cache-size` is measurably ignored
10
+ * for a profile's HTTP cache — the largest component by far — so deleting is
11
+ * the only lever. Two rules, cheapest first:
12
+ *
13
+ * 1. A profile untouched for longer than the age bound goes entirely. Its
14
+ * WorkOS cookie has expired anyway, so it holds nothing worth the disk.
15
+ * 2. A surviving profile whose cache exceeds the size bound has its cache
16
+ * directories removed. Cookies, Local Storage, Preferences and Local State
17
+ * are never touched — the whole point of the profile is that the session
18
+ * outlives the sweep.
19
+ *
20
+ * A profile whose SingletonLock names a live process is always left alone:
21
+ * deleting files under a running Chromium is how profiles get corrupted.
22
+ */
23
+ import { readlinkSync } from 'node:fs'
24
+ import { readdir, rm, stat } from 'node:fs/promises'
25
+ import { join } from 'node:path'
26
+
27
+ import { BROWSER_DIR } from './browser'
28
+ import { readConfig } from './config'
29
+
30
+ /** Reconstructible directories, relative to a profile root. Everything here can
31
+ * be deleted with no user-visible consequence beyond a colder first load. */
32
+ const CACHE_PATHS = [
33
+ 'Default/Cache',
34
+ 'Default/Code Cache',
35
+ 'Default/GPUCache',
36
+ 'Default/DawnWebGPUCache',
37
+ 'Default/DawnGraphiteCache',
38
+ 'Default/Service Worker/CacheStorage',
39
+ 'Default/Service Worker/ScriptCache',
40
+ 'GraphiteDawnCache',
41
+ 'GPUPersistentCache',
42
+ 'GrShaderCache',
43
+ 'ShaderCache',
44
+ 'component_crx_cache',
45
+ 'extensions_crx_cache',
46
+ ] as const
47
+
48
+ export const DEFAULT_MAX_CACHE_BYTES = 50 * 1024 * 1024
49
+ export const DEFAULT_MAX_PROFILE_AGE_DAYS = 30
50
+
51
+ export type BrowserRetentionBudget = {
52
+ /** Cap on one profile's cache directories, not on the profile as a whole. */
53
+ maxCacheBytes: number
54
+ maxProfileAgeMs: number
55
+ }
56
+
57
+ export type BrowserSweepResult = {
58
+ /** Profiles deleted outright (dormant past the age bound). */
59
+ removed: string[]
60
+ /** Profiles kept, cache emptied (over the size bound). */
61
+ purged: string[]
62
+ /** Profiles a live browser was holding — left untouched. */
63
+ skipped: string[]
64
+ bytesFreed: number
65
+ }
66
+
67
+ const EMPTY: BrowserSweepResult = { removed: [], purged: [], skipped: [], bytesFreed: 0 }
68
+
69
+ /** First finite, strictly positive candidate; anything else falls through to
70
+ * the next one, and ultimately to the default. A typo must not mean "no cap". */
71
+ function firstPositive(candidates: (number | string | undefined)[]): number | null {
72
+ for (const candidate of candidates) {
73
+ if (candidate === undefined) continue
74
+ const n = typeof candidate === 'string' ? Number(candidate.trim()) : candidate
75
+ if (Number.isFinite(n) && n > 0) return n
76
+ }
77
+ return null
78
+ }
79
+
80
+ /** Resolved budget: env over config over defaults. */
81
+ export async function browserRetentionBudget(): Promise<BrowserRetentionBudget> {
82
+ const browser = (await readConfig().catch(() => null))?.browser
83
+ const bytes =
84
+ firstPositive([process.env.ASTRALE_BROWSER_MAX_CACHE_BYTES, browser?.maxCacheBytes]) ??
85
+ DEFAULT_MAX_CACHE_BYTES
86
+ const days =
87
+ firstPositive([process.env.ASTRALE_BROWSER_MAX_PROFILE_AGE_DAYS, browser?.maxProfileAgeDays]) ??
88
+ DEFAULT_MAX_PROFILE_AGE_DAYS
89
+ return { maxCacheBytes: bytes, maxProfileAgeMs: days * 24 * 60 * 60 * 1000 }
90
+ }
91
+
92
+ /** True when a process with this pid exists. EPERM means it exists but is not
93
+ * ours — still alive, and still a reason not to touch the profile. */
94
+ function isLive(pid: number): boolean {
95
+ try {
96
+ process.kill(pid, 0)
97
+ return true
98
+ } catch (e) {
99
+ return (e as NodeJS.ErrnoException).code === 'EPERM'
100
+ }
101
+ }
102
+
103
+ /**
104
+ * Whether a live browser holds this profile. SingletonLock is a symlink whose
105
+ * target is `<hostname>-<pid>` and which does NOT resolve to a real file, so it
106
+ * must be read with readlink, never stat'ed. A stale lock (dead pid) is not a
107
+ * reason to skip — Chromium leaves those behind after a crash.
108
+ */
109
+ export function heldByLiveBrowser(profileDir: string): boolean {
110
+ let target: string
111
+ try {
112
+ target = readlinkSync(join(profileDir, 'SingletonLock'))
113
+ } catch {
114
+ return false
115
+ }
116
+ const pid = Number(target.slice(target.lastIndexOf('-') + 1))
117
+ return Number.isInteger(pid) && pid > 0 && isLive(pid)
118
+ }
119
+
120
+ /** Bytes under `dir`, or 0 when it is missing or unreadable. */
121
+ async function directoryBytes(dir: string): Promise<number> {
122
+ let entries
123
+ try {
124
+ entries = await readdir(dir, { withFileTypes: true })
125
+ } catch {
126
+ return 0
127
+ }
128
+ let total = 0
129
+ for (const entry of entries) {
130
+ const path = join(dir, entry.name)
131
+ if (entry.isDirectory()) {
132
+ total += await directoryBytes(path)
133
+ } else if (entry.isFile()) {
134
+ try {
135
+ total += (await stat(path)).size
136
+ } catch {
137
+ /* raced away mid-walk */
138
+ }
139
+ }
140
+ }
141
+ return total
142
+ }
143
+
144
+ /** Cumulative size of one profile's cache directories. */
145
+ export async function profileCacheBytes(profileDir: string): Promise<number> {
146
+ let total = 0
147
+ for (const relative of CACHE_PATHS) total += await directoryBytes(join(profileDir, relative))
148
+ return total
149
+ }
150
+
151
+ /** Delete every cache directory of a profile; returns bytes actually freed. */
152
+ async function purgeCache(profileDir: string): Promise<number> {
153
+ const before = await profileCacheBytes(profileDir)
154
+ for (const relative of CACHE_PATHS) {
155
+ await rm(join(profileDir, relative), { recursive: true, force: true }).catch(() => {
156
+ /* best effort — retention must never break the browser command */
157
+ })
158
+ }
159
+ return before - (await profileCacheBytes(profileDir))
160
+ }
161
+
162
+ /**
163
+ * Apply both rules across every profile under `dir`. Never throws: a failed
164
+ * sweep must not stop the user from driving a browser.
165
+ */
166
+ export async function sweepBrowserProfiles(
167
+ options: { dir?: string; budget?: BrowserRetentionBudget; now?: number } = {},
168
+ ): Promise<BrowserSweepResult> {
169
+ const dir = options.dir ?? BROWSER_DIR
170
+ let names: string[]
171
+ try {
172
+ names = (await readdir(dir, { withFileTypes: true }))
173
+ .filter((e) => e.isDirectory())
174
+ .map((e) => e.name)
175
+ } catch {
176
+ return EMPTY
177
+ }
178
+ if (names.length === 0) return EMPTY
179
+
180
+ const budget = options.budget ?? (await browserRetentionBudget())
181
+ const now = options.now ?? Date.now()
182
+ const result: BrowserSweepResult = { removed: [], purged: [], skipped: [], bytesFreed: 0 }
183
+
184
+ for (const name of names) {
185
+ const profileDir = join(dir, name)
186
+ if (heldByLiveBrowser(profileDir)) {
187
+ result.skipped.push(name)
188
+ continue
189
+ }
190
+ try {
191
+ // The profile root's mtime tracks USE, not writes: Chromium rewrites
192
+ // SingletonLock and DevToolsActivePort there on every launch, while cache
193
+ // writes land in subdirectories and leave the root alone.
194
+ const idleMs = now - (await stat(profileDir)).mtime.getTime()
195
+ if (idleMs > budget.maxProfileAgeMs) {
196
+ result.bytesFreed += await directoryBytes(profileDir)
197
+ await rm(profileDir, { recursive: true, force: true })
198
+ result.removed.push(name)
199
+ continue
200
+ }
201
+ if ((await profileCacheBytes(profileDir)) > budget.maxCacheBytes) {
202
+ result.bytesFreed += await purgeCache(profileDir)
203
+ result.purged.push(name)
204
+ }
205
+ } catch {
206
+ /* best effort, per profile — one bad profile must not stop the sweep */
207
+ }
208
+ }
209
+ return result
210
+ }
package/src/lib/config.ts CHANGED
@@ -6,10 +6,21 @@ import { CONFIG_PATH } from '../state/index'
6
6
  import { AdminTargetConfigSchema, DEFAULT_ADMIN_TARGET_CONFIG } from './admin-target'
7
7
  import { log } from './log'
8
8
 
9
+ /** A retention bound, or undefined when absent or nonsensical. A bad value must
10
+ * fall back to the default rather than take the whole config down with it —
11
+ * and must never read as "no limit". */
12
+ const bound = z.number().positive().finite().optional().catch(undefined)
13
+
9
14
  export const AstraleConfigSchema = z.object({
10
15
  issuer: z.string().url().default('https://unregistered.invalid'),
11
16
  admin: AdminTargetConfigSchema.default(DEFAULT_ADMIN_TARGET_CONFIG),
12
- telemetry: z.object({ enabled: z.boolean().default(true) }).default({ enabled: true }),
17
+ // The retention bounds live in the schema, not just in the readers that
18
+ // consume them: zod strips unknown keys, so a config the CLI rewrites (see
19
+ // setup/steps/admin.ts) would silently drop anything declared elsewhere.
20
+ telemetry: z
21
+ .object({ enabled: z.boolean().default(true), maxAgeDays: bound, maxBytes: bound })
22
+ .default({ enabled: true }),
23
+ browser: z.object({ maxCacheBytes: bound, maxProfileAgeDays: bound }).default({}),
13
24
  })
14
25
 
15
26
  export type AstraleConfig = z.infer<typeof AstraleConfigSchema>
@@ -1,3 +1,5 @@
1
+ import type { SessionRouteArtifact, SessionRouteStore } from '@astrale-os/sdk/client/session'
2
+
1
3
  /** Environment values that affect CLI-owned state placement. */
2
4
  export interface PathEnvironment {
3
5
  readonly ASTRALE_HOME?: string
@@ -17,6 +19,7 @@ export interface Paths {
17
19
  readonly idps: string
18
20
  readonly idpSessionsDir: string
19
21
  readonly exchangeCredentials: string
22
+ readonly sessionRoutes: string
20
23
  idpDir(name: string): string
21
24
  idpSession(identityName: string): string
22
25
  }
@@ -35,22 +38,27 @@ export const INSTANCES_PATH: string
35
38
  export const IDPS_PATH: string
36
39
  export const IDP_SESSIONS_DIR: string
37
40
  export const EXCHANGE_CREDENTIALS_PATH: string
41
+ export const SESSION_ROUTES_PATH: string
38
42
 
39
43
  export namespace exchange {
40
44
  interface Artifact {
41
- readonly version: 1
45
+ readonly version: 2
42
46
  readonly entries: Record<string, Entry>
43
47
  }
44
48
 
45
49
  interface Key {
46
50
  readonly kernelIssuer: string
47
51
  readonly domainIssuer: string
48
- readonly user: string
52
+ readonly sourceIssuer: string
53
+ readonly sourceSubject: string
49
54
  }
50
55
 
51
56
  interface Entry {
52
57
  readonly credential: string
53
58
  readonly expiresAt: number
59
+ readonly user: string
60
+ readonly sourceIssuer: string
61
+ readonly sourceSubject: string
54
62
  }
55
63
  }
56
64
 
@@ -118,6 +126,17 @@ export function updateIdentityStore<Value>(
118
126
 
119
127
  /** Atomically replace one private CLI state file through a same-directory temporary file. */
120
128
  export function atomicWrite(path: string, data: string): Promise<void>
129
+ export function atomicWriteSync(path: string, data: string): void
130
+
131
+ /** CLI filesystem representation for Kernel Client's admitted confidential route artifact. */
132
+ export class FileSessionRouteStore implements SessionRouteStore {
133
+ constructor(path?: string)
134
+ read(): unknown
135
+ write(artifact: SessionRouteArtifact): void
136
+ clear(): void
137
+ }
138
+
139
+ export const SESSION_ROUTE_STORE: Readonly<FileSessionRouteStore>
121
140
 
122
141
  export interface FileLockOptions {
123
142
  readonly pollIntervalMs?: number
@@ -11,10 +11,24 @@ The identity registry decodes the legacy unversioned shape and current V1 envelo
11
11
  exact bytes at `identities.json.v0.bak` before publishing V1. Invalid or newer files remain untouched
12
12
  and fail closed. Identity orchestration owns key and IdP-session effects above this module.
13
13
 
14
- The exchange registry owns a versioned `exchange.Artifact`. Each entry is keyed by the atomic
15
- `(Kernel issuer, Domain issuer, registered User)` identity and stores only one inspected Domain
16
- credential and expiry. It reuses the same atomic-write and bounded file-lock primitives, maintains
17
- owner-only directory and file modes, and remains distinct from Client's process-local route cache.
14
+ The exchange registry owns a versioned `exchange.Artifact`. Each V2 entry is keyed by the atomic
15
+ `(Kernel issuer, Domain issuer, source issuer, source subject)` identity and stores one inspected
16
+ Domain credential, expiry, and the exact registered Kernel User proven when that credential was
17
+ minted, together with the exact upstream source issuer and subject that selected the entry. This lets
18
+ a warm command validate and reuse the credential before any network `whoami` without accepting a
19
+ refresh result filed under another source identity.
20
+ V1 is not migrated or retained; it is discarded and replaced by the next exact exchange. The
21
+ registry reuses the same atomic-write and bounded file-lock primitives and maintains owner-only
22
+ directory and file modes.
23
+
24
+ The session-route registry is a separate representation adapter for Kernel Client's versioned,
25
+ bounded confidential route artifact. Kernel Client exclusively owns route keying, admission, expiry,
26
+ and stale/miss recovery. CLI owns only synchronous owner-private JSON I/O so a new CLI process can
27
+ reuse admitted routing state without an Admin-specific shortcut. Writes are atomic snapshots; a
28
+ lost concurrent cache update or any read/write failure is only a future cold route miss and cannot
29
+ change product correctness.
30
+ Authentication logout and identity deletion remove this artifact together with exchanged Domain
31
+ credentials so locally retired authority does not leave reusable destination bearers behind.
18
32
 
19
33
  Shape decoding, migrations, and backup policy remain with each semantic registry. Commands do not
20
34
  call these primitives directly, and Kernel Client owns no CLI filesystem state.
@@ -8,6 +8,7 @@ export default defineLayout({
8
8
  'identities.ts',
9
9
  'index.ts',
10
10
  'paths.ts',
11
+ 'session-routes.ts',
11
12
  'tsconfig.json',
12
13
  ],
13
14
  exact: true,
@@ -1,5 +1,5 @@
1
1
  import { afterEach, beforeEach, describe, expect, test } from 'bun:test'
2
- import { mkdtemp, readFile, rm, stat } from 'node:fs/promises'
2
+ import { mkdir, mkdtemp, readFile, rm, stat, writeFile } from 'node:fs/promises'
3
3
  import { tmpdir } from 'node:os'
4
4
  import { join } from 'node:path'
5
5
 
@@ -19,11 +19,22 @@ afterEach(async () => {
19
19
 
20
20
  describe('exchange credential cache', () => {
21
21
  /** @evidence TEST-CLI-EXCHANGE-CACHE-EXACT-KEY-AND-PRIVATE-MODE */
22
- test('partitions by Kernel, Domain, and User under private filesystem modes', async () => {
22
+ test('partitions by Kernel, Domain, and source identity under private filesystem modes', async () => {
23
23
  const cache = new ExchangeCredentialCache(path)
24
24
  const now = () => 100
25
25
  const first = key('https://kernel-a.example', 'https://domain.example', 'user-a')
26
- const second = key('https://kernel-a.example', 'https://domain.example', 'user-b')
26
+ const partitions = [
27
+ first,
28
+ key('https://kernel-b.example', first.domainIssuer, first.sourceSubject),
29
+ key(first.kernelIssuer, 'https://other-domain.example', first.sourceSubject),
30
+ key(
31
+ first.kernelIssuer,
32
+ first.domainIssuer,
33
+ first.sourceSubject,
34
+ 'https://other-source.example',
35
+ ),
36
+ key(first.kernelIssuer, first.domainIssuer, 'user-b'),
37
+ ]
27
38
  let refreshes = 0
28
39
 
29
40
  const resolve = (candidate: typeof first) =>
@@ -31,18 +42,16 @@ describe('exchange credential cache', () => {
31
42
  candidate,
32
43
  async () => {
33
44
  refreshes += 1
34
- return {
35
- credential: token(candidate, 200),
36
- expiresAt: 200,
37
- }
45
+ return entry(candidate, 200)
38
46
  },
39
47
  now,
40
48
  )
41
49
 
42
- await expect(resolve(first)).resolves.toBe(token(first, 200))
43
- await expect(resolve(first)).resolves.toBe(token(first, 200))
44
- await expect(resolve(second)).resolves.toBe(token(second, 200))
45
- expect(refreshes).toBe(2)
50
+ for (const candidate of partitions) {
51
+ await expect(resolve(candidate)).resolves.toBe(token(candidate, 200))
52
+ await expect(resolve(candidate)).resolves.toBe(token(candidate, 200))
53
+ }
54
+ expect(refreshes).toBe(partitions.length)
46
55
  expect((await stat(path)).mode & 0o777).toBe(0o600)
47
56
  expect((await stat(join(directory, 'private'))).mode & 0o777).toBe(0o700)
48
57
  })
@@ -56,10 +65,7 @@ describe('exchange credential cache', () => {
56
65
  const refresh = async () => {
57
66
  refreshes += 1
58
67
  await new Promise((resolve) => setTimeout(resolve, 10))
59
- return {
60
- credential: token(candidate, 200),
61
- expiresAt: 200,
62
- }
68
+ return entry(candidate, 200)
63
69
  }
64
70
 
65
71
  const values = await Promise.all([
@@ -77,10 +83,7 @@ describe('exchange credential cache', () => {
77
83
  const candidate = key('https://kernel.example', 'https://domain.example', 'user')
78
84
  await cache.getOrRefresh(
79
85
  candidate,
80
- async () => ({
81
- credential: token(candidate, 120),
82
- expiresAt: 120,
83
- }),
86
+ async () => entry(candidate, 120),
84
87
  () => 50,
85
88
  )
86
89
  let refreshes = 0
@@ -88,10 +91,7 @@ describe('exchange credential cache', () => {
88
91
  candidate,
89
92
  async () => {
90
93
  refreshes += 1
91
- return {
92
- credential: token(candidate, 220),
93
- expiresAt: 220,
94
- }
94
+ return entry(candidate, 220)
95
95
  },
96
96
  () => 100,
97
97
  )
@@ -99,19 +99,16 @@ describe('exchange credential cache', () => {
99
99
 
100
100
  await expect(
101
101
  cache.getOrRefresh(
102
- key('https://other-kernel.example', candidate.domainIssuer, candidate.user),
103
- async () => ({
104
- credential: token(candidate, 220),
105
- expiresAt: 220,
106
- }),
102
+ key('https://other-kernel.example', candidate.domainIssuer, candidate.sourceSubject),
103
+ async () => entry(candidate, 220),
107
104
  () => 100,
108
105
  ),
109
106
  ).rejects.toThrow(/inconsistent with its cache key/i)
110
107
 
111
108
  await expect(
112
109
  cache.getOrRefresh(
113
- key(candidate.kernelIssuer, candidate.domainIssuer, 'other-user'),
114
- async () => ({ credential: token(candidate, 220), expiresAt: 220 }),
110
+ key(candidate.kernelIssuer, candidate.domainIssuer, 'other-source'),
111
+ async () => entry(candidate, 220),
115
112
  () => 100,
116
113
  ),
117
114
  ).rejects.toThrow(/inconsistent with its cache key/i)
@@ -125,10 +122,7 @@ describe('exchange credential cache', () => {
125
122
  await expect(
126
123
  cache.getOrRefresh(
127
124
  malformedCandidate,
128
- async () => ({
129
- credential: token(malformedCandidate, 220, malformed),
130
- expiresAt: 220,
131
- }),
125
+ async () => entry(malformedCandidate, 220, malformed),
132
126
  () => 100,
133
127
  ),
134
128
  ).rejects.toThrow(/inconsistent with its cache key/i)
@@ -143,10 +137,7 @@ describe('exchange credential cache', () => {
143
137
  for (const candidate of [a, b]) {
144
138
  await cache.getOrRefresh(
145
139
  candidate,
146
- async () => ({
147
- credential: token(candidate, 200),
148
- expiresAt: 200,
149
- }),
140
+ async () => entry(candidate, 200),
150
141
  () => 100,
151
142
  )
152
143
  }
@@ -156,10 +147,60 @@ describe('exchange credential cache', () => {
156
147
  await cache.clear()
157
148
  expect(JSON.parse(await readFile(path, 'utf8')).entries).toEqual({})
158
149
  })
150
+
151
+ test('discards the V1 cache and writes only V2 after a fresh exact exchange', async () => {
152
+ await mkdir(join(directory, 'private'))
153
+ await writeFile(
154
+ path,
155
+ JSON.stringify({
156
+ version: 1,
157
+ entries: { legacy: { credential: 'legacy', expiresAt: 999 } },
158
+ }),
159
+ )
160
+ const cache = new ExchangeCredentialCache(path)
161
+ const candidate = key('https://kernel.example', 'https://domain.example', 'source-user')
162
+ let refreshes = 0
163
+ await cache.getOrRefresh(
164
+ candidate,
165
+ async () => {
166
+ refreshes += 1
167
+ return entry(candidate, 200)
168
+ },
169
+ () => 100,
170
+ )
171
+ expect(refreshes).toBe(1)
172
+ const stored = JSON.parse(await readFile(path, 'utf8'))
173
+ expect(stored.version).toBe(2)
174
+ expect(JSON.stringify(stored)).not.toContain('legacy')
175
+ })
159
176
  })
160
177
 
161
- function key(kernelIssuer: string, domainIssuer: string, user: string) {
162
- return { kernelIssuer, domainIssuer, user }
178
+ function key(
179
+ kernelIssuer: string,
180
+ domainIssuer: string,
181
+ sourceSubject: string,
182
+ sourceIssuer = 'https://source.example',
183
+ ) {
184
+ return {
185
+ kernelIssuer,
186
+ domainIssuer,
187
+ sourceIssuer,
188
+ sourceSubject,
189
+ }
190
+ }
191
+
192
+ function entry(
193
+ candidate: ReturnType<typeof key>,
194
+ expiresAt: number,
195
+ malformed?: 'outer-delegation' | 'proof-without-delegation',
196
+ ) {
197
+ return {
198
+ credential: token(candidate, expiresAt, malformed),
199
+ expiresAt,
200
+ user: candidate.sourceSubject,
201
+ sourceIssuer: candidate.sourceIssuer,
202
+ sourceSubject: candidate.sourceSubject,
203
+ }
163
204
  }
164
205
 
165
206
  function token(
@@ -170,12 +211,17 @@ function token(
170
211
  const encode = (value: unknown) => Buffer.from(JSON.stringify(value)).toString('base64url')
171
212
  const proof = `${encode({ alg: 'EdDSA', typ: 'JWT' })}.${encode({
172
213
  iss: candidate.kernelIssuer,
173
- sub: candidate.user,
214
+ sub: candidate.sourceSubject,
174
215
  aud: candidate.kernelIssuer,
175
216
  exp,
176
217
  ...(malformed === 'proof-without-delegation'
177
218
  ? {}
178
- : { delegation: { v: 1, expr: { kind: 'identity', id: candidate.user } } }),
219
+ : {
220
+ delegation: {
221
+ v: 1,
222
+ expr: { kind: 'identity', id: candidate.sourceSubject },
223
+ },
224
+ }),
179
225
  })}.signature`
180
226
  return `${encode({ alg: 'EdDSA', typ: 'JWT' })}.${encode({
181
227
  iss: candidate.domainIssuer,
@@ -13,7 +13,7 @@ import {
13
13
  import { tmpdir } from 'node:os'
14
14
  import { join } from 'node:path'
15
15
 
16
- import { atomicWrite, withFileLock } from '../files'
16
+ import { atomicWrite, atomicWriteSync, withFileLock } from '../files'
17
17
 
18
18
  let temporaryDirectory: string
19
19
 
@@ -50,6 +50,29 @@ describe('atomicWrite', () => {
50
50
  })
51
51
  })
52
52
 
53
+ describe('atomicWriteSync', () => {
54
+ test('publishes a synced mode-0600 file without temporary residue', async () => {
55
+ const path = join(temporaryDirectory, 'sync', 'state.json')
56
+
57
+ atomicWriteSync(path, '{"value":1}')
58
+
59
+ expect(await readFile(path, 'utf-8')).toBe('{"value":1}')
60
+ expect((await stat(path)).mode & 0o777).toBe(0o600)
61
+ expect(await readdir(join(temporaryDirectory, 'sync'))).toEqual(['state.json'])
62
+ })
63
+
64
+ test('does not disturb the target or retain a temporary file after failure', async () => {
65
+ const path = join(temporaryDirectory, 'sync-target')
66
+ await mkdir(path)
67
+ await writeFile(join(path, 'retained'), 'stable')
68
+
69
+ expect(() => atomicWriteSync(path, 'replacement')).toThrow()
70
+
71
+ expect(await readFile(join(path, 'retained'), 'utf-8')).toBe('stable')
72
+ expect((await readdir(temporaryDirectory)).sort()).toEqual(['sync-target'])
73
+ })
74
+ })
75
+
53
76
  describe('withFileLock', () => {
54
77
  /** @evidence TEST-CLI-STATE-LOCK-SERIALIZES */
55
78
  test('serializes contending read-modify-write transitions', async () => {
@@ -0,0 +1,93 @@
1
+ import type { Transport } from '@astrale-os/sdk/client'
2
+
3
+ import { issuer } from '@astrale-os/sdk/auth'
4
+ import { call, Client } from '@astrale-os/sdk/client'
5
+ import { ClientSession } from '@astrale-os/sdk/client/session'
6
+ import { NodeId } from '@astrale-os/sdk/graph/node'
7
+ import { Path } from '@astrale-os/sdk/graph/path'
8
+ import { invocation } from '@astrale-os/sdk/invocation'
9
+
10
+ import { FileSessionRouteStore } from '../../session-routes'
11
+
12
+ const routePath = process.argv[2]
13
+ if (routePath === undefined) throw new Error('route artifact path is required')
14
+
15
+ const sourceEndpoint = 'https://source.kernel.test/invoke'
16
+ const sourceIssuer = issuer.accept('https://source.kernel.test')
17
+ const destinationEndpoint = 'https://destination.application.test/invoke'
18
+ const target = Path.id(NodeId('session-route-fresh-process'))
19
+ let sourceAttempts = 0
20
+ let destinationAttempts = 0
21
+
22
+ const route = invocation.acceptRoute({
23
+ endpoint: { http: destinationEndpoint },
24
+ via: {
25
+ kind: 'via',
26
+ issuer: sourceIssuer,
27
+ publication: {
28
+ origin: 'destination.application.test',
29
+ identity: {
30
+ issuer: 'https://destination.application.test',
31
+ subject: 'destination.application.test',
32
+ },
33
+ revision: `sha256:${'1'.padStart(64, '0')}`,
34
+ etag: `sha256:${'1'.padStart(64, '0')}`,
35
+ },
36
+ },
37
+ })
38
+ const carrier = `e30.${Buffer.from(
39
+ JSON.stringify({ exp: Math.floor(Date.now() / 1_000) + 600 }),
40
+ ).toString('base64url')}.signature`
41
+ const sourceDispatch: Transport['dispatch'] = async () => {
42
+ sourceAttempts += 1
43
+ return {
44
+ kind: 'redirect',
45
+ invocation: { source: sourceIssuer, id: 'source-invocation' },
46
+ redirect: { route, credential: carrier },
47
+ }
48
+ }
49
+ const destinationDispatch: Transport['dispatch'] = async () => {
50
+ destinationAttempts += 1
51
+ return {
52
+ kind: 'value',
53
+ value: 'done',
54
+ invocation: { source: sourceIssuer, id: 'destination-invocation' },
55
+ }
56
+ }
57
+ const source = new Client({ transport: { dispatch: sourceDispatch } })
58
+ const destination = new Client({ transport: { dispatch: destinationDispatch } })
59
+ const session = new ClientSession({
60
+ kernel: sourceIssuer,
61
+ fetch: async () =>
62
+ new Response(
63
+ JSON.stringify({
64
+ protocol: 'astrale-invocation',
65
+ version: 1,
66
+ issuer: sourceIssuer,
67
+ endpoints: { http: sourceEndpoint },
68
+ }),
69
+ { headers: { 'content-type': 'application/json' } },
70
+ ),
71
+ pool: {
72
+ clientFor(
73
+ target: Parameters<
74
+ NonNullable<ConstructorParameters<typeof ClientSession>[0]['pool']>['clientFor']
75
+ >[0],
76
+ ) {
77
+ const url = target.transport === 'auto' ? target.endpoints.http : target.url
78
+ return url === sourceEndpoint ? source : destination
79
+ },
80
+ },
81
+ auth: { ttlSeconds: 120, resolve: () => ({ credential: 'source-credential' }) },
82
+ routeStore: new FileSessionRouteStore(routePath),
83
+ policy: { maximumRouteAgeMs: 60_000 },
84
+ })
85
+
86
+ try {
87
+ const value = await session.call(call(target, null))
88
+ console.log(JSON.stringify({ value, sourceAttempts, destinationAttempts }))
89
+ } finally {
90
+ session.close()
91
+ source.close()
92
+ destination.close()
93
+ }