@astrale-os/kernel-client 0.6.0-beta.88 → 1.0.0-beta.1

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.
@@ -5,8 +5,8 @@ export interface SessionCredential {
5
5
  /** Absolute Unix time in milliseconds. */
6
6
  readonly expiresAt: number;
7
7
  }
8
- /** Observable lifecycle of the single credential one provider owns. */
9
- export type SessionCredentialState = {
8
+ /** Observable lifecycle of the single credential one Credentials owns. */
9
+ export type CredentialsState = {
10
10
  readonly status: 'empty';
11
11
  } | {
12
12
  readonly status: 'valid';
@@ -22,23 +22,28 @@ export type SessionCredentialState = {
22
22
  readonly status: 'expired';
23
23
  readonly error: unknown;
24
24
  };
25
- export interface SessionCredentialProviderOptions {
25
+ /**
26
+ * Acquire one fresh credential: a compact JWT, whose `exp` claim is its expiry, or an explicit
27
+ * credential and expiry. The supplied signal is owned by Credentials.
28
+ */
29
+ export type CredentialsMint = (signal: AbortSignal) => string | SessionCredential | PromiseLike<string | SessionCredential>;
30
+ export interface CredentialsOptions {
26
31
  /** Delegation TTL every served credential must still cover; also the SessionAuth TTL. */
27
- readonly ttlSeconds: number;
28
- /** Acquire one fresh credential; the supplied signal is owned by the provider. */
29
- mint(signal: AbortSignal): Promise<SessionCredential>;
32
+ readonly ttlSeconds?: number;
33
+ /** Renew the credential. Without it, the initial credential is served until it stops covering. */
34
+ readonly mint?: CredentialsMint;
30
35
  /** Caller-held credential admitted as the initial entry; it need only be unexpired. */
31
- readonly initial?: SessionCredential;
32
- readonly onChange?: (state: SessionCredentialState) => void;
36
+ readonly initial?: string | SessionCredential;
37
+ readonly onChange?: (state: CredentialsState) => void;
33
38
  }
34
39
  /**
35
40
  * Caller-owned source credential with a derived refresh threshold and shared minting.
36
41
  *
37
- * The provider is a SessionAuth, so a ClientSession consumes it directly. Anticipation is opt-in:
42
+ * Credentials is a SessionAuth, so a ClientSession consumes it directly. Anticipation is opt-in:
38
43
  * an ephemeral process or a request-scoped worker never holds a pending timer it did not ask for.
39
44
  */
40
- export interface SessionCredentialProvider extends SessionAuth {
41
- state(): SessionCredentialState;
45
+ export interface Credentials extends SessionAuth {
46
+ state(): CredentialsState;
42
47
  /** Serve a credential that still covers the delegation TTL; concurrent callers share one mint. */
43
48
  acquire(signal?: AbortSignal): Promise<SessionCredential>;
44
49
  /** Mint regardless of the current credential, joining a mint already in flight. */
@@ -53,4 +58,8 @@ export interface SessionCredentialProvider extends SessionAuth {
53
58
  * plus the settlement skew, so it cannot expire between admission and delivery.
54
59
  */
55
60
  export declare function delegationCoverageMs(ttlSeconds: number): number;
56
- export declare function createSessionCredentialProvider(options: SessionCredentialProviderOptions): SessionCredentialProvider;
61
+ /**
62
+ * Hold one source credential for a Session: a fixed credential, a mint that renews it on demand,
63
+ * or options that also seed it, observe it, or change the delegation TTL it must cover.
64
+ */
65
+ export declare function credentials(source: string | CredentialsMint | CredentialsOptions): Credentials;
@@ -1,5 +1,6 @@
1
+ import { inspect } from '@astrale-os/kernel-core/auth/credential';
1
2
  import { ClientError } from '../../errors/index.js';
2
- import { BACKOFF_MS, MINT_TIMEOUT_MS, RETRY_INTERVAL_MS, SETTLEMENT_SKEW_MS } from './limits.js';
3
+ import { BACKOFF_MS, DEFAULT_TTL_SECONDS, MINT_TIMEOUT_MS, RETRY_INTERVAL_MS, SETTLEMENT_SKEW_MS, } from './limits.js';
3
4
  /**
4
5
  * Remaining lifetime a credential must exceed to carry a delegation of `ttlSeconds`: the TTL itself
5
6
  * plus the settlement skew, so it cannot expire between admission and delivery.
@@ -7,21 +8,26 @@ import { BACKOFF_MS, MINT_TIMEOUT_MS, RETRY_INTERVAL_MS, SETTLEMENT_SKEW_MS } fr
7
8
  export function delegationCoverageMs(ttlSeconds) {
8
9
  return ttlSeconds * 1_000 + SETTLEMENT_SKEW_MS;
9
10
  }
10
- export function createSessionCredentialProvider(options) {
11
- if (options === null || typeof options !== 'object') {
12
- throw new TypeError('Session credential provider options are invalid.');
13
- }
14
- if (typeof options.mint !== 'function') {
11
+ /**
12
+ * Hold one source credential for a Session: a fixed credential, a mint that renews it on demand,
13
+ * or options that also seed it, observe it, or change the delegation TTL it must cover.
14
+ */
15
+ export function credentials(source) {
16
+ const options = admitSource(source);
17
+ if (options.mint !== undefined && typeof options.mint !== 'function') {
15
18
  throw new TypeError('Session credential mint capability is invalid.');
16
19
  }
17
- if (!Number.isSafeInteger(options.ttlSeconds) || options.ttlSeconds < 1) {
20
+ if (options.mint === undefined && options.initial === undefined) {
21
+ throw new TypeError('Session credentials need a mint or an initial credential.');
22
+ }
23
+ const ttlSeconds = options.ttlSeconds ?? DEFAULT_TTL_SECONDS;
24
+ if (!Number.isSafeInteger(ttlSeconds) || ttlSeconds < 1) {
18
25
  throw new TypeError('Session credential ttlSeconds must be a positive safe integer.');
19
26
  }
20
27
  if (options.onChange !== undefined && typeof options.onChange !== 'function') {
21
28
  throw new TypeError('Session credential change observer is invalid.');
22
29
  }
23
- const { ttlSeconds } = options;
24
- const mint = options.mint.bind(options);
30
+ const mint = options.mint?.bind(options);
25
31
  const notify = options.onChange?.bind(options);
26
32
  // The threshold is the coverage the caller already declared, never a separate guessed constant.
27
33
  const marginMs = delegationCoverageMs(ttlSeconds);
@@ -109,13 +115,19 @@ export function createSessionCredentialProvider(options) {
109
115
  });
110
116
  }
111
117
  function begin() {
118
+ if (mint === undefined) {
119
+ const error = new ClientError('Session credential needs renewal, but no mint was supplied.');
120
+ settleFailure(error);
121
+ return Promise.reject(error);
122
+ }
123
+ const renew = mint;
112
124
  publish({ status: 'refreshing', ...(current === undefined ? {} : { credential: current }) });
113
125
  const owned = new AbortController();
114
126
  controller = owned;
115
127
  const signal = AbortSignal.any([owned.signal, AbortSignal.timeout(MINT_TIMEOUT_MS)]);
116
128
  const pending = (async () => {
117
129
  try {
118
- const minted = admitMinted(await mint(signal));
130
+ const minted = admitMinted(await renew(signal));
119
131
  current = minted;
120
132
  attempt = 0;
121
133
  publish({ status: 'valid', credential: minted });
@@ -165,11 +177,14 @@ export function createSessionCredentialProvider(options) {
165
177
  function retry() {
166
178
  if (refreshTimer !== undefined)
167
179
  return;
180
+ if (current !== undefined)
181
+ armExpiry(current);
182
+ // Without a mint nothing can replace the held credential; only its expiry remains to report.
183
+ if (mint === undefined)
184
+ return;
168
185
  const backoff = BACKOFF_MS[attempt];
169
186
  attempt = Math.min(attempt + 1, BACKOFF_MS.length);
170
187
  armRefresh(backoff ?? RETRY_INTERVAL_MS);
171
- if (current !== undefined)
172
- armExpiry(current);
173
188
  }
174
189
  function armRefresh(delay) {
175
190
  refreshTimer = setTimeout(() => {
@@ -204,22 +219,67 @@ export function createSessionCredentialProvider(options) {
204
219
  notify?.(state);
205
220
  }
206
221
  function admitMinted(input) {
222
+ if (typeof input === 'string') {
223
+ const credential = fromCompactJwt(input);
224
+ if (credential === undefined) {
225
+ throw new ClientError('Minted session credential carries no expiry; return { credential, expiresAt }.');
226
+ }
227
+ return admitCovering(credential);
228
+ }
207
229
  const credential = admitShape(input);
208
230
  if (credential === undefined)
209
231
  throw new ClientError('Minted session credential is invalid.');
232
+ return admitCovering(credential);
233
+ }
234
+ function admitCovering(credential) {
210
235
  if (!covers(credential)) {
211
236
  throw new ClientError('Minted session credential cannot cover the delegation TTL.');
212
237
  }
213
238
  return credential;
214
239
  }
215
240
  }
241
+ /** A bare credential is fixed, a function mints; anything else must already be options. */
242
+ function admitSource(source) {
243
+ if (source === undefined || source === null || source === '') {
244
+ throw new TypeError('Session credential is missing.');
245
+ }
246
+ if (typeof source === 'string')
247
+ return { initial: source };
248
+ if (typeof source === 'function')
249
+ return { mint: source };
250
+ if (typeof source !== 'object')
251
+ throw new TypeError('Session credentials source is invalid.');
252
+ return source;
253
+ }
216
254
  function admitInitial(input) {
217
- const credential = admitShape(input);
218
- if (credential === undefined || credential.expiresAt <= Date.now()) {
219
- throw new TypeError('Initial session credential is invalid.');
255
+ const credential = typeof input === 'string' ? fromCompactJwt(input) : admitShape(input);
256
+ if (credential === undefined) {
257
+ throw new TypeError(typeof input === 'string'
258
+ ? 'Session credential carries no expiry; supply { credential, expiresAt }.'
259
+ : 'Initial session credential is invalid.');
260
+ }
261
+ if (credential.expiresAt <= Date.now()) {
262
+ throw new TypeError('Initial session credential has expired.');
220
263
  }
221
264
  return credential;
222
265
  }
266
+ /** Read the expiry a compact JWT declares; an opaque or expiry-less credential yields none. */
267
+ function fromCompactJwt(input) {
268
+ if (input.length === 0)
269
+ return undefined;
270
+ let exp;
271
+ try {
272
+ exp = inspect(input).claims.exp;
273
+ }
274
+ catch {
275
+ return undefined;
276
+ }
277
+ if (typeof exp !== 'number' || !Number.isSafeInteger(exp) || exp < 1)
278
+ return undefined;
279
+ if (!Number.isSafeInteger(exp * 1_000))
280
+ return undefined;
281
+ return Object.freeze({ credential: input, expiresAt: exp * 1_000 });
282
+ }
223
283
  function admitShape(input) {
224
284
  if (input === null ||
225
285
  typeof input !== 'object' ||
@@ -1 +1 @@
1
- export { createSessionCredentialProvider, delegationCoverageMs, type SessionCredential, type SessionCredentialProvider, type SessionCredentialProviderOptions, type SessionCredentialState, } from './provider.js';
1
+ export { credentials, delegationCoverageMs, type Credentials, type CredentialsMint, type CredentialsOptions, type CredentialsState, type SessionCredential, } from './credentials.js';
@@ -1 +1 @@
1
- export { createSessionCredentialProvider, delegationCoverageMs, } from './provider.js';
1
+ export { credentials, delegationCoverageMs, } from './credentials.js';
@@ -1,3 +1,5 @@
1
+ /** Delegation TTL a Credentials serves when its caller declares none. */
2
+ export declare const DEFAULT_TTL_SECONDS = 60;
1
3
  /**
2
4
  * Settlement allowance added to the declared delegation TTL to form the refresh threshold. It
3
5
  * matches the destination-credential skew routing already applies to a warm entry, so a credential
@@ -1,3 +1,5 @@
1
+ /** Delegation TTL a Credentials serves when its caller declares none. */
2
+ export const DEFAULT_TTL_SECONDS = 60;
1
3
  /**
2
4
  * Settlement allowance added to the declared delegation TTL to form the refresh threshold. It
3
5
  * matches the destination-credential skew routing already applies to a warm entry, so a credential
@@ -1,6 +1,6 @@
1
1
  import { ClientError } from '../../errors/index.js';
2
2
  import { runSessionOperation } from '../context/index.js';
3
- import { createSessionCredentialProvider, delegationCoverageMs } from '../credential/index.js';
3
+ import { credentials, delegationCoverageMs } from '../credential/index.js';
4
4
  import { createInstallations, declaringOrigin, isKernelOrigin } from './domain.js';
5
5
  import { exchangeDomainCredential } from './exchange.js';
6
6
  import { MAXIMUM_EXCHANGE_SOURCES } from './limits.js';
@@ -32,8 +32,8 @@ export function createSessionExchange(dependencies, options) {
32
32
  if (source.delegate.ttlSeconds > auth.ttlSeconds) {
33
33
  throw new ClientError('Session delegation outlives the Domain credential it would carry.');
34
34
  }
35
- const provider = providerFor(source, domain);
36
- const exchanged = await runSessionOperation(operation, (signal) => provider.acquire(signal));
35
+ const domainCredentials = credentialsFor(source, domain);
36
+ const exchanged = await runSessionOperation(operation, (signal) => domainCredentials.acquire(signal));
37
37
  return Object.freeze({ credential: exchanged.credential, delegate: source.delegate });
38
38
  });
39
39
  }
@@ -41,12 +41,12 @@ export function createSessionExchange(dependencies, options) {
41
41
  installations.clear();
42
42
  sources.clear();
43
43
  }
44
- function providerFor(source, domain) {
44
+ function credentialsFor(source, domain) {
45
45
  const held = heldFor(source.credential);
46
46
  const known = held.get(domain);
47
47
  if (known !== undefined)
48
48
  return known;
49
- const provider = createSessionCredentialProvider({
49
+ const domainCredentials = credentials({
50
50
  ttlSeconds: auth.ttlSeconds,
51
51
  mint: (signal) => exchangeDomainCredential(dependencies, source, {
52
52
  issuer: domain,
@@ -54,8 +54,8 @@ export function createSessionExchange(dependencies, options) {
54
54
  coverageMs,
55
55
  }, dependencies.operation(signal)),
56
56
  });
57
- held.set(domain, provider);
58
- return provider;
57
+ held.set(domain, domainCredentials);
58
+ return domainCredentials;
59
59
  }
60
60
  /** Domain credentials never cross source credentials; the oldest source is forgotten first. */
61
61
  function heldFor(credential) {
@@ -1,7 +1,7 @@
1
1
  export type { SessionControlOptions, SessionPolicy } from './context/index.js';
2
2
  export type { ContentApi, ContentDownload, ContentLocation, ContentRejection, ContentUploadOptions, ContentUploadResult, } from './content/index.js';
3
3
  export { bindSession, type BoundClientSession, type BoundSessionControls, type BoundSessionSource, } from './bound.js';
4
- export { createSessionCredentialProvider, type SessionCredential, type SessionCredentialProvider, type SessionCredentialProviderOptions, type SessionCredentialState, } from './credential/index.js';
4
+ export { credentials, type Credentials, type CredentialsMint, type CredentialsOptions, type CredentialsState, type SessionCredential, } from './credential/index.js';
5
5
  export type { IntrinsicRelease, SessionSnapshot } from './discovery/index.js';
6
6
  export type { SessionExchangeOptions, SessionExchangeRequest } from './exchange/index.js';
7
7
  export type { Auth, PersistedRoute, SessionRouteArtifact, SessionRouteStore, SessionAuth, SessionEnvelopeTransport, SessionRequestOptions, SessionRequestOptionsWithBody, } from './routing/index.js';
@@ -1,5 +1,5 @@
1
1
  export { bindSession, } from './bound.js';
2
- export { createSessionCredentialProvider, } from './credential/index.js';
2
+ export { credentials, } from './credential/index.js';
3
3
  export { ClientSession, connect } from './session.js';
4
4
  export { reference } from './reference.js';
5
5
  export { execution, } from './execution.js';
@@ -41,7 +41,7 @@ export declare class ClientSession {
41
41
  /**
42
42
  * Delegate this Session's caller to one Domain issuer and exchange that delegation for the
43
43
  * Domain's credential to this Kernel. Nothing is cached: hold the result, for example through
44
- * `createSessionCredentialProvider`, for as long as it covers the calls it carries.
44
+ * `credentials`, for as long as it covers the calls it carries.
45
45
  */
46
46
  exchange(domain: string, options?: SessionExchangeRequest): Promise<SessionCredential>;
47
47
  /**
@@ -107,7 +107,7 @@ export class ClientSession {
107
107
  /**
108
108
  * Delegate this Session's caller to one Domain issuer and exchange that delegation for the
109
109
  * Domain's credential to this Kernel. Nothing is cached: hold the result, for example through
110
- * `createSessionCredentialProvider`, for as long as it covers the calls it carries.
110
+ * `credentials`, for as long as it covers the calls it carries.
111
111
  */
112
112
  async exchange(domain, options) {
113
113
  const request = admitExchangeRequest(domain, options);
@@ -4,7 +4,7 @@ import { K, KernelSchema } from '@astrale-os/kernel-core/schema';
4
4
  import { defineSchema, func, method, nodeClass, schema, valueSchema, } from '@astrale-os/kernel-dsl/v1';
5
5
  import { isBinaryInput } from '@astrale-os/kernel-dsl/v1/language';
6
6
  import { call } from '../client/index.js';
7
- import { ClientSession, createSessionCredentialProvider, execution, reference } from './index.js';
7
+ import { ClientSession, credentials, execution, reference } from './index.js';
8
8
  void new ClientSession(options);
9
9
  void auth;
10
10
  void control;
@@ -29,12 +29,15 @@ void session.auth.admit({ target: Path.parse('/:example.test:function.write'), i
29
29
  { attenuation: { kind: 'identity', self: true } });
30
30
  // @ts-expect-error Admission belongs to Auth, not the top-level Session.
31
31
  void session.admit({ target: Path.parse('/:example.test:function.write'), input: {} });
32
- const credentials = createSessionCredentialProvider({
33
- ttlSeconds: 60,
34
- mint: async () => minted,
35
- });
36
- // A credential provider is a Session authentication resolver; no adapter stands between them.
37
- const credentialAuth = credentials;
32
+ const held = credentials({ ttlSeconds: 60, mint: async () => minted });
33
+ // Credentials is a Session authentication resolver; no adapter stands between them.
34
+ const credentialAuth = held;
35
+ void new ClientSession({ ...options, auth: credentials(minted.credential) });
36
+ void new ClientSession({ ...options, auth: credentials(async () => minted.credential) });
37
+ void new ClientSession({ ...options, auth: credentials(() => minted) });
38
+ void credentials({ initial: minted.credential, onChange: (state) => void state.status });
39
+ // @ts-expect-error A credential that may be missing is refused before any call.
40
+ void credentials(configured);
38
41
  void new ClientSession({ ...options, auth: credentialAuth });
39
42
  void new ClientSession({ ...options, auth: credentialAuth, exchange: { mode: 'auto' } });
40
43
  void new ClientSession({
@@ -53,8 +56,8 @@ void new ClientSession({ ...options, exchange: { mode: 'source', ttlSeconds: 300
53
56
  void new ClientSession({ ...options, exchange: true });
54
57
  // @ts-expect-error Unknown exchange modes are not admitted.
55
58
  void new ClientSession({ ...options, exchange: { mode: 'invalid' } });
56
- // @ts-expect-error A minted credential must carry its own absolute expiry.
57
- void createSessionCredentialProvider({ ttlSeconds: 60, mint: async () => minted.credential });
59
+ // @ts-expect-error A minted credential is a credential string or a credential with its expiry.
60
+ void credentials(async () => ({ credential: minted.credential }));
58
61
  const dynamicReference = reference(dynamicDomain, dynamicMethod)(Path.id(NodeId('dynamic-node')));
59
62
  void session.invoke(dynamicReference, dynamicInput);
60
63
  const dynamicInputIsClientInput = true;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@astrale-os/kernel-client",
3
- "version": "0.6.0-beta.88",
3
+ "version": "1.0.0-beta.1",
4
4
  "description": "Universal Client — protocol-first, transport-agnostic",
5
5
  "keywords": [
6
6
  "astrale",
@@ -65,13 +65,13 @@
65
65
  "access": "public"
66
66
  },
67
67
  "dependencies": {
68
- "@astrale-os/kernel-core": "0.9.0-beta.67",
69
- "@astrale-os/kernel-dsl": "0.2.0-beta.49",
70
- "@astrale-os/kernel-protocol": "0.5.0-beta.73",
68
+ "@astrale-os/kernel-core": "1.0.0-beta.1",
69
+ "@astrale-os/kernel-dsl": "1.0.0-beta.1",
70
+ "@astrale-os/kernel-protocol": "1.0.0-beta.1",
71
71
  "@tanstack/pacer": "0.20.1"
72
72
  },
73
73
  "devDependencies": {
74
- "@astrale-os/kernel-server": "0.5.0-beta.75",
74
+ "@astrale-os/kernel-server": "1.0.0-beta.1",
75
75
  "@astrale/typescript-config": "npm:@jsr/astrale__typescript-config@~1.1.0",
76
76
  "@types/node": "^22.0.0",
77
77
  "typescript": "7.0.2",