@modelprofile.com/authswitch 6.2.0 → 6.4.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_ts/00_commitinfo_data.js +1 -1
- package/dist_ts/authority-contract.d.ts +142 -0
- package/dist_ts/authority-contract.js +3 -0
- package/dist_ts/authority-runtime-contract.d.ts +32 -0
- package/dist_ts/authority-runtime-contract.js +2 -0
- package/dist_ts/classes.authoritybroker.d.ts +73 -0
- package/dist_ts/classes.authoritybroker.js +548 -0
- package/dist_ts/classes.authorityclient.d.ts +34 -0
- package/dist_ts/classes.authorityclient.js +200 -0
- package/dist_ts/classes.authoritydaemon.d.ts +26 -0
- package/dist_ts/classes.authoritydaemon.js +249 -0
- package/dist_ts/classes.authoritydatabase.d.ts +94 -0
- package/dist_ts/classes.authoritydatabase.js +736 -0
- package/dist_ts/classes.authorityframing.d.ts +8 -0
- package/dist_ts/classes.authorityframing.js +22 -0
- package/dist_ts/classes.authoritymodels.d.ts +215 -0
- package/dist_ts/classes.authoritymodels.js +818 -0
- package/dist_ts/classes.authoritysecrets.d.ts +9 -0
- package/dist_ts/classes.authoritysecrets.js +30 -0
- package/dist_ts/classes.authorityservice.d.ts +28 -0
- package/dist_ts/classes.authorityservice.js +71 -0
- package/dist_ts/classes.cli.d.ts +56 -0
- package/dist_ts/classes.cli.js +238 -63
- package/dist_ts/classes.codexpreuse.js +2 -2
- package/dist_ts/classes.tui.js +51 -2
- package/dist_ts/index.d.ts +2 -0
- package/dist_ts/index.js +26 -1
- package/dist_ts/plugins.d.ts +9 -2
- package/dist_ts/plugins.js +10 -3
- package/dist_ts/preuse.d.ts +89 -2
- package/dist_ts/preuse.js +107 -2
- package/package.json +17 -3
- package/readme.md +118 -16
- package/ts/00_commitinfo_data.ts +1 -1
- package/ts/authority-contract.ts +109 -0
- package/ts/authority-runtime-contract.ts +27 -0
- package/ts/classes.authoritybroker.ts +530 -0
- package/ts/classes.authorityclient.ts +183 -0
- package/ts/classes.authoritydaemon.ts +219 -0
- package/ts/classes.authoritydatabase.ts +725 -0
- package/ts/classes.authorityframing.ts +21 -0
- package/ts/classes.authoritymodels.ts +367 -0
- package/ts/classes.authoritysecrets.ts +27 -0
- package/ts/classes.authorityservice.ts +83 -0
- package/ts/classes.cli.ts +236 -54
- package/ts/classes.codexpreuse.ts +1 -1
- package/ts/classes.tui.ts +39 -2
- package/ts/index.ts +25 -0
- package/ts/plugins.ts +9 -2
- package/ts/preuse.ts +141 -3
|
@@ -0,0 +1,183 @@
|
|
|
1
|
+
import type { ITypedRequest } from '@api.global/typedrequest-interfaces';
|
|
2
|
+
import * as plugins from './plugins.js';
|
|
3
|
+
import type {
|
|
4
|
+
IAuthSwitchAccountEvent, IAuthSwitchSnapshot, IReq_AuthSwitchBeginAdd,
|
|
5
|
+
IReq_AuthSwitchBeginReauth, IReq_AuthSwitchCancelOperation, IReq_AuthSwitchEvents,
|
|
6
|
+
IReq_AuthSwitchGetOperation, IReq_AuthSwitchRemoveAccount, IReq_AuthSwitchRenameAccount,
|
|
7
|
+
IReq_AuthSwitchSnapshot,
|
|
8
|
+
} from './authority-contract.js';
|
|
9
|
+
import type { IReq_AuthSwitchBindAccount, IReq_AuthSwitchResolveAccess } from './authority-runtime-contract.js';
|
|
10
|
+
import { AuthSwitchAuthorityFrameReader, authSwitchAuthorityFrameBytes,
|
|
11
|
+
maxAuthSwitchAuthorityFrameBytes } from './classes.authorityframing.js';
|
|
12
|
+
|
|
13
|
+
const post = (path: string, payload: ITypedRequest, signal?: AbortSignal): Promise<ITypedRequest> => {
|
|
14
|
+
return new Promise((resolve, reject) => {
|
|
15
|
+
if (signal?.aborted) { reject(signal.reason); return; }
|
|
16
|
+
const socket = plugins.net.createConnection(path);
|
|
17
|
+
let settled = false;
|
|
18
|
+
const frame = new AuthSwitchAuthorityFrameReader();
|
|
19
|
+
const finish = (error?: unknown, response?: ITypedRequest): void => {
|
|
20
|
+
if (settled) return;
|
|
21
|
+
settled = true;
|
|
22
|
+
signal?.removeEventListener('abort', abort);
|
|
23
|
+
socket.destroy();
|
|
24
|
+
if (error) reject(error);
|
|
25
|
+
else if (response) resolve(response);
|
|
26
|
+
else reject(new Error('Authswitch daemon returned no response.'));
|
|
27
|
+
};
|
|
28
|
+
const abort = () => finish(signal?.reason ?? new Error('Account request was cancelled.'));
|
|
29
|
+
signal?.addEventListener('abort', abort, { once: true });
|
|
30
|
+
socket.setTimeout(35_000, () => finish(new Error('Authswitch daemon request timed out.')));
|
|
31
|
+
socket.on('connect', () => {
|
|
32
|
+
const raw = JSON.stringify(payload);
|
|
33
|
+
if (authSwitchAuthorityFrameBytes(raw) > maxAuthSwitchAuthorityFrameBytes) { finish(new Error('Account request is too large.')); return; }
|
|
34
|
+
socket.write(raw + '\n');
|
|
35
|
+
});
|
|
36
|
+
socket.on('data', chunk => {
|
|
37
|
+
if (!Buffer.isBuffer(chunk)) { finish(new Error('Account response must be a byte frame.')); return; }
|
|
38
|
+
let input: string | null;
|
|
39
|
+
try { input = frame.add(chunk); }
|
|
40
|
+
catch (error) { finish(error); return; }
|
|
41
|
+
if (input === null) return;
|
|
42
|
+
try { finish(undefined, JSON.parse(input) as ITypedRequest); }
|
|
43
|
+
catch { finish(new Error('Account response could not be decoded.')); }
|
|
44
|
+
});
|
|
45
|
+
socket.on('error', () => finish(new Error('Authswitch daemon is unavailable.')));
|
|
46
|
+
socket.on('close', () => finish(new Error('Authswitch daemon connection closed before its response.')));
|
|
47
|
+
});
|
|
48
|
+
};
|
|
49
|
+
|
|
50
|
+
/** Node-only client for the per-user daemon. Each request has its own bounded Unix connection. */
|
|
51
|
+
export class AuthSwitchClient {
|
|
52
|
+
private readonly target: plugins.typedrequest.TypedTarget;
|
|
53
|
+
private readonly runtimeTarget: plugins.typedrequest.TypedTarget;
|
|
54
|
+
|
|
55
|
+
constructor(public readonly socketPath: string, public readonly runtimeSocketPath: string) {
|
|
56
|
+
this.target = new plugins.typedrequest.TypedTarget({
|
|
57
|
+
supportsAbortSignal: true,
|
|
58
|
+
postMethod: (payload, options) => post(this.socketPath, payload, options?.signal),
|
|
59
|
+
});
|
|
60
|
+
this.runtimeTarget = new plugins.typedrequest.TypedTarget({
|
|
61
|
+
supportsAbortSignal: true,
|
|
62
|
+
postMethod: (payload, options) => post(this.runtimeSocketPath, payload, options?.signal),
|
|
63
|
+
});
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
private request<T extends ITypedRequest>(method: T['method'], request: T['request'], timeoutMs = 35_000,
|
|
67
|
+
runtime = false, signal?: AbortSignal): Promise<T['response']> {
|
|
68
|
+
return new plugins.typedrequest.TypedRequest<T>(runtime ? this.runtimeTarget : this.target, method)
|
|
69
|
+
.fire(request, { timeoutMs, maxRetries: 0, abortSignal: signal });
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
public async snapshot(options: IReq_AuthSwitchSnapshot['request'] = {}, signal?: AbortSignal): Promise<IAuthSwitchSnapshot> {
|
|
73
|
+
return (await this.request<IReq_AuthSwitchSnapshot>('authswitch.authority.snapshot', options, 35_000, false, signal)).snapshot;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/** Assemble a consistent view from bounded database pages; restart if a writer changes the revision. */
|
|
77
|
+
public async snapshotAll(options: { limit?: number; signal?: AbortSignal } = {}): Promise<IAuthSwitchSnapshot> {
|
|
78
|
+
while (true) {
|
|
79
|
+
if (options.signal?.aborted) throw options.signal.reason ?? new Error('Account snapshot cancelled.');
|
|
80
|
+
let accountAfter: string | undefined;
|
|
81
|
+
let bindingAfter: string | undefined;
|
|
82
|
+
let aggregate: IAuthSwitchSnapshot | undefined;
|
|
83
|
+
let changed = false;
|
|
84
|
+
while (true) {
|
|
85
|
+
const page = await this.snapshot({ accountAfter, bindingAfter, limit: options.limit }, options.signal);
|
|
86
|
+
if (!aggregate) aggregate = { ...page, accounts: [...page.accounts], bindings: [...page.bindings] };
|
|
87
|
+
else if (aggregate.epoch !== page.epoch || aggregate.revision !== page.revision) {
|
|
88
|
+
changed = true;
|
|
89
|
+
break;
|
|
90
|
+
} else {
|
|
91
|
+
aggregate.accounts.push(...page.accounts);
|
|
92
|
+
aggregate.bindings.push(...page.bindings);
|
|
93
|
+
}
|
|
94
|
+
accountAfter = page.nextAccountCursor ?? accountAfter ?? page.accounts.at(-1)?.id;
|
|
95
|
+
bindingAfter = page.nextBindingCursor ?? bindingAfter ?? page.bindings.at(-1)?.id;
|
|
96
|
+
if (!page.nextAccountCursor && !page.nextBindingCursor) {
|
|
97
|
+
return { ...aggregate, nextAccountCursor: null, nextBindingCursor: null };
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
if (!changed) throw new Error('Authority snapshot could not complete.');
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
public events(epoch: string, afterRevision: number, waitMs = 30_000, signal?: AbortSignal): Promise<IReq_AuthSwitchEvents['response']> {
|
|
105
|
+
return this.request<IReq_AuthSwitchEvents>('authswitch.authority.events', { epoch, afterRevision, waitMs }, waitMs + 5_000, false, signal);
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/** Always obtains a fresh snapshot after reconnect or an event-log gap. */
|
|
109
|
+
public async subscribe(onSnapshot: (snapshot: IAuthSwitchSnapshot) => void | Promise<void>,
|
|
110
|
+
onEvent: (event: IAuthSwitchAccountEvent) => void | Promise<void>, signal: AbortSignal): Promise<void> {
|
|
111
|
+
const retry = () => new Promise<void>(resolve => {
|
|
112
|
+
const timer = setTimeout(() => { signal.removeEventListener('abort', aborted); resolve(); }, 250);
|
|
113
|
+
const aborted = () => { clearTimeout(timer); resolve(); };
|
|
114
|
+
signal.addEventListener('abort', aborted, { once: true });
|
|
115
|
+
});
|
|
116
|
+
let snapshot: IAuthSwitchSnapshot | undefined;
|
|
117
|
+
while (!signal.aborted) {
|
|
118
|
+
if (!snapshot) {
|
|
119
|
+
try { snapshot = await this.snapshotAll({ signal }); }
|
|
120
|
+
catch {
|
|
121
|
+
if (signal.aborted) break;
|
|
122
|
+
await retry();
|
|
123
|
+
continue;
|
|
124
|
+
}
|
|
125
|
+
await onSnapshot(snapshot);
|
|
126
|
+
}
|
|
127
|
+
let result: IReq_AuthSwitchEvents['response'];
|
|
128
|
+
try { result = await this.events(snapshot.epoch, snapshot.revision, 30_000, signal); }
|
|
129
|
+
catch {
|
|
130
|
+
if (signal.aborted) break;
|
|
131
|
+
snapshot = undefined;
|
|
132
|
+
await retry();
|
|
133
|
+
continue;
|
|
134
|
+
}
|
|
135
|
+
if (result.resyncRequired || result.epoch !== snapshot.epoch) {
|
|
136
|
+
snapshot = undefined;
|
|
137
|
+
continue;
|
|
138
|
+
}
|
|
139
|
+
for (const event of result.events) await onEvent(event);
|
|
140
|
+
snapshot = { ...snapshot, revision: result.revision };
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
public async beginAddOpenAi(): Promise<IReq_AuthSwitchBeginAdd['response']['operation']> {
|
|
145
|
+
return (await this.request<IReq_AuthSwitchBeginAdd>('authswitch.authority.add', { providerId: 'openai', flow: 'device' })).operation;
|
|
146
|
+
}
|
|
147
|
+
public async beginReauthOpenAi(accountId: string): Promise<IReq_AuthSwitchBeginReauth['response']['operation']> {
|
|
148
|
+
return (await this.request<IReq_AuthSwitchBeginReauth>('authswitch.authority.reauth', { accountId, flow: 'device' })).operation;
|
|
149
|
+
}
|
|
150
|
+
public async getOperation(operationId: string): Promise<IReq_AuthSwitchGetOperation['response']['operation']> {
|
|
151
|
+
return (await this.request<IReq_AuthSwitchGetOperation>('authswitch.authority.operation', { operationId })).operation;
|
|
152
|
+
}
|
|
153
|
+
public async cancelOperation(operationId: string): Promise<IReq_AuthSwitchCancelOperation['response']['operation']> {
|
|
154
|
+
return (await this.request<IReq_AuthSwitchCancelOperation>('authswitch.authority.cancel', { operationId })).operation;
|
|
155
|
+
}
|
|
156
|
+
public async renameAccount(accountId: string, expectedRevision: number, label: string): Promise<IReq_AuthSwitchRenameAccount['response']['account']> {
|
|
157
|
+
return (await this.request<IReq_AuthSwitchRenameAccount>('authswitch.authority.rename', { accountId, expectedRevision, label })).account;
|
|
158
|
+
}
|
|
159
|
+
public async removeAccount(accountId: string, expectedRevision: number): Promise<IReq_AuthSwitchRemoveAccount['response']['account']> {
|
|
160
|
+
return (await this.request<IReq_AuthSwitchRemoveAccount>('authswitch.authority.remove', { accountId, expectedRevision })).account;
|
|
161
|
+
}
|
|
162
|
+
public bindAccount(input: IReq_AuthSwitchBindAccount['request']): Promise<IReq_AuthSwitchBindAccount['response']> {
|
|
163
|
+
return this.request<IReq_AuthSwitchBindAccount>('authswitch.authority.bind', input);
|
|
164
|
+
}
|
|
165
|
+
public resolveAccess(input: IReq_AuthSwitchResolveAccess['request']): Promise<IReq_AuthSwitchResolveAccess['response']> {
|
|
166
|
+
return this.request<IReq_AuthSwitchResolveAccess>('authswitch.authority.resolveAccess', input, 35_000, true);
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
/** Container-facing client. It can only resolve a previously issued binding capability. */
|
|
171
|
+
export class AuthSwitchRuntimeClient {
|
|
172
|
+
private readonly target: plugins.typedrequest.TypedTarget;
|
|
173
|
+
constructor(runtimeSocketPath: string) {
|
|
174
|
+
this.target = new plugins.typedrequest.TypedTarget({
|
|
175
|
+
supportsAbortSignal: true,
|
|
176
|
+
postMethod: (payload, options) => post(runtimeSocketPath, payload, options?.signal),
|
|
177
|
+
});
|
|
178
|
+
}
|
|
179
|
+
public resolveAccess(input: IReq_AuthSwitchResolveAccess['request']): Promise<IReq_AuthSwitchResolveAccess['response']> {
|
|
180
|
+
return new plugins.typedrequest.TypedRequest<IReq_AuthSwitchResolveAccess>(this.target,
|
|
181
|
+
'authswitch.authority.resolveAccess').fire(input, { timeoutMs: 35_000, maxRetries: 0 });
|
|
182
|
+
}
|
|
183
|
+
}
|
|
@@ -0,0 +1,219 @@
|
|
|
1
|
+
import type { ITypedRequest } from '@api.global/typedrequest-interfaces';
|
|
2
|
+
import * as plugins from './plugins.js';
|
|
3
|
+
import type {
|
|
4
|
+
IReq_AuthSwitchBeginAdd, IReq_AuthSwitchBeginReauth, IReq_AuthSwitchCancelOperation,
|
|
5
|
+
IReq_AuthSwitchEvents, IReq_AuthSwitchGetOperation, IReq_AuthSwitchRemoveAccount,
|
|
6
|
+
IReq_AuthSwitchRenameAccount, IReq_AuthSwitchSnapshot,
|
|
7
|
+
} from './authority-contract.js';
|
|
8
|
+
import type { IReq_AuthSwitchBindAccount, IReq_AuthSwitchResolveAccess } from './authority-runtime-contract.js';
|
|
9
|
+
import { AuthSwitchAuthorityBroker, type IAuthSwitchAuthorityBrokerOptions } from './classes.authoritybroker.js';
|
|
10
|
+
import { AuthSwitchAuthorityDatabase, type IAuthSwitchAuthorityDatabaseOptions } from './classes.authoritydatabase.js';
|
|
11
|
+
import { AuthSwitchAuthorityFrameReader, authSwitchAuthorityFrameBytes,
|
|
12
|
+
maxAuthSwitchAuthorityFrameBytes } from './classes.authorityframing.js';
|
|
13
|
+
|
|
14
|
+
export interface IAuthSwitchAuthorityDaemonOptions extends IAuthSwitchAuthorityDatabaseOptions {
|
|
15
|
+
authoritySocketPath: string;
|
|
16
|
+
runtimeSocketPath: string;
|
|
17
|
+
broker?: IAuthSwitchAuthorityBrokerOptions;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
const hasKeys = (value: unknown, keys: readonly string[]): value is Record<string, unknown> =>
|
|
21
|
+
value !== null && typeof value === 'object' && !Array.isArray(value)
|
|
22
|
+
&& Object.keys(value).length === keys.length && keys.every(key => Object.hasOwn(value, key));
|
|
23
|
+
const invalid = (): never => { throw new plugins.typedrequest.TypedResponseError('Invalid authswitch authority request.'); };
|
|
24
|
+
|
|
25
|
+
/** TypedRequest handlers over a private one-request-per-connection Unix socket. */
|
|
26
|
+
export class AuthSwitchAuthorityDaemon {
|
|
27
|
+
public readonly database: AuthSwitchAuthorityDatabase;
|
|
28
|
+
public readonly broker: AuthSwitchAuthorityBroker;
|
|
29
|
+
private readonly managementRouter = new plugins.typedrequest.TypedRouter();
|
|
30
|
+
private readonly runtimeRouter = new plugins.typedrequest.TypedRouter();
|
|
31
|
+
private managementServer?: plugins.net.Server;
|
|
32
|
+
private runtimeServer?: plugins.net.Server;
|
|
33
|
+
private readonly sockets = new Set<plugins.net.Socket>();
|
|
34
|
+
|
|
35
|
+
constructor(private readonly options: IAuthSwitchAuthorityDaemonOptions) {
|
|
36
|
+
this.database = new AuthSwitchAuthorityDatabase(options);
|
|
37
|
+
this.broker = new AuthSwitchAuthorityBroker(this.database, options.broker);
|
|
38
|
+
this.register();
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
private register(): void {
|
|
42
|
+
this.managementRouter.addTypedHandler(new plugins.typedrequest.TypedHandler<IReq_AuthSwitchSnapshot>(
|
|
43
|
+
'authswitch.authority.snapshot', async request => {
|
|
44
|
+
if (request === null || typeof request !== 'object' || Array.isArray(request)) invalid();
|
|
45
|
+
const keys = Object.keys(request);
|
|
46
|
+
if (keys.some(key => !['accountAfter', 'bindingAfter', 'limit'].includes(key))) invalid();
|
|
47
|
+
return { snapshot: await this.broker.snapshot(request) };
|
|
48
|
+
}));
|
|
49
|
+
this.managementRouter.addTypedHandler(new plugins.typedrequest.TypedHandler<IReq_AuthSwitchEvents>(
|
|
50
|
+
'authswitch.authority.events', async (request, tools) => {
|
|
51
|
+
if (!hasKeys(request, ['epoch', 'afterRevision', 'waitMs'])) invalid();
|
|
52
|
+
return this.broker.events(request.epoch, request.afterRevision, request.waitMs, tools?.abortSignal);
|
|
53
|
+
}));
|
|
54
|
+
this.managementRouter.addTypedHandler(new plugins.typedrequest.TypedHandler<IReq_AuthSwitchBeginAdd>(
|
|
55
|
+
'authswitch.authority.add', async request => {
|
|
56
|
+
if (!hasKeys(request, ['providerId', 'flow']) || request.providerId !== 'openai' || request.flow !== 'device') invalid();
|
|
57
|
+
return { operation: await this.broker.beginAddOpenAi() };
|
|
58
|
+
}));
|
|
59
|
+
this.managementRouter.addTypedHandler(new plugins.typedrequest.TypedHandler<IReq_AuthSwitchBeginReauth>(
|
|
60
|
+
'authswitch.authority.reauth', async request => {
|
|
61
|
+
if (!hasKeys(request, ['accountId', 'flow']) || request.flow !== 'device' || typeof request.accountId !== 'string') invalid();
|
|
62
|
+
return { operation: await this.broker.beginReauthOpenAi(request.accountId) };
|
|
63
|
+
}));
|
|
64
|
+
this.managementRouter.addTypedHandler(new plugins.typedrequest.TypedHandler<IReq_AuthSwitchGetOperation>(
|
|
65
|
+
'authswitch.authority.operation', async request => {
|
|
66
|
+
if (!hasKeys(request, ['operationId']) || typeof request.operationId !== 'string') invalid();
|
|
67
|
+
return { operation: this.broker.getOperation(request.operationId) };
|
|
68
|
+
}));
|
|
69
|
+
this.managementRouter.addTypedHandler(new plugins.typedrequest.TypedHandler<IReq_AuthSwitchCancelOperation>(
|
|
70
|
+
'authswitch.authority.cancel', async request => {
|
|
71
|
+
if (!hasKeys(request, ['operationId']) || typeof request.operationId !== 'string') invalid();
|
|
72
|
+
return { operation: await this.broker.cancelOperation(request.operationId) };
|
|
73
|
+
}));
|
|
74
|
+
this.managementRouter.addTypedHandler(new plugins.typedrequest.TypedHandler<IReq_AuthSwitchRenameAccount>(
|
|
75
|
+
'authswitch.authority.rename', async request => {
|
|
76
|
+
if (!hasKeys(request, ['accountId', 'expectedRevision', 'label']) || typeof request.accountId !== 'string'
|
|
77
|
+
|| typeof request.expectedRevision !== 'number' || typeof request.label !== 'string') invalid();
|
|
78
|
+
return { account: await this.broker.renameAccount(request.accountId, request.expectedRevision, request.label) };
|
|
79
|
+
}));
|
|
80
|
+
this.managementRouter.addTypedHandler(new plugins.typedrequest.TypedHandler<IReq_AuthSwitchRemoveAccount>(
|
|
81
|
+
'authswitch.authority.remove', async request => {
|
|
82
|
+
if (!hasKeys(request, ['accountId', 'expectedRevision']) || typeof request.accountId !== 'string'
|
|
83
|
+
|| typeof request.expectedRevision !== 'number') invalid();
|
|
84
|
+
return { account: await this.broker.removeAccount(request.accountId, request.expectedRevision) };
|
|
85
|
+
}));
|
|
86
|
+
this.managementRouter.addTypedHandler(new plugins.typedrequest.TypedHandler<IReq_AuthSwitchBindAccount>(
|
|
87
|
+
'authswitch.authority.bind', async request => {
|
|
88
|
+
if (!hasKeys(request, ['accountId', 'runtime', 'scopeId', 'incarnationId'])
|
|
89
|
+
|| typeof request.accountId !== 'string' || typeof request.scopeId !== 'string'
|
|
90
|
+
|| typeof request.incarnationId !== 'string') invalid();
|
|
91
|
+
return this.broker.bindAccount(request);
|
|
92
|
+
}));
|
|
93
|
+
this.runtimeRouter.addTypedHandler(new plugins.typedrequest.TypedHandler<IReq_AuthSwitchResolveAccess>(
|
|
94
|
+
'authswitch.authority.resolveAccess', async request => {
|
|
95
|
+
if (!hasKeys(request, ['bindingId', 'capability', 'minValidityMs'])
|
|
96
|
+
|| typeof request.bindingId !== 'string' || typeof request.capability !== 'string'
|
|
97
|
+
|| typeof request.minValidityMs !== 'number') invalid();
|
|
98
|
+
return this.broker.resolveAccess(request.bindingId, request.capability, request.minValidityMs);
|
|
99
|
+
}));
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
public async start(): Promise<void> {
|
|
103
|
+
if (this.managementServer || this.runtimeServer) throw new Error('Authswitch authority daemon is already started.');
|
|
104
|
+
await this.database.start();
|
|
105
|
+
try {
|
|
106
|
+
await this.broker.start();
|
|
107
|
+
const managementDirectory = plugins.path.dirname(this.options.authoritySocketPath);
|
|
108
|
+
const runtimeDirectory = plugins.path.dirname(this.options.runtimeSocketPath);
|
|
109
|
+
const databaseDirectory = plugins.path.dirname(this.options.socketPath);
|
|
110
|
+
if (managementDirectory === runtimeDirectory || databaseDirectory === runtimeDirectory
|
|
111
|
+
|| managementDirectory.startsWith(runtimeDirectory + plugins.path.sep)
|
|
112
|
+
|| databaseDirectory.startsWith(runtimeDirectory + plugins.path.sep)
|
|
113
|
+
|| runtimeDirectory.startsWith(managementDirectory + plugins.path.sep)
|
|
114
|
+
|| runtimeDirectory.startsWith(databaseDirectory + plugins.path.sep)) {
|
|
115
|
+
throw new Error('Runtime socket directory must contain no management or database endpoint.');
|
|
116
|
+
}
|
|
117
|
+
this.managementServer = await this.listen(this.options.authoritySocketPath, this.managementRouter);
|
|
118
|
+
this.runtimeServer = await this.listen(this.options.runtimeSocketPath, this.runtimeRouter);
|
|
119
|
+
} catch (error) {
|
|
120
|
+
try { await this.close(); } catch { /* Preserve startup failure. */ }
|
|
121
|
+
throw error;
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
private async listen(path: string, router: plugins.typedrequest.TypedRouter): Promise<plugins.net.Server> {
|
|
126
|
+
const directory = plugins.path.dirname(path);
|
|
127
|
+
await plugins.fs.promises.mkdir(directory, { recursive: true, mode: 0o700 });
|
|
128
|
+
const stat = await plugins.fs.promises.lstat(directory);
|
|
129
|
+
if (!stat.isDirectory() || stat.isSymbolicLink() || stat.uid !== process.getuid?.()) {
|
|
130
|
+
throw new Error('Authswitch authority socket directory is not private.');
|
|
131
|
+
}
|
|
132
|
+
await plugins.fs.promises.chmod(directory, 0o700);
|
|
133
|
+
await this.clearStaleSocket(path);
|
|
134
|
+
const server = plugins.net.createServer(socket => this.accept(socket, router));
|
|
135
|
+
try {
|
|
136
|
+
await new Promise<void>((resolve, reject) => {
|
|
137
|
+
server.once('error', reject);
|
|
138
|
+
server.listen(path, () => { server.off('error', reject); resolve(); });
|
|
139
|
+
});
|
|
140
|
+
await plugins.fs.promises.chmod(path, 0o600);
|
|
141
|
+
return server;
|
|
142
|
+
} catch (error) {
|
|
143
|
+
if (server.listening) await new Promise<void>(resolve => server.close(() => resolve()));
|
|
144
|
+
throw error;
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
/** A killed daemon leaves a pathname behind; only remove an unchanged, owned, refused Unix socket. */
|
|
149
|
+
private async clearStaleSocket(path: string): Promise<void> {
|
|
150
|
+
let before: plugins.fs.Stats;
|
|
151
|
+
try { before = await plugins.fs.promises.lstat(path); }
|
|
152
|
+
catch (error) {
|
|
153
|
+
if ((error as NodeJS.ErrnoException).code === 'ENOENT') return;
|
|
154
|
+
throw error;
|
|
155
|
+
}
|
|
156
|
+
if (!before.isSocket() || before.uid !== process.getuid?.()) throw new Error('Authswitch socket path is unsafe.');
|
|
157
|
+
const refused = await new Promise<boolean>((resolve, reject) => {
|
|
158
|
+
const probe = plugins.net.createConnection(path);
|
|
159
|
+
probe.setTimeout(1_000, () => { probe.destroy(); reject(new Error('Authswitch socket probe timed out.')); });
|
|
160
|
+
probe.once('connect', () => { probe.destroy(); resolve(false); });
|
|
161
|
+
probe.once('error', error => {
|
|
162
|
+
probe.destroy();
|
|
163
|
+
if ((error as NodeJS.ErrnoException).code === 'ECONNREFUSED') resolve(true);
|
|
164
|
+
else reject(error);
|
|
165
|
+
});
|
|
166
|
+
});
|
|
167
|
+
if (!refused) throw new Error('Authswitch authority socket is already active.');
|
|
168
|
+
const after = await plugins.fs.promises.lstat(path);
|
|
169
|
+
if (!after.isSocket() || after.uid !== before.uid || after.dev !== before.dev || after.ino !== before.ino) {
|
|
170
|
+
throw new Error('Authswitch socket path changed during startup.');
|
|
171
|
+
}
|
|
172
|
+
await plugins.fs.promises.unlink(path);
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
private accept(socket: plugins.net.Socket, router: plugins.typedrequest.TypedRouter): void {
|
|
176
|
+
this.sockets.add(socket);
|
|
177
|
+
const abort = new AbortController();
|
|
178
|
+
socket.on('close', () => { this.sockets.delete(socket); abort.abort(); });
|
|
179
|
+
const frame = new AuthSwitchAuthorityFrameReader();
|
|
180
|
+
let handled = false;
|
|
181
|
+
socket.setTimeout(35_000, () => socket.destroy());
|
|
182
|
+
socket.on('data', chunk => {
|
|
183
|
+
if (handled) { socket.destroy(); return; }
|
|
184
|
+
if (!Buffer.isBuffer(chunk)) { socket.destroy(); return; }
|
|
185
|
+
let input: string | null;
|
|
186
|
+
try { input = frame.add(chunk); }
|
|
187
|
+
catch { socket.destroy(); return; }
|
|
188
|
+
if (input === null) return;
|
|
189
|
+
handled = true;
|
|
190
|
+
let request: ITypedRequest;
|
|
191
|
+
try { request = JSON.parse(input) as ITypedRequest; }
|
|
192
|
+
catch { socket.destroy(); return; }
|
|
193
|
+
void router.routeAndAddResponse(request, { trustedLocalData: { authoritySocket: socket },
|
|
194
|
+
trustedAbortSignal: abort.signal })
|
|
195
|
+
.then(response => {
|
|
196
|
+
const raw = JSON.stringify(response);
|
|
197
|
+
if (authSwitchAuthorityFrameBytes(raw) > maxAuthSwitchAuthorityFrameBytes) { socket.destroy(); return; }
|
|
198
|
+
socket.end(raw + '\n');
|
|
199
|
+
}).catch(() => socket.destroy());
|
|
200
|
+
});
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
public async close(): Promise<void> {
|
|
204
|
+
const errors: unknown[] = [];
|
|
205
|
+
try { await this.broker.close(); } catch (error) { errors.push(error); }
|
|
206
|
+
const management = this.managementServer;
|
|
207
|
+
const runtime = this.runtimeServer;
|
|
208
|
+
this.managementServer = undefined;
|
|
209
|
+
this.runtimeServer = undefined;
|
|
210
|
+
for (const socket of this.sockets) socket.destroy();
|
|
211
|
+
for (const server of [management, runtime]) {
|
|
212
|
+
if (server) try {
|
|
213
|
+
await new Promise<void>((resolve, reject) => server.close(error => error ? reject(error) : resolve()));
|
|
214
|
+
} catch (error) { errors.push(error); }
|
|
215
|
+
}
|
|
216
|
+
try { await this.database.stop(); } catch (error) { errors.push(error); }
|
|
217
|
+
if (errors.length) throw new AggregateError(errors, 'Authswitch authority shutdown was incomplete.');
|
|
218
|
+
}
|
|
219
|
+
}
|