@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.
- package/.check-workspace.cjs +40 -0
- package/README.md +151 -0
- package/dist/astrale.js +59749 -0
- package/package.json +90 -0
- package/src/command.ts +40 -0
- package/src/commands/__tests__/admin-instance.test.ts +73 -0
- package/src/commands/__tests__/auth-login.test.ts +178 -0
- package/src/commands/__tests__/auth-token.test.ts +223 -0
- package/src/commands/__tests__/call.test.ts +72 -0
- package/src/commands/__tests__/domain-list.test.ts +74 -0
- package/src/commands/__tests__/help-contract.test.ts +136 -0
- package/src/commands/__tests__/install-identity-override.test.ts +65 -0
- package/src/commands/__tests__/instance-bookmark.test.ts +101 -0
- package/src/commands/__tests__/instance-create-hosts.test.ts +29 -0
- package/src/commands/__tests__/instance-list-rows.test.ts +63 -0
- package/src/commands/__tests__/logs.test.ts +117 -0
- package/src/commands/__tests__/ls.test.ts +25 -0
- package/src/commands/__tests__/setup-plan.test.ts +61 -0
- package/src/commands/admin/status.ts +61 -0
- package/src/commands/admin/use.ts +77 -0
- package/src/commands/auth/login.ts +82 -0
- package/src/commands/auth/logout.ts +50 -0
- package/src/commands/auth/status.ts +86 -0
- package/src/commands/auth/token.ts +162 -0
- package/src/commands/browser.ts +207 -0
- package/src/commands/call.ts +300 -0
- package/src/commands/describe.ts +182 -0
- package/src/commands/domain/install.ts +420 -0
- package/src/commands/domain/list.ts +154 -0
- package/src/commands/domain/publish.ts +155 -0
- package/src/commands/get.ts +60 -0
- package/src/commands/identity/create.ts +26 -0
- package/src/commands/identity/delete.ts +18 -0
- package/src/commands/identity/export.ts +66 -0
- package/src/commands/identity/import.ts +101 -0
- package/src/commands/identity/list.ts +56 -0
- package/src/commands/identity/register.ts +170 -0
- package/src/commands/identity/sync.ts +32 -0
- package/src/commands/identity/unsync.ts +24 -0
- package/src/commands/identity/use.ts +18 -0
- package/src/commands/identity/whoami.ts +34 -0
- package/src/commands/idp/add.ts +150 -0
- package/src/commands/idp/list.ts +57 -0
- package/src/commands/idp/refresh.ts +38 -0
- package/src/commands/idp/remove.ts +36 -0
- package/src/commands/idp/show.ts +29 -0
- package/src/commands/instance/active.ts +64 -0
- package/src/commands/instance/bookmark.ts +72 -0
- package/src/commands/instance/create.ts +69 -0
- package/src/commands/instance/delete.ts +72 -0
- package/src/commands/instance/forget.ts +26 -0
- package/src/commands/instance/list.ts +149 -0
- package/src/commands/instance/status.ts +42 -0
- package/src/commands/instance/use.ts +210 -0
- package/src/commands/logs.ts +347 -0
- package/src/commands/ls.ts +229 -0
- package/src/commands/query.ts +32 -0
- package/src/commands/setup.ts +54 -0
- package/src/commands/status.ts +60 -0
- package/src/commands/studio.ts +401 -0
- package/src/commands/token.ts +77 -0
- package/src/commands/update.ts +267 -0
- package/src/commands/use.ts +87 -0
- package/src/errors.ts +65 -0
- package/src/kernel/__tests__/auth.test.ts +77 -0
- package/src/kernel/__tests__/errors.test.ts +43 -0
- package/src/kernel/__tests__/remote-routing.test.ts +70 -0
- package/src/kernel/auth.ts +234 -0
- package/src/kernel/ca-fetch.ts +119 -0
- package/src/kernel/client.ts +191 -0
- package/src/kernel/errors.ts +280 -0
- package/src/kernel/expand.ts +217 -0
- package/src/kernel/index.ts +14 -0
- package/src/kernel/options.ts +22 -0
- package/src/kernel/remote-routing.ts +88 -0
- package/src/kernel/run.ts +63 -0
- package/src/kernel/types.ts +14 -0
- package/src/lib/__tests__/admin-target.test.ts +112 -0
- package/src/lib/__tests__/binary.test.ts +56 -0
- package/src/lib/__tests__/command-dx.test.ts +58 -0
- package/src/lib/__tests__/concurrency.test.ts +62 -0
- package/src/lib/__tests__/config.test.ts +53 -0
- package/src/lib/__tests__/design.test.ts +99 -0
- package/src/lib/__tests__/domain-identity.test.ts +60 -0
- package/src/lib/__tests__/format.test.ts +22 -0
- package/src/lib/__tests__/fs-atomic.test.ts +104 -0
- package/src/lib/__tests__/identity.test.ts +79 -0
- package/src/lib/__tests__/idp-session.driver.ts +53 -0
- package/src/lib/__tests__/idp-session.test.ts +357 -0
- package/src/lib/__tests__/idp.test.ts +385 -0
- package/src/lib/__tests__/instance-candidates.test.ts +73 -0
- package/src/lib/__tests__/instance-target.test.ts +183 -0
- package/src/lib/__tests__/instance.test.ts +136 -0
- package/src/lib/__tests__/keys.test.ts +129 -0
- package/src/lib/__tests__/local-status.test.ts +202 -0
- package/src/lib/__tests__/output.test.ts +150 -0
- package/src/lib/__tests__/panel.test.ts +40 -0
- package/src/lib/__tests__/port.test.ts +44 -0
- package/src/lib/__tests__/prompt.test.ts +25 -0
- package/src/lib/__tests__/sdk-deps.test.ts +68 -0
- package/src/lib/__tests__/self.test.ts +272 -0
- package/src/lib/__tests__/studio-server-deps.test.ts +74 -0
- package/src/lib/__tests__/table.test.ts +53 -0
- package/src/lib/__tests__/update.test.ts +246 -0
- package/src/lib/__tests__/use-target.test.ts +56 -0
- package/src/lib/__tests__/validation.test.ts +34 -0
- package/src/lib/admin-domain.ts +25 -0
- package/src/lib/admin-instance.ts +26 -0
- package/src/lib/admin-target.ts +217 -0
- package/src/lib/binary.ts +131 -0
- package/src/lib/browser.ts +150 -0
- package/src/lib/command-dx.ts +161 -0
- package/src/lib/concurrency.ts +31 -0
- package/src/lib/config.ts +45 -0
- package/src/lib/domain-identity.ts +49 -0
- package/src/lib/env.ts +49 -0
- package/src/lib/format.ts +4 -0
- package/src/lib/fs-atomic.ts +126 -0
- package/src/lib/identity.ts +256 -0
- package/src/lib/idp-session.ts +134 -0
- package/src/lib/idp.ts +876 -0
- package/src/lib/instance-candidates.ts +49 -0
- package/src/lib/instance-target.ts +182 -0
- package/src/lib/instance.ts +395 -0
- package/src/lib/keys.ts +294 -0
- package/src/lib/local-status.ts +152 -0
- package/src/lib/log.ts +116 -0
- package/src/lib/login-flow.ts +164 -0
- package/src/lib/meta.ts +86 -0
- package/src/lib/output.ts +222 -0
- package/src/lib/panel.ts +61 -0
- package/src/lib/paths.ts +11 -0
- package/src/lib/port.ts +41 -0
- package/src/lib/proc.ts +82 -0
- package/src/lib/prompt.ts +136 -0
- package/src/lib/provision-instance.ts +170 -0
- package/src/lib/sdk-deps.ts +104 -0
- package/src/lib/self.ts +166 -0
- package/src/lib/skills.ts +171 -0
- package/src/lib/table.ts +62 -0
- package/src/lib/update.ts +315 -0
- package/src/lib/use-target.ts +24 -0
- package/src/lib/validation.ts +59 -0
- package/src/program.ts +200 -0
- package/src/registry.ts +59 -0
- package/src/setup/__tests__/util.test.ts +29 -0
- package/src/setup/engine.ts +83 -0
- package/src/setup/render.ts +109 -0
- package/src/setup/steps/admin.ts +78 -0
- package/src/setup/steps/agent-browser.ts +81 -0
- package/src/setup/steps/auth.ts +54 -0
- package/src/setup/steps/domain.ts +68 -0
- package/src/setup/steps/index.ts +18 -0
- package/src/setup/steps/instance.ts +119 -0
- package/src/setup/steps/skills-bridge.ts +70 -0
- package/src/setup/steps/skills.ts +59 -0
- package/src/setup/types.ts +61 -0
- package/src/setup/util.ts +34 -0
- package/src/test-utils.ts +18 -0
- package/studio/client/dist/assets/index-DOwzZAEK.css +1 -0
- package/studio/client/dist/assets/index-wtU0Zxhy.js +183 -0
- package/studio/client/dist/index.html +13 -0
- package/studio/package.json +62 -0
- package/studio/server/agent/ask.ts +68 -0
- package/studio/server/agent/bridge-mcp.ts +182 -0
- package/studio/server/agent/bridge.ts +188 -0
- package/studio/server/agent/claude.ts +666 -0
- package/studio/server/agent/mock.ts +186 -0
- package/studio/server/agent/prompt.ts +202 -0
- package/studio/server/agent/registry.ts +29 -0
- package/studio/server/agent/runner.ts +484 -0
- package/studio/server/agent/schema-map.ts +112 -0
- package/studio/server/agent/types.ts +120 -0
- package/studio/server/api.ts +574 -0
- package/studio/server/cache.ts +138 -0
- package/studio/server/detect.ts +81 -0
- package/studio/server/domain.ts +70 -0
- package/studio/server/index.ts +136 -0
- package/studio/server/introspect/anatomy-extras.ts +398 -0
- package/studio/server/introspect/anatomy.ts +108 -0
- package/studio/server/introspect/bundle.ts +57 -0
- package/studio/server/introspect/core-extractor.ts +119 -0
- package/studio/server/introspect/core.ts +44 -0
- package/studio/server/introspect/diff.ts +133 -0
- package/studio/server/introspect/extractor.ts +102 -0
- package/studio/server/introspect/hash.ts +21 -0
- package/studio/server/introspect/overlay-tsmorph.ts +874 -0
- package/studio/server/introspect/overlay.ts +57 -0
- package/studio/server/introspect/runtime.ts +99 -0
- package/studio/server/introspect/schema-refs.ts +46 -0
- package/studio/server/lifecycle.ts +38 -0
- package/studio/server/sse.ts +57 -0
- package/studio/server/state/baseline.ts +211 -0
- package/studio/server/state/catalog.ts +117 -0
- package/studio/server/state/comments.ts +321 -0
- package/studio/server/state/context.ts +167 -0
- package/studio/server/state/copy.ts +156 -0
- package/studio/server/state/create.ts +156 -0
- package/studio/server/state/documents.ts +70 -0
- package/studio/server/state/env.ts +161 -0
- package/studio/server/state/git.ts +75 -0
- package/studio/server/state/handoff.ts +55 -0
- package/studio/server/state/harness-gateway.ts +181 -0
- package/studio/server/state/harness-token.ts +0 -0
- package/studio/server/state/instance.ts +244 -0
- package/studio/server/state/integrations.ts +55 -0
- package/studio/server/state/layout.ts +55 -0
- package/studio/server/state/settings.ts +39 -0
- package/studio/server/state/store.ts +97 -0
- package/studio/server/state/updates.ts +63 -0
- package/studio/server/state/usage.ts +37 -0
- package/studio/server/state/views.ts +138 -0
- package/studio/server/state/visibility.ts +33 -0
- package/studio/server/watch.ts +81 -0
- package/studio/server/workspace-state.ts +26 -0
- package/studio/server/workspace-watch.ts +101 -0
- package/studio/shared/types.ts +873 -0
- package/studio/tsconfig.json +23 -0
- package/tsconfig.json +14 -0
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
import { describe, expect, test } from 'bun:test'
|
|
2
|
+
|
|
3
|
+
import { IdentityStoreSchema } from '../identity'
|
|
4
|
+
|
|
5
|
+
describe('IdentityStoreSchema', () => {
|
|
6
|
+
test('parses valid store', () => {
|
|
7
|
+
const result = IdentityStoreSchema.parse({
|
|
8
|
+
default: 'manager',
|
|
9
|
+
identities: {
|
|
10
|
+
manager: { subject: 'manager', createdAt: '2024-01-01T00:00:00Z' },
|
|
11
|
+
},
|
|
12
|
+
})
|
|
13
|
+
expect(result.default).toBe('manager')
|
|
14
|
+
expect(result.identities.manager.subject).toBe('manager')
|
|
15
|
+
})
|
|
16
|
+
|
|
17
|
+
test('parses multiple identities', () => {
|
|
18
|
+
const result = IdentityStoreSchema.parse({
|
|
19
|
+
default: 'admin',
|
|
20
|
+
identities: {
|
|
21
|
+
admin: {
|
|
22
|
+
subject: 'admin',
|
|
23
|
+
createdAt: '2024-01-01T00:00:00Z',
|
|
24
|
+
issuer: 'https://admin.example.com',
|
|
25
|
+
},
|
|
26
|
+
user: { subject: 'user-principal', createdAt: '2024-06-15T12:00:00Z' },
|
|
27
|
+
},
|
|
28
|
+
})
|
|
29
|
+
expect(Object.keys(result.identities)).toHaveLength(2)
|
|
30
|
+
expect(result.identities.admin.issuer).toBe('https://admin.example.com')
|
|
31
|
+
expect(result.identities.user.subject).toBe('user-principal')
|
|
32
|
+
})
|
|
33
|
+
|
|
34
|
+
test('parses IdP-backed identities without key metadata', () => {
|
|
35
|
+
const result = IdentityStoreSchema.parse({
|
|
36
|
+
default: 'alice',
|
|
37
|
+
identities: {
|
|
38
|
+
alice: {
|
|
39
|
+
source: 'idp',
|
|
40
|
+
subject: 'user_123',
|
|
41
|
+
idp: 'workos',
|
|
42
|
+
issuer: 'https://example.authkit.app',
|
|
43
|
+
audience: 'https://api.example.com',
|
|
44
|
+
createdAt: '2024-01-01T00:00:00Z',
|
|
45
|
+
claims: { email: 'alice@example.com' },
|
|
46
|
+
},
|
|
47
|
+
},
|
|
48
|
+
})
|
|
49
|
+
|
|
50
|
+
expect(result.identities.alice.source).toBe('idp')
|
|
51
|
+
expect(result.identities.alice.kid).toBeUndefined()
|
|
52
|
+
expect(result.identities.alice.idp).toBe('workos')
|
|
53
|
+
})
|
|
54
|
+
|
|
55
|
+
test('rejects missing default field', () => {
|
|
56
|
+
expect(() =>
|
|
57
|
+
IdentityStoreSchema.parse({
|
|
58
|
+
identities: { manager: { subject: 'manager', createdAt: '2024-01-01' } },
|
|
59
|
+
}),
|
|
60
|
+
).toThrow()
|
|
61
|
+
})
|
|
62
|
+
|
|
63
|
+
test('rejects identity missing subject', () => {
|
|
64
|
+
expect(() =>
|
|
65
|
+
IdentityStoreSchema.parse({
|
|
66
|
+
default: 'manager',
|
|
67
|
+
identities: { manager: { createdAt: '2024-01-01' } },
|
|
68
|
+
}),
|
|
69
|
+
).toThrow()
|
|
70
|
+
})
|
|
71
|
+
|
|
72
|
+
test('accepts empty identities record', () => {
|
|
73
|
+
const result = IdentityStoreSchema.parse({
|
|
74
|
+
default: 'nobody',
|
|
75
|
+
identities: {},
|
|
76
|
+
})
|
|
77
|
+
expect(Object.keys(result.identities)).toHaveLength(0)
|
|
78
|
+
})
|
|
79
|
+
})
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Subprocess driver for idp-session.test.ts. `ensureFreshSession` resolves
|
|
3
|
+
* paths through the import-time ASTRALE_HOME singleton, and `bun test` shares
|
|
4
|
+
* one process across files, so session-touching scenarios run here — in a
|
|
5
|
+
* fresh process whose ASTRALE_HOME the test controls.
|
|
6
|
+
*
|
|
7
|
+
* Usage: bun idp-session.driver.ts <ensure|ensure-concurrent>
|
|
8
|
+
* Env: ASTRALE_HOME (required), DRIVER_AUDIENCE, DRIVER_ORG_ID
|
|
9
|
+
* Stdout: one JSON line describing the outcome.
|
|
10
|
+
*/
|
|
11
|
+
import { accessTokenForAudience, classifyRefreshFailure } from '../idp'
|
|
12
|
+
import { ensureFreshSession } from '../idp-session'
|
|
13
|
+
|
|
14
|
+
const scenario = process.argv[2]
|
|
15
|
+
const audience = process.env.DRIVER_AUDIENCE || undefined
|
|
16
|
+
let orgHintCalls = 0
|
|
17
|
+
const resolveOrganizationId = async (): Promise<string | undefined> => {
|
|
18
|
+
orgHintCalls += 1
|
|
19
|
+
return process.env.DRIVER_ORG_ID || undefined
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
function print(result: Record<string, unknown>): void {
|
|
23
|
+
process.stdout.write(JSON.stringify(result) + '\n')
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
try {
|
|
27
|
+
if (scenario === 'ensure') {
|
|
28
|
+
const session = await ensureFreshSession('alice', { audience, resolveOrganizationId })
|
|
29
|
+
print({ ok: true, token: accessTokenForAudience(session, audience), orgHintCalls })
|
|
30
|
+
} else if (scenario === 'ensure-concurrent') {
|
|
31
|
+
const [a, b] = await Promise.all([
|
|
32
|
+
ensureFreshSession('alice', { audience, resolveOrganizationId }),
|
|
33
|
+
ensureFreshSession('alice', { audience, resolveOrganizationId }),
|
|
34
|
+
])
|
|
35
|
+
print({
|
|
36
|
+
ok: true,
|
|
37
|
+
tokens: [accessTokenForAudience(a, audience), accessTokenForAudience(b, audience)],
|
|
38
|
+
orgHintCalls,
|
|
39
|
+
})
|
|
40
|
+
} else {
|
|
41
|
+
throw new Error(`Unknown scenario: ${scenario}`)
|
|
42
|
+
}
|
|
43
|
+
} catch (e) {
|
|
44
|
+
const error = e as Error & { code?: string }
|
|
45
|
+
print({
|
|
46
|
+
ok: false,
|
|
47
|
+
errorName: error.name,
|
|
48
|
+
errorCode: error.code,
|
|
49
|
+
classification: classifyRefreshFailure(e),
|
|
50
|
+
message: error.message,
|
|
51
|
+
orgHintCalls,
|
|
52
|
+
})
|
|
53
|
+
}
|
|
@@ -0,0 +1,357 @@
|
|
|
1
|
+
import { afterEach, beforeEach, describe, expect, test } from 'bun:test'
|
|
2
|
+
import { mkdir, mkdtemp, readFile, readdir, rm, unlink, writeFile } from 'node:fs/promises'
|
|
3
|
+
import { tmpdir } from 'node:os'
|
|
4
|
+
import { join } from 'node:path'
|
|
5
|
+
|
|
6
|
+
const AUD = 'https://kernel.example.com'
|
|
7
|
+
|
|
8
|
+
let tmp: string
|
|
9
|
+
|
|
10
|
+
beforeEach(async () => {
|
|
11
|
+
tmp = await mkdtemp(join(tmpdir(), 'astrale-idp-session-'))
|
|
12
|
+
await mkdir(join(tmp, 'idp-sessions'), { recursive: true })
|
|
13
|
+
})
|
|
14
|
+
|
|
15
|
+
afterEach(async () => {
|
|
16
|
+
await rm(tmp, { recursive: true, force: true })
|
|
17
|
+
})
|
|
18
|
+
|
|
19
|
+
describe('ensureFreshSession', () => {
|
|
20
|
+
test('returns a fresh session without touching the IdP or the org hint', async () => {
|
|
21
|
+
const server = rotationServer()
|
|
22
|
+
try {
|
|
23
|
+
await writeIdpConfig(server.url)
|
|
24
|
+
await writeSession({ expires_at: future() })
|
|
25
|
+
|
|
26
|
+
const result = await runDriver('ensure')
|
|
27
|
+
|
|
28
|
+
expect(result.ok).toBe(true)
|
|
29
|
+
expect(result.orgHintCalls).toBe(0)
|
|
30
|
+
expect(server.refreshCount()).toBe(0)
|
|
31
|
+
} finally {
|
|
32
|
+
await server.stop()
|
|
33
|
+
}
|
|
34
|
+
})
|
|
35
|
+
|
|
36
|
+
test('serves an instance flip from the per-audience map without a refresh', async () => {
|
|
37
|
+
const server = rotationServer()
|
|
38
|
+
try {
|
|
39
|
+
await writeIdpConfig(server.url)
|
|
40
|
+
await writeSession({
|
|
41
|
+
access_token: unsignedJwt({ aud: 'https://other.example.com', exp: futureEpoch() }),
|
|
42
|
+
expires_at: future(),
|
|
43
|
+
tokens: {
|
|
44
|
+
[AUD]: { access_token: 'cached-for-kernel', expires_at: future() },
|
|
45
|
+
},
|
|
46
|
+
})
|
|
47
|
+
|
|
48
|
+
const result = await runDriver('ensure', { DRIVER_AUDIENCE: AUD })
|
|
49
|
+
|
|
50
|
+
expect(result.ok).toBe(true)
|
|
51
|
+
expect(result.token).toBe('cached-for-kernel')
|
|
52
|
+
expect(result.orgHintCalls).toBe(0)
|
|
53
|
+
expect(server.refreshCount()).toBe(0)
|
|
54
|
+
} finally {
|
|
55
|
+
await server.stop()
|
|
56
|
+
}
|
|
57
|
+
})
|
|
58
|
+
|
|
59
|
+
test('refreshes an expired session, rotating the refresh token and caching by audience', async () => {
|
|
60
|
+
const server = rotationServer()
|
|
61
|
+
try {
|
|
62
|
+
await writeIdpConfig(server.url)
|
|
63
|
+
await writeSession({ expires_at: past() })
|
|
64
|
+
|
|
65
|
+
const result = await runDriver('ensure', { DRIVER_AUDIENCE: AUD, DRIVER_ORG_ID: 'org_1' })
|
|
66
|
+
|
|
67
|
+
expect(result.ok).toBe(true)
|
|
68
|
+
expect(result.orgHintCalls).toBe(1)
|
|
69
|
+
expect(server.refreshCount()).toBe(1)
|
|
70
|
+
const session = await readSession()
|
|
71
|
+
expect(session.refresh_token).toBe('rt-1')
|
|
72
|
+
expect((session.tokens as Record<string, { access_token: string }>)[AUD].access_token).toBe(
|
|
73
|
+
result.token as string,
|
|
74
|
+
)
|
|
75
|
+
expect(server.lastOrganizationId()).toBe('org_1')
|
|
76
|
+
} finally {
|
|
77
|
+
await server.stop()
|
|
78
|
+
}
|
|
79
|
+
})
|
|
80
|
+
|
|
81
|
+
test('two concurrent callers in one process perform exactly one refresh', async () => {
|
|
82
|
+
const server = rotationServer({ delayMs: 50 })
|
|
83
|
+
try {
|
|
84
|
+
await writeIdpConfig(server.url)
|
|
85
|
+
await writeSession({ expires_at: past() })
|
|
86
|
+
|
|
87
|
+
const result = await runDriver('ensure-concurrent')
|
|
88
|
+
|
|
89
|
+
expect(result.ok).toBe(true)
|
|
90
|
+
const [a, b] = result.tokens as [string, string]
|
|
91
|
+
expect(a).toBe(b)
|
|
92
|
+
expect(server.refreshCount()).toBe(1)
|
|
93
|
+
} finally {
|
|
94
|
+
await server.stop()
|
|
95
|
+
}
|
|
96
|
+
})
|
|
97
|
+
|
|
98
|
+
test('two concurrent PROCESSES perform exactly one refresh (single-use token survives)', async () => {
|
|
99
|
+
const server = rotationServer({ delayMs: 50 })
|
|
100
|
+
try {
|
|
101
|
+
await writeIdpConfig(server.url)
|
|
102
|
+
await writeSession({ expires_at: past() })
|
|
103
|
+
|
|
104
|
+
const [a, b] = await Promise.all([runDriver('ensure'), runDriver('ensure')])
|
|
105
|
+
|
|
106
|
+
expect(a.ok).toBe(true)
|
|
107
|
+
expect(b.ok).toBe(true)
|
|
108
|
+
expect(a.token).toBe(b.token)
|
|
109
|
+
expect(server.refreshCount()).toBe(1)
|
|
110
|
+
expect(await lockFilesLeft()).toEqual([])
|
|
111
|
+
} finally {
|
|
112
|
+
await server.stop()
|
|
113
|
+
}
|
|
114
|
+
})
|
|
115
|
+
|
|
116
|
+
test('rescues an invalid_grant raced by a non-locking winner that saved a rotated session', async () => {
|
|
117
|
+
const winnerToken = unsignedJwt({ aud: AUD, exp: futureEpoch() })
|
|
118
|
+
const server = rotationServer({
|
|
119
|
+
beforeRespond: async () => {
|
|
120
|
+
// Simulate an old, non-locking CLI that already exchanged the token
|
|
121
|
+
// and persisted the rotated session before our request landed.
|
|
122
|
+
await writeSession({
|
|
123
|
+
access_token: winnerToken,
|
|
124
|
+
expires_at: future(),
|
|
125
|
+
refresh_token: 'rt-winner',
|
|
126
|
+
updatedAt: new Date(Date.now() + 1000).toISOString(),
|
|
127
|
+
})
|
|
128
|
+
return Response.json(
|
|
129
|
+
{ error: 'invalid_grant', error_description: 'Refresh token already exchanged.' },
|
|
130
|
+
{ status: 400 },
|
|
131
|
+
)
|
|
132
|
+
},
|
|
133
|
+
})
|
|
134
|
+
try {
|
|
135
|
+
await writeIdpConfig(server.url)
|
|
136
|
+
await writeSession({ expires_at: past() })
|
|
137
|
+
|
|
138
|
+
const result = await runDriver('ensure')
|
|
139
|
+
|
|
140
|
+
expect(result.ok).toBe(true)
|
|
141
|
+
expect(result.token).toBe(winnerToken)
|
|
142
|
+
} finally {
|
|
143
|
+
await server.stop()
|
|
144
|
+
}
|
|
145
|
+
})
|
|
146
|
+
|
|
147
|
+
test('reports a missing session when it is deleted while waiting for the lock', async () => {
|
|
148
|
+
const server = rotationServer()
|
|
149
|
+
try {
|
|
150
|
+
await writeIdpConfig(server.url)
|
|
151
|
+
await writeSession({ expires_at: past() })
|
|
152
|
+
const lockPath = join(tmp, 'idp-sessions', 'alice.json.lock')
|
|
153
|
+
await writeFile(lockPath, JSON.stringify({ pid: process.pid }))
|
|
154
|
+
|
|
155
|
+
const pending = runDriver('ensure')
|
|
156
|
+
await new Promise((r) => setTimeout(r, 300))
|
|
157
|
+
await unlink(join(tmp, 'idp-sessions', 'alice.json'))
|
|
158
|
+
await unlink(lockPath)
|
|
159
|
+
const result = await pending
|
|
160
|
+
|
|
161
|
+
expect(result.ok).toBe(false)
|
|
162
|
+
expect(result.errorName).toBe('IdpSessionMissingError')
|
|
163
|
+
expect(await lockFilesLeft()).toEqual([])
|
|
164
|
+
} finally {
|
|
165
|
+
await server.stop()
|
|
166
|
+
}
|
|
167
|
+
})
|
|
168
|
+
|
|
169
|
+
test('classifies a dead grant as session-ended when no winner can rescue it', async () => {
|
|
170
|
+
const server = rotationServer()
|
|
171
|
+
try {
|
|
172
|
+
await writeIdpConfig(server.url)
|
|
173
|
+
await writeSession({ expires_at: past(), refresh_token: 'rt-already-burned' })
|
|
174
|
+
|
|
175
|
+
const result = await runDriver('ensure')
|
|
176
|
+
|
|
177
|
+
expect(result.ok).toBe(false)
|
|
178
|
+
expect(result.errorName).toBe('OAuthTokenError')
|
|
179
|
+
expect(result.errorCode).toBe('invalid_grant')
|
|
180
|
+
expect(result.classification).toBe('session-ended')
|
|
181
|
+
} finally {
|
|
182
|
+
await server.stop()
|
|
183
|
+
}
|
|
184
|
+
})
|
|
185
|
+
|
|
186
|
+
test('classifies an IdP 503 as transient', async () => {
|
|
187
|
+
const server = rotationServer({
|
|
188
|
+
beforeRespond: async () =>
|
|
189
|
+
Response.json({ error_description: 'upstream unavailable' }, { status: 503 }),
|
|
190
|
+
})
|
|
191
|
+
try {
|
|
192
|
+
await writeIdpConfig(server.url)
|
|
193
|
+
await writeSession({ expires_at: past() })
|
|
194
|
+
|
|
195
|
+
const result = await runDriver('ensure')
|
|
196
|
+
|
|
197
|
+
expect(result.ok).toBe(false)
|
|
198
|
+
expect(result.classification).toBe('transient')
|
|
199
|
+
} finally {
|
|
200
|
+
await server.stop()
|
|
201
|
+
}
|
|
202
|
+
})
|
|
203
|
+
|
|
204
|
+
test('classifies an unreachable IdP as transient', async () => {
|
|
205
|
+
const server = rotationServer()
|
|
206
|
+
await server.stop()
|
|
207
|
+
await writeIdpConfig(server.url)
|
|
208
|
+
await writeSession({ expires_at: past() })
|
|
209
|
+
|
|
210
|
+
const result = await runDriver('ensure')
|
|
211
|
+
|
|
212
|
+
expect(result.ok).toBe(false)
|
|
213
|
+
expect(result.classification).toBe('transient')
|
|
214
|
+
})
|
|
215
|
+
})
|
|
216
|
+
|
|
217
|
+
// --- fixtures -------------------------------------------------------------
|
|
218
|
+
|
|
219
|
+
async function writeIdpConfig(baseUrl: string): Promise<void> {
|
|
220
|
+
await mkdir(join(tmp, 'idps', 'test'), { recursive: true })
|
|
221
|
+
await writeFile(
|
|
222
|
+
join(tmp, 'idps', 'index.json'),
|
|
223
|
+
JSON.stringify({
|
|
224
|
+
idps: {
|
|
225
|
+
test: {
|
|
226
|
+
issuer: baseUrl,
|
|
227
|
+
createdAt: '2026-01-01T00:00:00.000Z',
|
|
228
|
+
updatedAt: '2026-01-01T00:00:00.000Z',
|
|
229
|
+
},
|
|
230
|
+
},
|
|
231
|
+
}),
|
|
232
|
+
)
|
|
233
|
+
await writeFile(
|
|
234
|
+
join(tmp, 'idps', 'test', 'metadata.json'),
|
|
235
|
+
JSON.stringify({
|
|
236
|
+
issuer: baseUrl,
|
|
237
|
+
token_endpoint: `${baseUrl}/token`,
|
|
238
|
+
jwks_uri: `${baseUrl}/jwks`,
|
|
239
|
+
}),
|
|
240
|
+
)
|
|
241
|
+
await writeFile(join(tmp, 'idps', 'test', 'client.json'), JSON.stringify({ client_id: 'c_1' }))
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
async function writeSession(overrides: Record<string, unknown>): Promise<void> {
|
|
245
|
+
await writeFile(
|
|
246
|
+
join(tmp, 'idp-sessions', 'alice.json'),
|
|
247
|
+
JSON.stringify({
|
|
248
|
+
identity: 'alice',
|
|
249
|
+
idp: 'test',
|
|
250
|
+
issuer: 'https://idp.example.com',
|
|
251
|
+
subject: 'user_123',
|
|
252
|
+
access_token: 'expired-access-token',
|
|
253
|
+
refresh_token: 'rt-0',
|
|
254
|
+
token_type: 'Bearer',
|
|
255
|
+
updatedAt: '2026-01-01T00:00:00.000Z',
|
|
256
|
+
...overrides,
|
|
257
|
+
}),
|
|
258
|
+
)
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
async function readSession(): Promise<Record<string, unknown>> {
|
|
262
|
+
return JSON.parse(await readFile(join(tmp, 'idp-sessions', 'alice.json'), 'utf-8'))
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
async function lockFilesLeft(): Promise<string[]> {
|
|
266
|
+
const entries = await readdir(join(tmp, 'idp-sessions'))
|
|
267
|
+
return entries.filter((e) => e.endsWith('.lock') || e.endsWith('.tmp'))
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
function rotationServer(opts?: {
|
|
271
|
+
delayMs?: number
|
|
272
|
+
beforeRespond?: () => Promise<Response | undefined>
|
|
273
|
+
}): {
|
|
274
|
+
url: string
|
|
275
|
+
refreshCount: () => number
|
|
276
|
+
lastOrganizationId: () => string | undefined
|
|
277
|
+
stop: () => Promise<void>
|
|
278
|
+
} {
|
|
279
|
+
// WorkOS-style single-use rotation: presenting anything but the CURRENT
|
|
280
|
+
// refresh token is invalid_grant.
|
|
281
|
+
let current = 'rt-0'
|
|
282
|
+
let count = 0
|
|
283
|
+
let lastOrgId: string | undefined
|
|
284
|
+
const server = Bun.serve({
|
|
285
|
+
port: 0,
|
|
286
|
+
fetch: async (request) => {
|
|
287
|
+
const url = new URL(request.url)
|
|
288
|
+
if (url.pathname !== '/token') return new Response('not found', { status: 404 })
|
|
289
|
+
const form = new URLSearchParams(await request.text())
|
|
290
|
+
if (opts?.beforeRespond) {
|
|
291
|
+
const response = await opts.beforeRespond()
|
|
292
|
+
if (response) return response
|
|
293
|
+
}
|
|
294
|
+
if (form.get('refresh_token') !== current) {
|
|
295
|
+
return Response.json(
|
|
296
|
+
{ error: 'invalid_grant', error_description: 'Refresh token already exchanged.' },
|
|
297
|
+
{ status: 400 },
|
|
298
|
+
)
|
|
299
|
+
}
|
|
300
|
+
if (opts?.delayMs) await new Promise((r) => setTimeout(r, opts.delayMs))
|
|
301
|
+
count += 1
|
|
302
|
+
current = `rt-${count}`
|
|
303
|
+
lastOrgId = form.get('organization_id') ?? undefined
|
|
304
|
+
return Response.json({
|
|
305
|
+
access_token: unsignedJwt({ aud: AUD, exp: futureEpoch() }),
|
|
306
|
+
refresh_token: current,
|
|
307
|
+
token_type: 'Bearer',
|
|
308
|
+
expires_in: 3600,
|
|
309
|
+
})
|
|
310
|
+
},
|
|
311
|
+
})
|
|
312
|
+
return {
|
|
313
|
+
url: `http://${server.hostname}:${server.port}`,
|
|
314
|
+
refreshCount: () => count,
|
|
315
|
+
lastOrganizationId: () => lastOrgId,
|
|
316
|
+
stop: () => server.stop(true),
|
|
317
|
+
}
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
async function runDriver(
|
|
321
|
+
scenario: string,
|
|
322
|
+
env: Record<string, string> = {},
|
|
323
|
+
): Promise<Record<string, unknown> & { tokens?: unknown }> {
|
|
324
|
+
const proc = Bun.spawn({
|
|
325
|
+
cmd: ['bun', join(import.meta.dir, 'idp-session.driver.ts'), scenario],
|
|
326
|
+
env: { ...process.env, ASTRALE_HOME: tmp, ...env },
|
|
327
|
+
stdout: 'pipe',
|
|
328
|
+
stderr: 'pipe',
|
|
329
|
+
})
|
|
330
|
+
const [stdout, stderr, exitCode] = await Promise.all([
|
|
331
|
+
new Response(proc.stdout).text(),
|
|
332
|
+
new Response(proc.stderr).text(),
|
|
333
|
+
proc.exited,
|
|
334
|
+
])
|
|
335
|
+
if (exitCode !== 0) throw new Error(`driver exited ${exitCode}: ${stderr}`)
|
|
336
|
+
return JSON.parse(stdout.trim().split('\n').at(-1) ?? '{}')
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
function unsignedJwt(payload: Record<string, unknown>): string {
|
|
340
|
+
return [base64url({ alg: 'none', typ: 'JWT' }), base64url(payload), ''].join('.')
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
function base64url(value: Record<string, unknown>): string {
|
|
344
|
+
return Buffer.from(JSON.stringify(value)).toString('base64url')
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
function future(): string {
|
|
348
|
+
return new Date(Date.now() + 3_600_000).toISOString()
|
|
349
|
+
}
|
|
350
|
+
|
|
351
|
+
function futureEpoch(): number {
|
|
352
|
+
return Math.floor(Date.now() / 1000) + 3600
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
function past(): string {
|
|
356
|
+
return new Date(Date.now() - 3_600_000).toISOString()
|
|
357
|
+
}
|