@cortexkit/common-auth 0.19.1 → 0.21.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/claustrum/availability.d.ts +89 -0
- package/dist/claustrum/availability.js +106 -0
- package/dist/claustrum/consumer.d.ts +31 -1
- package/dist/claustrum/consumer.js +130 -5
- package/dist/claustrum/custody.d.ts +46 -14
- package/dist/claustrum/custody.js +225 -16
- package/dist/claustrum/errors.d.ts +1 -0
- package/dist/claustrum/index.d.ts +5 -3
- package/dist/claustrum/index.js +3 -1
- package/dist/claustrum/insula.d.ts +48 -0
- package/dist/claustrum/insula.js +286 -21
- package/dist/claustrum/watch.d.ts +140 -0
- package/dist/claustrum/watch.js +253 -0
- package/dist/fs/private-files.js +10 -2
- package/dist/quota/format.d.ts +3 -0
- package/dist/quota/format.js +69 -1
- package/dist/quota/index.d.ts +1 -1
- package/dist/quota/projection.d.ts +16 -0
- package/package.json +4 -4
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
import { ClaustrumConsumerError } from './errors.js';
|
|
2
|
+
export type VaultFailureClass = 'unreachable' | 'answered';
|
|
3
|
+
/**
|
|
4
|
+
* Codes from claustrum-client's decoder and its subc transport. A retry action
|
|
5
|
+
* alone is not evidence of an outage: even transient vault refusals must win
|
|
6
|
+
* over a previously served credential. New codes fail closed until reviewed.
|
|
7
|
+
*/
|
|
8
|
+
export declare const VAULT_FAILURE_CLASSES: Readonly<{
|
|
9
|
+
ECONNREFUSED: "unreachable";
|
|
10
|
+
ENOENT: "unreachable";
|
|
11
|
+
ECONNRESET: "unreachable";
|
|
12
|
+
EPIPE: "unreachable";
|
|
13
|
+
ETIMEDOUT: "unreachable";
|
|
14
|
+
transport_error: "unreachable";
|
|
15
|
+
unavailable: "unreachable";
|
|
16
|
+
timeout: "unreachable";
|
|
17
|
+
route_closed: "unreachable";
|
|
18
|
+
daemon_draining: "unreachable";
|
|
19
|
+
connection_closed: "unreachable";
|
|
20
|
+
connection_dropped: "unreachable";
|
|
21
|
+
request_deadline: "unreachable";
|
|
22
|
+
deadline_exceeded_no_drop_observed: "unreachable";
|
|
23
|
+
module_reloading: "unreachable";
|
|
24
|
+
module_warming: "unreachable";
|
|
25
|
+
target_unavailable: "unreachable";
|
|
26
|
+
module_timeout: "unreachable";
|
|
27
|
+
invalid_response: "answered";
|
|
28
|
+
invalid_record_version: "answered";
|
|
29
|
+
invalid_expiry: "answered";
|
|
30
|
+
invalid_status: "answered";
|
|
31
|
+
invalid_params: "answered";
|
|
32
|
+
ttl_unsatisfiable: "answered";
|
|
33
|
+
not_found: "answered";
|
|
34
|
+
enrollment_revoked: "answered";
|
|
35
|
+
enrollment_invalid: "answered";
|
|
36
|
+
grant_denied: "answered";
|
|
37
|
+
credential_unavailable: "answered";
|
|
38
|
+
needs_reauth: "answered";
|
|
39
|
+
declined: "answered";
|
|
40
|
+
disabled: "answered";
|
|
41
|
+
identity_changed: "answered";
|
|
42
|
+
closed: "answered";
|
|
43
|
+
client_closed: "answered";
|
|
44
|
+
pending_exists: "answered";
|
|
45
|
+
pending_queue_full: "answered";
|
|
46
|
+
already_consumed: "answered";
|
|
47
|
+
superseded: "answered";
|
|
48
|
+
stale_generation: "answered";
|
|
49
|
+
missing_identity: "answered";
|
|
50
|
+
invalid_control_body: "answered";
|
|
51
|
+
unknown_module: "answered";
|
|
52
|
+
module_removed: "answered";
|
|
53
|
+
capability_denied: "answered";
|
|
54
|
+
unknown_channel: "unreachable";
|
|
55
|
+
stale_route_epoch: "unreachable";
|
|
56
|
+
capability_forbidden: "answered";
|
|
57
|
+
capability_unprovided: "answered";
|
|
58
|
+
capability_ambiguous: "answered";
|
|
59
|
+
invalid_capability_identifier: "answered";
|
|
60
|
+
binary_body_required: "answered";
|
|
61
|
+
binary_call_requires_call_binary: "answered";
|
|
62
|
+
corr_exhausted: "answered";
|
|
63
|
+
late_route_cleanup_failed: "answered";
|
|
64
|
+
reverse_request_capability_not_declared: "answered";
|
|
65
|
+
stale_route_handle: "answered";
|
|
66
|
+
reverse_request_unhandled: "answered";
|
|
67
|
+
handler_error: "answered";
|
|
68
|
+
health_error: "answered";
|
|
69
|
+
duplicate_module_id: "answered";
|
|
70
|
+
route_rejected: "answered";
|
|
71
|
+
lock_busy: "answered";
|
|
72
|
+
owner_invalid: "answered";
|
|
73
|
+
renewal_failed: "answered";
|
|
74
|
+
unsupported_platform: "answered";
|
|
75
|
+
EACCES: "answered";
|
|
76
|
+
EPERM: "answered";
|
|
77
|
+
ERR_PRIVATE_FILES_SECURITY: "answered";
|
|
78
|
+
}>;
|
|
79
|
+
/**
|
|
80
|
+
* An injected adapter may throw this ONLY when its connection/transport is
|
|
81
|
+
* unreachable, including a failed connect before getScoped. Do not wrap an
|
|
82
|
+
* adapter shutdown, cancellation, validation error or vault refusal in it.
|
|
83
|
+
* Its fixed message cannot echo enrollment or credential material, and its
|
|
84
|
+
* kind stays `unavailable` for callers handling ClaustrumConsumerError.
|
|
85
|
+
*/
|
|
86
|
+
export declare class ClaustrumUnreachableError extends ClaustrumConsumerError {
|
|
87
|
+
constructor();
|
|
88
|
+
}
|
|
89
|
+
export declare function classifyVaultFailure(error: unknown): VaultFailureClass;
|
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
import { ClaustrumCredentialError } from '@cortexkit/claustrum-client';
|
|
2
|
+
import { SocketClosedError, SocketTimeoutError, SubcCallError, } from '@cortexkit/subc-client';
|
|
3
|
+
import { ClaustrumConsumerError } from './errors.js';
|
|
4
|
+
/**
|
|
5
|
+
* Codes from claustrum-client's decoder and its subc transport. A retry action
|
|
6
|
+
* alone is not evidence of an outage: even transient vault refusals must win
|
|
7
|
+
* over a previously served credential. New codes fail closed until reviewed.
|
|
8
|
+
*/
|
|
9
|
+
export const VAULT_FAILURE_CLASSES = Object.freeze({
|
|
10
|
+
ECONNREFUSED: 'unreachable',
|
|
11
|
+
ENOENT: 'unreachable',
|
|
12
|
+
ECONNRESET: 'unreachable',
|
|
13
|
+
EPIPE: 'unreachable',
|
|
14
|
+
ETIMEDOUT: 'unreachable',
|
|
15
|
+
transport_error: 'unreachable',
|
|
16
|
+
unavailable: 'unreachable',
|
|
17
|
+
timeout: 'unreachable',
|
|
18
|
+
route_closed: 'unreachable',
|
|
19
|
+
daemon_draining: 'unreachable',
|
|
20
|
+
connection_closed: 'unreachable',
|
|
21
|
+
connection_dropped: 'unreachable',
|
|
22
|
+
request_deadline: 'unreachable',
|
|
23
|
+
deadline_exceeded_no_drop_observed: 'unreachable',
|
|
24
|
+
module_reloading: 'unreachable',
|
|
25
|
+
module_warming: 'unreachable',
|
|
26
|
+
target_unavailable: 'unreachable',
|
|
27
|
+
module_timeout: 'unreachable',
|
|
28
|
+
invalid_response: 'answered',
|
|
29
|
+
invalid_record_version: 'answered',
|
|
30
|
+
invalid_expiry: 'answered',
|
|
31
|
+
invalid_status: 'answered',
|
|
32
|
+
invalid_params: 'answered',
|
|
33
|
+
ttl_unsatisfiable: 'answered',
|
|
34
|
+
not_found: 'answered',
|
|
35
|
+
enrollment_revoked: 'answered',
|
|
36
|
+
enrollment_invalid: 'answered',
|
|
37
|
+
grant_denied: 'answered',
|
|
38
|
+
credential_unavailable: 'answered',
|
|
39
|
+
needs_reauth: 'answered',
|
|
40
|
+
declined: 'answered',
|
|
41
|
+
disabled: 'answered',
|
|
42
|
+
identity_changed: 'answered',
|
|
43
|
+
closed: 'answered',
|
|
44
|
+
client_closed: 'answered',
|
|
45
|
+
pending_exists: 'answered',
|
|
46
|
+
pending_queue_full: 'answered',
|
|
47
|
+
already_consumed: 'answered',
|
|
48
|
+
superseded: 'answered',
|
|
49
|
+
stale_generation: 'answered',
|
|
50
|
+
missing_identity: 'answered',
|
|
51
|
+
invalid_control_body: 'answered',
|
|
52
|
+
unknown_module: 'answered',
|
|
53
|
+
module_removed: 'answered',
|
|
54
|
+
capability_denied: 'answered',
|
|
55
|
+
unknown_channel: 'unreachable',
|
|
56
|
+
stale_route_epoch: 'unreachable',
|
|
57
|
+
capability_forbidden: 'answered',
|
|
58
|
+
capability_unprovided: 'answered',
|
|
59
|
+
capability_ambiguous: 'answered',
|
|
60
|
+
invalid_capability_identifier: 'answered',
|
|
61
|
+
binary_body_required: 'answered',
|
|
62
|
+
binary_call_requires_call_binary: 'answered',
|
|
63
|
+
corr_exhausted: 'answered',
|
|
64
|
+
late_route_cleanup_failed: 'answered',
|
|
65
|
+
reverse_request_capability_not_declared: 'answered',
|
|
66
|
+
stale_route_handle: 'answered',
|
|
67
|
+
reverse_request_unhandled: 'answered',
|
|
68
|
+
handler_error: 'answered',
|
|
69
|
+
health_error: 'answered',
|
|
70
|
+
duplicate_module_id: 'answered',
|
|
71
|
+
route_rejected: 'answered',
|
|
72
|
+
lock_busy: 'answered',
|
|
73
|
+
owner_invalid: 'answered',
|
|
74
|
+
renewal_failed: 'answered',
|
|
75
|
+
unsupported_platform: 'answered',
|
|
76
|
+
EACCES: 'answered',
|
|
77
|
+
EPERM: 'answered',
|
|
78
|
+
ERR_PRIVATE_FILES_SECURITY: 'answered',
|
|
79
|
+
});
|
|
80
|
+
/**
|
|
81
|
+
* An injected adapter may throw this ONLY when its connection/transport is
|
|
82
|
+
* unreachable, including a failed connect before getScoped. Do not wrap an
|
|
83
|
+
* adapter shutdown, cancellation, validation error or vault refusal in it.
|
|
84
|
+
* Its fixed message cannot echo enrollment or credential material, and its
|
|
85
|
+
* kind stays `unavailable` for callers handling ClaustrumConsumerError.
|
|
86
|
+
*/
|
|
87
|
+
export class ClaustrumUnreachableError extends ClaustrumConsumerError {
|
|
88
|
+
constructor() {
|
|
89
|
+
super('unavailable', 'Claustrum scoped operation unavailable');
|
|
90
|
+
this.name = 'ClaustrumUnreachableError';
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
export function classifyVaultFailure(error) {
|
|
94
|
+
if (error instanceof ClaustrumUnreachableError ||
|
|
95
|
+
error instanceof SocketClosedError ||
|
|
96
|
+
error instanceof SocketTimeoutError)
|
|
97
|
+
return 'unreachable';
|
|
98
|
+
const code = error instanceof ClaustrumCredentialError || error instanceof SubcCallError
|
|
99
|
+
? error.code
|
|
100
|
+
: error instanceof Error && 'code' in error
|
|
101
|
+
? error.code
|
|
102
|
+
: undefined;
|
|
103
|
+
if (typeof code !== 'string' || !Object.hasOwn(VAULT_FAILURE_CLASSES, code))
|
|
104
|
+
return 'answered';
|
|
105
|
+
return VAULT_FAILURE_CLASSES[code];
|
|
106
|
+
}
|
|
@@ -1,10 +1,11 @@
|
|
|
1
1
|
import type { ClaustrumReporterSource } from '@cortexkit/claustrum-client';
|
|
2
2
|
import type { QuotaObservation } from '../quota/index.js';
|
|
3
3
|
import type { RoutingRow } from '../routing/index.js';
|
|
4
|
-
import { type ClaustrumFamily, type ClaustrumScopedAttempt, type ClaustrumScopedClient, type IdentityParser, type VaultGrantReach } from './custody.js';
|
|
4
|
+
import { type ClaustrumFamily, type ClaustrumScopedAttempt, type ClaustrumScopedClient, type IdentityParser, type KeptReceiptState, type VaultGrantReach } from './custody.js';
|
|
5
5
|
import { type ClaustrumLogger } from './errors.js';
|
|
6
6
|
import { type InsulaQuotaOptions } from './insula.js';
|
|
7
7
|
import { type AccountMapper, type QuotaReceipt, type VaultRosterFile } from './roster.js';
|
|
8
|
+
import { type WatchMode } from './watch.js';
|
|
8
9
|
export interface ClaustrumConsumerOptions<Q = QuotaObservation> {
|
|
9
10
|
/**
|
|
10
11
|
* The roster file: one row per vault account (route id, credential id,
|
|
@@ -41,6 +42,12 @@ export interface ClaustrumConsumerOptions<Q = QuotaObservation> {
|
|
|
41
42
|
*/
|
|
42
43
|
onRoster?: (roster: VaultRosterFile) => void;
|
|
43
44
|
onError?: (error: unknown) => void;
|
|
45
|
+
/**
|
|
46
|
+
* How often `start()` ticks. A tick lists the vault when no vault watch is
|
|
47
|
+
* open (before it is accepted, or when the vault or the client cannot
|
|
48
|
+
* watch), and otherwise only every five minutes, as a safety net. A tick
|
|
49
|
+
* polls insula (at most once a minute) only while its watch is not open.
|
|
50
|
+
*/
|
|
44
51
|
pollIntervalMs?: number;
|
|
45
52
|
setTimeoutImpl?: typeof setTimeout;
|
|
46
53
|
clearTimeoutImpl?: typeof clearTimeout;
|
|
@@ -49,6 +56,15 @@ export interface ClaustrumConsumerOptions<Q = QuotaObservation> {
|
|
|
49
56
|
/** Optional background quota source. In-band readings still use recordQuota. */
|
|
50
57
|
insula?: InsulaQuotaOptions<Q>;
|
|
51
58
|
}
|
|
59
|
+
/**
|
|
60
|
+
* How a started consumer learns about changes, for logs and status displays.
|
|
61
|
+
* `insula` is present when the consumer was given an insula source. Never
|
|
62
|
+
* carries secrets.
|
|
63
|
+
*/
|
|
64
|
+
export interface ClaustrumWatchState {
|
|
65
|
+
readonly vault: WatchMode;
|
|
66
|
+
readonly insula?: WatchMode;
|
|
67
|
+
}
|
|
52
68
|
export interface SendOptions {
|
|
53
69
|
/**
|
|
54
70
|
* What kind of request this is (for example `model`, `quota`, `profile`),
|
|
@@ -81,9 +97,23 @@ export declare class ClaustrumConsumer<Q = QuotaObservation> {
|
|
|
81
97
|
* held the discovery lease and its newer roster was served instead).
|
|
82
98
|
*/
|
|
83
99
|
grantReach(): VaultGrantReach | undefined;
|
|
100
|
+
/** How this consumer currently learns about changes, without I/O. */
|
|
101
|
+
watchState(): ClaustrumWatchState;
|
|
102
|
+
/** Whether any account is using an in-memory outage receipt, without I/O. */
|
|
103
|
+
keptReceiptState(): KeptReceiptState;
|
|
84
104
|
/** Rows for `/routing`, from the last committed roster. */
|
|
85
105
|
routingRows(): RoutingRow[];
|
|
86
106
|
refresh(): Promise<VaultRosterFile | undefined>;
|
|
107
|
+
/**
|
|
108
|
+
* Poll in the background and open the vault and insula watches. Until the
|
|
109
|
+
* vault watch is accepted, and whenever it is unavailable, every tick lists
|
|
110
|
+
* the vault exactly as before watches existed. While it is open a tick
|
|
111
|
+
* lists only when five minutes have passed since the last discovery, since
|
|
112
|
+
* the watch keeps no history; it still checks `isCustodyActive`, so a switch
|
|
113
|
+
* to local mode closes the connection as quickly as before. Insula is
|
|
114
|
+
* polled on the tick only while its own watch is not open. A host not in
|
|
115
|
+
* vault mode makes no request.
|
|
116
|
+
*/
|
|
87
117
|
start(): void;
|
|
88
118
|
/**
|
|
89
119
|
* Fetch on a background tick, at most once per minute across projects with
|
|
@@ -5,6 +5,7 @@ import { readClaustrumEnrollmentToken } from './enrollment.js';
|
|
|
5
5
|
import { ClaustrumConsumerError } from './errors.js';
|
|
6
6
|
import { acquireInsulaQuotaSource } from './insula.js';
|
|
7
7
|
import { acceptVaultRoute, declineVaultRoute, readVaultRoster, recordVaultAccountQuota, recordVaultQuota, refreshVaultRoster, vaultRoutingRows, } from './roster.js';
|
|
8
|
+
import { SAFETY_POLL_MS, ScopedRosterWatch } from './watch.js';
|
|
8
9
|
/**
|
|
9
10
|
* One plugin host's view of its vault accounts. It turns vault credentials
|
|
10
11
|
* into rows for `/routing`, authorizes each physical send with the vault, and
|
|
@@ -18,6 +19,8 @@ export class ClaustrumConsumer {
|
|
|
18
19
|
#shutdown = new AbortController();
|
|
19
20
|
#logger;
|
|
20
21
|
#custody;
|
|
22
|
+
/** The custody's client, kept so `start()` can open its vault watch. */
|
|
23
|
+
#client;
|
|
21
24
|
#connecting;
|
|
22
25
|
#refreshing;
|
|
23
26
|
#roster;
|
|
@@ -29,6 +32,10 @@ export class ClaustrumConsumer {
|
|
|
29
32
|
#timer;
|
|
30
33
|
#started = false;
|
|
31
34
|
#insula;
|
|
35
|
+
#vaultWatch;
|
|
36
|
+
#releaseInsulaWatch;
|
|
37
|
+
/** When this instance last completed a discovery, by `now`. */
|
|
38
|
+
#discoveredAt;
|
|
32
39
|
constructor(options) {
|
|
33
40
|
this.#options = options;
|
|
34
41
|
this.#logger = options.logger ?? createLogger('claustrum');
|
|
@@ -83,6 +90,7 @@ export class ClaustrumConsumer {
|
|
|
83
90
|
client.close();
|
|
84
91
|
this.#assertOpen();
|
|
85
92
|
}
|
|
93
|
+
this.#client = client;
|
|
86
94
|
this.#custody = new ClaustrumScopedCustody({
|
|
87
95
|
client,
|
|
88
96
|
family: this.#options.family,
|
|
@@ -91,6 +99,8 @@ export class ClaustrumConsumer {
|
|
|
91
99
|
requireAssertion: this.#options.requireAssertion,
|
|
92
100
|
now: this.#options.now,
|
|
93
101
|
logger: this.#logger,
|
|
102
|
+
setTimeoutImpl: this.#options.setTimeoutImpl,
|
|
103
|
+
clearTimeoutImpl: this.#options.clearTimeoutImpl,
|
|
94
104
|
});
|
|
95
105
|
if (this.#options.insula && client.insula) {
|
|
96
106
|
this.#insula = acquireInsulaQuotaSource(client.insula, this.#options.tokenPath);
|
|
@@ -122,6 +132,28 @@ export class ClaustrumConsumer {
|
|
|
122
132
|
? latest.reach
|
|
123
133
|
: undefined;
|
|
124
134
|
}
|
|
135
|
+
/** How this consumer currently learns about changes, without I/O. */
|
|
136
|
+
watchState() {
|
|
137
|
+
return Object.freeze({
|
|
138
|
+
vault: this.#vaultWatch?.mode ?? 'polling',
|
|
139
|
+
...(this.#options.insula && {
|
|
140
|
+
insula: this.#insula?.source.watchMode() ?? 'polling',
|
|
141
|
+
}),
|
|
142
|
+
});
|
|
143
|
+
}
|
|
144
|
+
/** Close the watches with the connection they belong to. */
|
|
145
|
+
#stopWatch() {
|
|
146
|
+
this.#vaultWatch?.stop();
|
|
147
|
+
this.#vaultWatch = undefined;
|
|
148
|
+
this.#client = undefined;
|
|
149
|
+
this.#releaseInsulaWatch?.();
|
|
150
|
+
this.#releaseInsulaWatch = undefined;
|
|
151
|
+
}
|
|
152
|
+
/** Whether any account is using an in-memory outage receipt, without I/O. */
|
|
153
|
+
keptReceiptState() {
|
|
154
|
+
return (this.#custody?.keptReceiptState() ??
|
|
155
|
+
Object.freeze({ active: false, since: null }));
|
|
156
|
+
}
|
|
125
157
|
/** Rows for `/routing`, from the last committed roster. */
|
|
126
158
|
routingRows() {
|
|
127
159
|
return vaultRoutingRows(this.#roster);
|
|
@@ -134,6 +166,7 @@ export class ClaustrumConsumer {
|
|
|
134
166
|
if (!(await this.#active())) {
|
|
135
167
|
this.#roster = undefined;
|
|
136
168
|
this.#grantReach = undefined;
|
|
169
|
+
this.#stopWatch();
|
|
137
170
|
this.#custody?.close();
|
|
138
171
|
this.#custody = undefined;
|
|
139
172
|
this.#insula?.release();
|
|
@@ -164,6 +197,7 @@ export class ClaustrumConsumer {
|
|
|
164
197
|
this.#assertOpen();
|
|
165
198
|
const changed = roster?.view !== this.#roster?.view;
|
|
166
199
|
this.#roster = roster;
|
|
200
|
+
custody.retain(roster?.rows ?? []);
|
|
167
201
|
// Each discovery replaces the previous value, including with unknown. A
|
|
168
202
|
// refresh that served a peer's roster discovered nothing and leaves it;
|
|
169
203
|
// grantReach() hides it once the roster's view no longer matches.
|
|
@@ -175,12 +209,23 @@ export class ClaustrumConsumer {
|
|
|
175
209
|
// notification, and the poll runs every few seconds.
|
|
176
210
|
if (roster && changed)
|
|
177
211
|
this.#options.onRoster?.(roster);
|
|
212
|
+
this.#discoveredAt = (this.#options.now ?? Date.now)();
|
|
178
213
|
return roster;
|
|
179
214
|
})().finally(() => {
|
|
180
215
|
this.#refreshing = undefined;
|
|
181
216
|
});
|
|
182
217
|
return this.#refreshing;
|
|
183
218
|
}
|
|
219
|
+
/**
|
|
220
|
+
* Poll in the background and open the vault and insula watches. Until the
|
|
221
|
+
* vault watch is accepted, and whenever it is unavailable, every tick lists
|
|
222
|
+
* the vault exactly as before watches existed. While it is open a tick
|
|
223
|
+
* lists only when five minutes have passed since the last discovery, since
|
|
224
|
+
* the watch keeps no history; it still checks `isCustodyActive`, so a switch
|
|
225
|
+
* to local mode closes the connection as quickly as before. Insula is
|
|
226
|
+
* polled on the tick only while its own watch is not open. A host not in
|
|
227
|
+
* vault mode makes no request.
|
|
228
|
+
*/
|
|
184
229
|
start() {
|
|
185
230
|
if (this.#started)
|
|
186
231
|
return;
|
|
@@ -188,8 +233,10 @@ export class ClaustrumConsumer {
|
|
|
188
233
|
this.#started = true;
|
|
189
234
|
const tick = async () => {
|
|
190
235
|
try {
|
|
191
|
-
await this
|
|
236
|
+
if (await this.#listDue())
|
|
237
|
+
await this.refresh();
|
|
192
238
|
await this.refreshInsulaQuota();
|
|
239
|
+
this.#openWatch();
|
|
193
240
|
}
|
|
194
241
|
catch (error) {
|
|
195
242
|
if (!this.#shutdown.signal.aborted)
|
|
@@ -208,6 +255,65 @@ export class ClaustrumConsumer {
|
|
|
208
255
|
};
|
|
209
256
|
void tick();
|
|
210
257
|
}
|
|
258
|
+
/** Whether a background tick must list the vault now. */
|
|
259
|
+
async #listDue() {
|
|
260
|
+
if (this.#vaultWatch?.mode !== 'watching')
|
|
261
|
+
return true;
|
|
262
|
+
const now = (this.#options.now ?? Date.now)();
|
|
263
|
+
if (this.#discoveredAt === undefined ||
|
|
264
|
+
now - this.#discoveredAt >= SAFETY_POLL_MS)
|
|
265
|
+
return true;
|
|
266
|
+
// refresh() is what closes the connection when the host left vault mode.
|
|
267
|
+
return !(await this.#active());
|
|
268
|
+
}
|
|
269
|
+
/**
|
|
270
|
+
* Open the vault and insula watches once a vault connection exists. Only
|
|
271
|
+
* reached in vault mode: a host in local mode never connects.
|
|
272
|
+
*/
|
|
273
|
+
#openWatch() {
|
|
274
|
+
const client = this.#client;
|
|
275
|
+
if (this.#shutdown.signal.aborted || !client || !this.#custody)
|
|
276
|
+
return;
|
|
277
|
+
if (!this.#vaultWatch) {
|
|
278
|
+
const watch = new ScopedRosterWatch({
|
|
279
|
+
client,
|
|
280
|
+
enrollmentToken: async () => (await readClaustrumEnrollmentToken(this.#options.tokenPath)).token,
|
|
281
|
+
view: () => this.#roster?.view,
|
|
282
|
+
// The existing discovery, so a watched change commits the roster and
|
|
283
|
+
// re-applies it to kept receipts exactly as a poll does. A refresh
|
|
284
|
+
// already in flight may have listed before the change was announced,
|
|
285
|
+
// so wait for it and list again.
|
|
286
|
+
discover: async () => {
|
|
287
|
+
while (this.#refreshing)
|
|
288
|
+
await this.#refreshing.catch(() => { });
|
|
289
|
+
await this.refresh();
|
|
290
|
+
},
|
|
291
|
+
onRefused: (error) => {
|
|
292
|
+
// As a poll that met the same refusal from list_scoped would.
|
|
293
|
+
this.#custody?.listFailed(error);
|
|
294
|
+
this.#options.onError?.(error);
|
|
295
|
+
},
|
|
296
|
+
onTransportLost: () => this.#custody?.transportLost(),
|
|
297
|
+
onReachable: () => this.#custody?.reachable(),
|
|
298
|
+
onError: (error) => {
|
|
299
|
+
if (!this.#shutdown.signal.aborted)
|
|
300
|
+
this.#options.onError?.(error);
|
|
301
|
+
},
|
|
302
|
+
logger: this.#logger,
|
|
303
|
+
now: this.#options.now,
|
|
304
|
+
setTimeoutImpl: this.#options.setTimeoutImpl,
|
|
305
|
+
clearTimeoutImpl: this.#options.clearTimeoutImpl,
|
|
306
|
+
});
|
|
307
|
+
this.#vaultWatch = watch;
|
|
308
|
+
watch.start();
|
|
309
|
+
}
|
|
310
|
+
if (this.#options.insula && this.#insula && !this.#releaseInsulaWatch)
|
|
311
|
+
this.#releaseInsulaWatch = this.#insula.source.watch({
|
|
312
|
+
provider: this.#options.insula.provider,
|
|
313
|
+
setTimeoutImpl: this.#options.setTimeoutImpl,
|
|
314
|
+
clearTimeoutImpl: this.#options.clearTimeoutImpl,
|
|
315
|
+
});
|
|
316
|
+
}
|
|
211
317
|
/**
|
|
212
318
|
* Fetch on a background tick, at most once per minute across projects with
|
|
213
319
|
* the same daemon and enrollment token path. Admission must use the cache
|
|
@@ -282,20 +388,33 @@ export class ClaustrumConsumer {
|
|
|
282
388
|
async authorize(routeId, signal) {
|
|
283
389
|
this.#assertOpen(signal);
|
|
284
390
|
const roster = this.#roster ?? (await this.#wait(this.refresh(), signal));
|
|
285
|
-
if (!roster || !(await this.#active()))
|
|
391
|
+
if (!roster || !(await this.#active())) {
|
|
392
|
+
this.#custody?.close();
|
|
393
|
+
this.#custody = undefined;
|
|
394
|
+
this.#stopWatch();
|
|
395
|
+
this.#insula?.release();
|
|
396
|
+
this.#insula = undefined;
|
|
286
397
|
throw new ClaustrumConsumerError('not-active', 'Claustrum scoped custody is not active');
|
|
398
|
+
}
|
|
287
399
|
const current = await readVaultRoster(this.#options.rosterPath);
|
|
288
400
|
this.#assertOpen(signal);
|
|
289
401
|
const observed = roster.rows.find((row) => row.routeId === routeId);
|
|
290
402
|
const configured = current?.rows.find((row) => row.routeId === routeId);
|
|
291
|
-
if (configured && !configured.enabled)
|
|
403
|
+
if (configured && !configured.enabled) {
|
|
404
|
+
if (observed)
|
|
405
|
+
this.#custody?.forget(observed.credentialId);
|
|
292
406
|
throw new ClaustrumConsumerError('route-declined', 'Claustrum route is disabled');
|
|
407
|
+
}
|
|
293
408
|
if (!observed ||
|
|
294
409
|
!configured ||
|
|
295
410
|
configured.state !== 'active' ||
|
|
296
411
|
configured.credentialId !== observed.credentialId ||
|
|
297
|
-
configured.accountIdentity !== observed.accountIdentity
|
|
412
|
+
configured.accountIdentity !== observed.accountIdentity ||
|
|
413
|
+
configured.credentialType !== observed.credentialType) {
|
|
414
|
+
if (observed)
|
|
415
|
+
this.#custody?.forget(observed.credentialId);
|
|
298
416
|
throw new ClaustrumConsumerError('route-unavailable', 'Claustrum route is disabled, removed or changed');
|
|
417
|
+
}
|
|
299
418
|
const custody = await this.#wait(this.#getCustody(), signal);
|
|
300
419
|
const combined = combineAbortSignals([
|
|
301
420
|
this.#shutdown.signal,
|
|
@@ -308,7 +427,7 @@ export class ClaustrumConsumer {
|
|
|
308
427
|
...(configured.accountIdentity !== undefined && {
|
|
309
428
|
accountIdentity: configured.accountIdentity,
|
|
310
429
|
}),
|
|
311
|
-
}, combined.signal);
|
|
430
|
+
}, combined.signal, routeId);
|
|
312
431
|
}
|
|
313
432
|
finally {
|
|
314
433
|
combined.dispose();
|
|
@@ -332,6 +451,10 @@ export class ClaustrumConsumer {
|
|
|
332
451
|
const signal = options.signal;
|
|
333
452
|
let served = await this.authorize(routeId, signal);
|
|
334
453
|
let response = await dispatch(served, signal);
|
|
454
|
+
if (response.status === 401 && served.fromKeptReceipt) {
|
|
455
|
+
await this.reportFailure(served, 401, options.reporterSource ?? 'direct');
|
|
456
|
+
return response;
|
|
457
|
+
}
|
|
335
458
|
if (response.status === 401 && !signal?.aborted) {
|
|
336
459
|
let current;
|
|
337
460
|
try {
|
|
@@ -366,6 +489,7 @@ export class ClaustrumConsumer {
|
|
|
366
489
|
this.#assertOpen();
|
|
367
490
|
await declineVaultRoute(this.#options.rosterPath, routeId);
|
|
368
491
|
this.#roster = await readVaultRoster(this.#options.rosterPath);
|
|
492
|
+
this.#custody?.retain(this.#roster?.rows ?? []);
|
|
369
493
|
}
|
|
370
494
|
async accept(routeId) {
|
|
371
495
|
this.#assertOpen();
|
|
@@ -421,6 +545,7 @@ export class ClaustrumConsumer {
|
|
|
421
545
|
if (this.#timer)
|
|
422
546
|
(this.#options.clearTimeoutImpl ?? clearTimeout)(this.#timer);
|
|
423
547
|
this.#timer = undefined;
|
|
548
|
+
this.#stopWatch();
|
|
424
549
|
this.#custody?.close();
|
|
425
550
|
this.#insula?.release();
|
|
426
551
|
this.#insula = undefined;
|
|
@@ -1,9 +1,14 @@
|
|
|
1
1
|
import { type ClaustrumClient, type ClaustrumReporterSource, type EnrollmentTokenFile } from '@cortexkit/claustrum-client';
|
|
2
2
|
import { type ClaustrumLogger } from './errors.js';
|
|
3
3
|
import type { InsulaUsageTransport } from './insula.js';
|
|
4
|
+
import type { ScopedWatchSource } from './watch.js';
|
|
5
|
+
/**
|
|
6
|
+
* `watchScoped` is present from claustrum-client 0.12.0. Hosts detect it at
|
|
7
|
+
* run time and keep polling without it.
|
|
8
|
+
*/
|
|
4
9
|
export type ClaustrumScopedClient = Pick<ClaustrumClient, 'listScoped' | 'getScoped' | 'reportAuthFailureScoped' | 'close'> & {
|
|
5
10
|
insula?: InsulaUsageTransport;
|
|
6
|
-
};
|
|
11
|
+
} & ScopedWatchSource;
|
|
7
12
|
/** The two credential types a plugin's family can hold; routing differs by type. */
|
|
8
13
|
export type VaultCredentialType = 'oauth' | 'api_key';
|
|
9
14
|
/**
|
|
@@ -132,6 +137,17 @@ export interface ClaustrumScopedAttempt {
|
|
|
132
137
|
readonly accessToken: string;
|
|
133
138
|
readonly recordVersion: number;
|
|
134
139
|
readonly expiresAtMs: number | null;
|
|
140
|
+
/**
|
|
141
|
+
* True when this receipt was not freshly served but is the last token kept
|
|
142
|
+
* from an earlier read, used because the vault could not be reached. A 401
|
|
143
|
+
* with such a receipt must not be retried and is not reported to the vault,
|
|
144
|
+
* which is unreachable.
|
|
145
|
+
*/
|
|
146
|
+
readonly fromKeptReceipt?: true;
|
|
147
|
+
}
|
|
148
|
+
export interface KeptReceiptState {
|
|
149
|
+
readonly active: boolean;
|
|
150
|
+
readonly since: number | null;
|
|
135
151
|
}
|
|
136
152
|
/** Reads the provider identity a served token executes under, when the plugin can tell. */
|
|
137
153
|
export type IdentityParser = (accessToken: string) => string | undefined;
|
|
@@ -151,13 +167,15 @@ export declare function decideScopedRetryAfter401(site: string, served: Claustru
|
|
|
151
167
|
* so it cannot expire while a long request is still using it.
|
|
152
168
|
*/
|
|
153
169
|
export declare const SERVING_MARGIN_MS = 300000;
|
|
170
|
+
/** A kept receipt needs a minute of headroom, not the vault's refresh demand. */
|
|
171
|
+
export declare const KEPT_RECEIPT_MARGIN_MS = 60000;
|
|
154
172
|
/**
|
|
155
173
|
* Reads this consumer's vault credentials (list, fetch, 401 report), with the
|
|
156
|
-
* enrollment token as authorization. Used by every host of a plugin.
|
|
157
|
-
*
|
|
158
|
-
*
|
|
159
|
-
*
|
|
160
|
-
*
|
|
174
|
+
* enrollment token as authorization. Used by every host of a plugin. Every
|
|
175
|
+
* physical send asks the vault first while reachable. Only an unreachable vault permits
|
|
176
|
+
* reuse of the last validated receipt, in memory and bounded by its expiry.
|
|
177
|
+
* The enrollment token is re-read per operation so revocation and disconnect
|
|
178
|
+
* still take effect without a process restart.
|
|
161
179
|
*/
|
|
162
180
|
export declare class ClaustrumScopedCustody {
|
|
163
181
|
#private;
|
|
@@ -177,7 +195,13 @@ export declare class ClaustrumScopedCustody {
|
|
|
177
195
|
requireAssertion?: boolean;
|
|
178
196
|
now?: () => number;
|
|
179
197
|
logger?: ClaustrumLogger;
|
|
198
|
+
setTimeoutImpl?: typeof setTimeout;
|
|
199
|
+
clearTimeoutImpl?: typeof clearTimeout;
|
|
180
200
|
});
|
|
201
|
+
/** A watch losing its transport is the same outage as an unreachable read. */
|
|
202
|
+
transportLost(error?: unknown): void;
|
|
203
|
+
/** Any vault answer ends transport fallback, even when it refuses access. */
|
|
204
|
+
reachable(): void;
|
|
181
205
|
/**
|
|
182
206
|
* List this consumer's credentials. A record that cannot be used is skipped
|
|
183
207
|
* and warned about rather than failing the whole list, so one bad record
|
|
@@ -186,15 +210,23 @@ export declare class ClaustrumScopedCustody {
|
|
|
186
210
|
*/
|
|
187
211
|
discover(signal?: AbortSignal): Promise<VaultInventory>;
|
|
188
212
|
/**
|
|
189
|
-
*
|
|
190
|
-
*
|
|
191
|
-
*
|
|
192
|
-
*
|
|
193
|
-
* refuse; the receipt records what the vault asserted separately from what
|
|
194
|
-
* the roster expected. With it, a reply that does not itself name the
|
|
195
|
-
* credential id and the expected account is refused.
|
|
213
|
+
* Apply a failed account listing: any answer from the vault (a refusal such
|
|
214
|
+
* as a revoked enrollment's `not_found`) drops every kept receipt, while an
|
|
215
|
+
* unreachable vault keeps them. A vault watch that ends with the same
|
|
216
|
+
* refusal calls this too, so both paths treat it alike.
|
|
196
217
|
*/
|
|
197
|
-
|
|
218
|
+
listFailed(error: unknown): void;
|
|
219
|
+
/** Discard bearer material when a route is removed, declined or rebound. */
|
|
220
|
+
forget(credentialId: string): void;
|
|
221
|
+
/** Apply an already-held roster; this never fetches credentials or writes it. */
|
|
222
|
+
retain(identities: readonly (ClaustrumScopedIdentity & {
|
|
223
|
+
enabled: boolean;
|
|
224
|
+
state: string;
|
|
225
|
+
})[]): void;
|
|
226
|
+
/** A frozen, non-secret summary for a plugin's status display. */
|
|
227
|
+
keptReceiptState(): KeptReceiptState;
|
|
228
|
+
/** Ask the vault while reachable; retain one validated receipt in memory only. */
|
|
229
|
+
authorize(identity: ClaustrumScopedIdentity, signal?: AbortSignal, routeId?: string): Promise<ClaustrumScopedAttempt>;
|
|
198
230
|
/**
|
|
199
231
|
* Report that a send this consumer actually made was rejected. Only a 401
|
|
200
232
|
* is reported (the vault refuses 429, 402 and 5xx reports), addressed by
|