@decryption/accounts 0.0.0-stage → 0.2.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.
- package/LICENSE +21 -0
- package/README.md +176 -2
- package/client.d.ts +77 -0
- package/client.js +381 -0
- package/credentials.d.ts +53 -0
- package/credentials.js +57 -0
- package/endpoint.d.ts +11 -0
- package/endpoint.js +44 -0
- package/esm/client.js +372 -0
- package/esm/credentials.js +53 -0
- package/esm/endpoint.js +39 -0
- package/esm/index.js +5 -0
- package/esm/manager.js +347 -0
- package/esm/types.js +1 -0
- package/index.d.ts +5 -0
- package/index.js +21 -0
- package/manager.d.ts +101 -0
- package/manager.js +352 -0
- package/package.json +45 -4
- package/types.d.ts +104 -0
- package/types.js +2 -0
package/credentials.d.ts
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
import { AccountManager } from './manager';
|
|
2
|
+
/**
|
|
3
|
+
* Result of a data-plane token request, structurally the harness's own
|
|
4
|
+
* `DataTokenResult`. The shape is duplicated rather than imported so this
|
|
5
|
+
* package does not depend on the harness to serve it — the harness is
|
|
6
|
+
* auth-agnostic by design and asks only for these two methods.
|
|
7
|
+
*/
|
|
8
|
+
export interface DataTokenResult {
|
|
9
|
+
token: string | null;
|
|
10
|
+
/** Where the token came from; always the vault when dcrypt answers. */
|
|
11
|
+
origin?: string;
|
|
12
|
+
}
|
|
13
|
+
/** The credential contract a harness host supplies (`HarnessCredentials`). */
|
|
14
|
+
export interface CredentialProvider {
|
|
15
|
+
accountBearer(): Promise<string | null>;
|
|
16
|
+
dataToken(databaseId: string): Promise<DataTokenResult>;
|
|
17
|
+
}
|
|
18
|
+
export interface VaultCredentialsOptions {
|
|
19
|
+
/** Serve this account. Otherwise the one signed-in account is used. */
|
|
20
|
+
accountItemId?: string;
|
|
21
|
+
}
|
|
22
|
+
/**
|
|
23
|
+
* Serves a harness its credentials out of the unlocked vault, so the harness,
|
|
24
|
+
* the CLI and any MCP host stop each keeping their own copy of a token on
|
|
25
|
+
* disk. Locking dcrypt cuts every one of them off at once, and there is a
|
|
26
|
+
* single place to revoke.
|
|
27
|
+
*
|
|
28
|
+
* Nothing is cached: every call re-reads the vault, because a token that was
|
|
29
|
+
* valid when the provider was constructed says nothing about now.
|
|
30
|
+
*/
|
|
31
|
+
export declare class VaultCredentials implements CredentialProvider {
|
|
32
|
+
private readonly accounts;
|
|
33
|
+
private readonly options;
|
|
34
|
+
constructor(accounts: AccountManager, options?: VaultCredentialsOptions);
|
|
35
|
+
/** The control-plane bearer, or null when signed out, expired or ambiguous. */
|
|
36
|
+
accountBearer(): Promise<string | null>;
|
|
37
|
+
/**
|
|
38
|
+
* The data-plane token for one provisioned database: the API key tagged with
|
|
39
|
+
* that database id. An untagged key is never handed over — a key minted for
|
|
40
|
+
* something else is not this database's token, and guessing would hand a
|
|
41
|
+
* caller more authority than it asked for.
|
|
42
|
+
*
|
|
43
|
+
* An API key is its own credential, so this does not require a live session;
|
|
44
|
+
* a signed-out account can still serve the key it minted.
|
|
45
|
+
*/
|
|
46
|
+
dataToken(databaseId: string): Promise<DataTokenResult>;
|
|
47
|
+
/**
|
|
48
|
+
* Which account to serve. With no explicit choice, exactly one account must
|
|
49
|
+
* be signed in: picking for the caller when several are would silently act
|
|
50
|
+
* as the wrong user, which is worse than refusing.
|
|
51
|
+
*/
|
|
52
|
+
private account;
|
|
53
|
+
}
|
package/credentials.js
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.VaultCredentials = void 0;
|
|
4
|
+
/**
|
|
5
|
+
* Serves a harness its credentials out of the unlocked vault, so the harness,
|
|
6
|
+
* the CLI and any MCP host stop each keeping their own copy of a token on
|
|
7
|
+
* disk. Locking dcrypt cuts every one of them off at once, and there is a
|
|
8
|
+
* single place to revoke.
|
|
9
|
+
*
|
|
10
|
+
* Nothing is cached: every call re-reads the vault, because a token that was
|
|
11
|
+
* valid when the provider was constructed says nothing about now.
|
|
12
|
+
*/
|
|
13
|
+
class VaultCredentials {
|
|
14
|
+
accounts;
|
|
15
|
+
options;
|
|
16
|
+
constructor(accounts, options = {}) {
|
|
17
|
+
this.accounts = accounts;
|
|
18
|
+
this.options = options;
|
|
19
|
+
}
|
|
20
|
+
/** The control-plane bearer, or null when signed out, expired or ambiguous. */
|
|
21
|
+
async accountBearer() {
|
|
22
|
+
const account = await this.account();
|
|
23
|
+
return account ? this.accounts.accessToken(account.itemId) : null;
|
|
24
|
+
}
|
|
25
|
+
/**
|
|
26
|
+
* The data-plane token for one provisioned database: the API key tagged with
|
|
27
|
+
* that database id. An untagged key is never handed over — a key minted for
|
|
28
|
+
* something else is not this database's token, and guessing would hand a
|
|
29
|
+
* caller more authority than it asked for.
|
|
30
|
+
*
|
|
31
|
+
* An API key is its own credential, so this does not require a live session;
|
|
32
|
+
* a signed-out account can still serve the key it minted.
|
|
33
|
+
*/
|
|
34
|
+
async dataToken(databaseId) {
|
|
35
|
+
const keys = await this.accounts.listApiKeys(this.options.accountItemId);
|
|
36
|
+
const matches = keys.filter((key) => key.databaseId === databaseId);
|
|
37
|
+
if (matches.length !== 1)
|
|
38
|
+
return { token: null };
|
|
39
|
+
return {
|
|
40
|
+
token: await this.accounts.revealApiKey(matches[0].itemId),
|
|
41
|
+
origin: 'vault',
|
|
42
|
+
};
|
|
43
|
+
}
|
|
44
|
+
/**
|
|
45
|
+
* Which account to serve. With no explicit choice, exactly one account must
|
|
46
|
+
* be signed in: picking for the caller when several are would silently act
|
|
47
|
+
* as the wrong user, which is worse than refusing.
|
|
48
|
+
*/
|
|
49
|
+
async account() {
|
|
50
|
+
if (this.options.accountItemId) {
|
|
51
|
+
return this.accounts.getAccount(this.options.accountItemId);
|
|
52
|
+
}
|
|
53
|
+
const signedIn = (await this.accounts.listAccounts()).filter((account) => account.signedIn);
|
|
54
|
+
return signedIn.length === 1 ? signedIn[0] : null;
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
exports.VaultCredentials = VaultCredentials;
|
package/endpoint.d.ts
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
/** Raised when an endpoint cannot be read as a URL at all. */
|
|
2
|
+
export declare class EndpointError extends Error {
|
|
3
|
+
constructor(message: string);
|
|
4
|
+
}
|
|
5
|
+
/**
|
|
6
|
+
* Turn what a human types into the GraphQL URL the SDK needs: a bare host gets
|
|
7
|
+
* `/graphql`, and a scheme is assumed (http for localhost, https otherwise).
|
|
8
|
+
* Everything else is left alone, so an endpoint that is already a full URL —
|
|
9
|
+
* including one on a non-standard path — round-trips unchanged.
|
|
10
|
+
*/
|
|
11
|
+
export declare const normalizeEndpoint: (input: string) => string;
|
package/endpoint.js
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.normalizeEndpoint = exports.EndpointError = void 0;
|
|
4
|
+
/** Raised when an endpoint cannot be read as a URL at all. */
|
|
5
|
+
class EndpointError extends Error {
|
|
6
|
+
constructor(message) {
|
|
7
|
+
super(message);
|
|
8
|
+
this.name = 'EndpointError';
|
|
9
|
+
}
|
|
10
|
+
}
|
|
11
|
+
exports.EndpointError = EndpointError;
|
|
12
|
+
/** Hosts that are never reachable over TLS in a dev setup. */
|
|
13
|
+
const isLocal = (host) => host === 'localhost' ||
|
|
14
|
+
host.endsWith('.localhost') ||
|
|
15
|
+
host === '::1' ||
|
|
16
|
+
/^127\./.test(host);
|
|
17
|
+
/**
|
|
18
|
+
* Turn what a human types into the GraphQL URL the SDK needs: a bare host gets
|
|
19
|
+
* `/graphql`, and a scheme is assumed (http for localhost, https otherwise).
|
|
20
|
+
* Everything else is left alone, so an endpoint that is already a full URL —
|
|
21
|
+
* including one on a non-standard path — round-trips unchanged.
|
|
22
|
+
*/
|
|
23
|
+
const normalizeEndpoint = (input) => {
|
|
24
|
+
const trimmed = input.trim();
|
|
25
|
+
if (!trimmed)
|
|
26
|
+
throw new EndpointError('an auth endpoint is required');
|
|
27
|
+
const hostOnly = !/^[a-z][a-z0-9+.-]*:\/\//i.test(trimmed);
|
|
28
|
+
const scheme = isLocal(trimmed.split(/[:/]/)[0]) ? 'http://' : 'https://';
|
|
29
|
+
let url;
|
|
30
|
+
try {
|
|
31
|
+
url = new URL(hostOnly ? scheme + trimmed : trimmed);
|
|
32
|
+
}
|
|
33
|
+
catch {
|
|
34
|
+
throw new EndpointError(`not a URL: ${input}`);
|
|
35
|
+
}
|
|
36
|
+
if (url.protocol !== 'http:' && url.protocol !== 'https:') {
|
|
37
|
+
throw new EndpointError(`unsupported scheme ${url.protocol} in ${input}`);
|
|
38
|
+
}
|
|
39
|
+
if (url.pathname === '/' || url.pathname === '')
|
|
40
|
+
url.pathname = '/graphql';
|
|
41
|
+
url.hash = '';
|
|
42
|
+
return url.toString();
|
|
43
|
+
};
|
|
44
|
+
exports.normalizeEndpoint = normalizeEndpoint;
|
package/esm/client.js
ADDED
|
@@ -0,0 +1,372 @@
|
|
|
1
|
+
import { auth } from '@constructive-io/sdk';
|
|
2
|
+
import { normalizeEndpoint } from './endpoint';
|
|
3
|
+
/** Raised when the auth server refuses a call, with the server's own wording. */
|
|
4
|
+
export class AuthError extends Error {
|
|
5
|
+
operation;
|
|
6
|
+
constructor(operation, message) {
|
|
7
|
+
super(message);
|
|
8
|
+
this.operation = operation;
|
|
9
|
+
this.name = 'AuthError';
|
|
10
|
+
}
|
|
11
|
+
}
|
|
12
|
+
/**
|
|
13
|
+
* The session is authenticated but not *recently* verified. Recoverable: prove
|
|
14
|
+
* the factor, then run the very same request again.
|
|
15
|
+
*/
|
|
16
|
+
export class StepUpRequiredError extends AuthError {
|
|
17
|
+
kind;
|
|
18
|
+
constructor(operation, kind, message) {
|
|
19
|
+
super(operation, message);
|
|
20
|
+
this.kind = kind;
|
|
21
|
+
this.name = 'StepUpRequiredError';
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
const SESSION_SELECT = {
|
|
25
|
+
select: {
|
|
26
|
+
result: {
|
|
27
|
+
select: { userId: true, accessToken: true, accessTokenExpiresAt: true },
|
|
28
|
+
},
|
|
29
|
+
},
|
|
30
|
+
};
|
|
31
|
+
const readSession = (operation, payload) => {
|
|
32
|
+
if (!payload?.userId || !payload.accessToken) {
|
|
33
|
+
throw new AuthError(operation, 'the server returned no session');
|
|
34
|
+
}
|
|
35
|
+
return {
|
|
36
|
+
userId: payload.userId,
|
|
37
|
+
accessToken: payload.accessToken,
|
|
38
|
+
accessTokenExpiresAt: payload.accessTokenExpiresAt ?? null,
|
|
39
|
+
};
|
|
40
|
+
};
|
|
41
|
+
/**
|
|
42
|
+
* An auth plane old enough to still keep `allowed_mask` on `principals` derives
|
|
43
|
+
* the mask from `bit_length(permissions)` in the general permission table, and
|
|
44
|
+
* inserts NULL when that lookup finds nothing — so the constraint, not the
|
|
45
|
+
* lookup, is what fails, and the raw message names a column the caller never
|
|
46
|
+
* sent. Later schemas moved the mask onto `principal_scope_overrides`, where
|
|
47
|
+
* absent means "inherits", and the personal path simply works.
|
|
48
|
+
*/
|
|
49
|
+
const PERSONAL_MASK = /null value in column "allowed_mask" of relation "principals"/i;
|
|
50
|
+
export const explainFailure = (message, endpoint) => {
|
|
51
|
+
if (PERSONAL_MASK.test(message)) {
|
|
52
|
+
return ('this auth plane cannot create a personal principal: it still stores a ' +
|
|
53
|
+
'permission mask on the principal itself and found no permission row to ' +
|
|
54
|
+
'size it from — scope the principal to an organization instead, or ' +
|
|
55
|
+
'update the auth plane');
|
|
56
|
+
}
|
|
57
|
+
// a 404 means the URL is not a GraphQL route at all, which is by far the
|
|
58
|
+
// most common way to get this wrong — say so instead of passing on `HTTP 404`
|
|
59
|
+
if (!/\b404\b/.test(message))
|
|
60
|
+
return message;
|
|
61
|
+
const suffix = endpoint.endsWith('/graphql')
|
|
62
|
+
? 'check the host and that the auth plane is running'
|
|
63
|
+
: `try ${endpoint.replace(/\/$/, '')}/graphql`;
|
|
64
|
+
return `no GraphQL endpoint at ${endpoint} — ${suffix}`;
|
|
65
|
+
};
|
|
66
|
+
const STEP_UP = /STEP_UP_REQUIRED(?:_(PASSWORD|MFA|FRESH_AUTH))?/;
|
|
67
|
+
/**
|
|
68
|
+
* Which factor a message is asking for, or null. Exported because a step-up
|
|
69
|
+
* error arrives at a UI as plain text once it has crossed a process boundary,
|
|
70
|
+
* and the server's own code is the only trustworthy thing to key off.
|
|
71
|
+
*
|
|
72
|
+
* The bare `STEP_UP_REQUIRED` raised by the generated guard means the session
|
|
73
|
+
* has no recent password verification, so it asks for a password.
|
|
74
|
+
*/
|
|
75
|
+
export const stepUpKind = (message) => {
|
|
76
|
+
const found = STEP_UP.exec(message);
|
|
77
|
+
if (!found)
|
|
78
|
+
return null;
|
|
79
|
+
return found[1]?.toLowerCase() ?? 'password';
|
|
80
|
+
};
|
|
81
|
+
/**
|
|
82
|
+
* The server's defaults are the permissive ones: a principal inherits its
|
|
83
|
+
* owner unless a row says otherwise, so a missing flag reads as "inherits".
|
|
84
|
+
*/
|
|
85
|
+
const readPrincipal = (node) => ({
|
|
86
|
+
principalId: node.id,
|
|
87
|
+
name: node.name ?? '',
|
|
88
|
+
ownerId: node.ownerId ?? null,
|
|
89
|
+
isReadOnly: node.isReadOnly ?? false,
|
|
90
|
+
bypassStepUp: node.bypassStepUp ?? false,
|
|
91
|
+
useAdminOwner: node.useAdminOwner ?? true,
|
|
92
|
+
entityIds: (node.principalEntities?.nodes ?? [])
|
|
93
|
+
.map((entity) => entity.entityId)
|
|
94
|
+
.filter((id) => Boolean(id)),
|
|
95
|
+
scopes: (node.principalScopeOverrides?.nodes ?? []).map((scope) => ({
|
|
96
|
+
membershipType: scope.membershipType ?? 0,
|
|
97
|
+
allowedMask: scope.allowedMask ?? null,
|
|
98
|
+
isActive: scope.isActive ?? true,
|
|
99
|
+
isReadOnly: scope.isReadOnly ?? false,
|
|
100
|
+
useAdminOwner: scope.useAdminOwner ?? true,
|
|
101
|
+
})),
|
|
102
|
+
});
|
|
103
|
+
/**
|
|
104
|
+
* Whether the server rejected a *field*, rather than the request.
|
|
105
|
+
*
|
|
106
|
+
* The published SDK's types are generated from one schema and an auth plane may
|
|
107
|
+
* be running an older one, so a field the types promise can still be absent —
|
|
108
|
+
* something no amount of type-checking on this side can catch.
|
|
109
|
+
*/
|
|
110
|
+
export const missingField = (message) => /Cannot query field/i.test(message);
|
|
111
|
+
/**
|
|
112
|
+
* Everything a principal can tell us. Optimistic on purpose: ask for the whole
|
|
113
|
+
* picture, and fall back only when a particular server cannot supply it.
|
|
114
|
+
*/
|
|
115
|
+
const PRINCIPAL_SELECT = {
|
|
116
|
+
id: true,
|
|
117
|
+
name: true,
|
|
118
|
+
ownerId: true,
|
|
119
|
+
isReadOnly: true,
|
|
120
|
+
bypassStepUp: true,
|
|
121
|
+
useAdminOwner: true,
|
|
122
|
+
principalEntities: { select: { entityId: true }, first: 100 },
|
|
123
|
+
principalScopeOverrides: {
|
|
124
|
+
select: {
|
|
125
|
+
membershipType: true,
|
|
126
|
+
allowedMask: true,
|
|
127
|
+
isActive: true,
|
|
128
|
+
isReadOnly: true,
|
|
129
|
+
useAdminOwner: true,
|
|
130
|
+
},
|
|
131
|
+
first: 100,
|
|
132
|
+
},
|
|
133
|
+
};
|
|
134
|
+
/**
|
|
135
|
+
* The fields every vintage of the auth schema has. Dropping the rest costs
|
|
136
|
+
* detail, never correctness: an unread flag reads as inherited, which is what
|
|
137
|
+
* the server means by its absence anyway.
|
|
138
|
+
*/
|
|
139
|
+
const PRINCIPAL_SELECT_CORE = {
|
|
140
|
+
id: true,
|
|
141
|
+
name: true,
|
|
142
|
+
ownerId: true,
|
|
143
|
+
isReadOnly: true,
|
|
144
|
+
bypassStepUp: true,
|
|
145
|
+
principalEntities: { select: { entityId: true }, first: 100 },
|
|
146
|
+
principalScopeOverrides: {
|
|
147
|
+
select: { membershipType: true, allowedMask: true, isReadOnly: true },
|
|
148
|
+
first: 100,
|
|
149
|
+
},
|
|
150
|
+
};
|
|
151
|
+
/**
|
|
152
|
+
* A principal scoped to nothing but its owner — the personal CI identity.
|
|
153
|
+
*
|
|
154
|
+
* Sent by hand because the generated ORM has no `mutation.createPrincipal`: the
|
|
155
|
+
* codegen let the principals table's CRUD create shadow the procedure of the
|
|
156
|
+
* same inflected name, so the typed surface offers only the org variant. The
|
|
157
|
+
* auth schema itself does expose it, taking the flat input built here.
|
|
158
|
+
*/
|
|
159
|
+
const createPersonalPrincipal = async (endpoint, token, input) => {
|
|
160
|
+
const adapter = new auth.FetchAdapter(endpoint, token ? { Authorization: `Bearer ${token}` } : undefined);
|
|
161
|
+
const result = await adapter.execute(`mutation CreatePrincipal($input: CreatePrincipalInput!) {
|
|
162
|
+
createPrincipal(input: $input) { result }
|
|
163
|
+
}`, { input });
|
|
164
|
+
if (!result.ok)
|
|
165
|
+
throw new Error(result.errors.map((e) => e.message).join('; '));
|
|
166
|
+
return result.data.createPrincipal?.result ?? null;
|
|
167
|
+
};
|
|
168
|
+
const rethrow = (operation, endpoint, error) => {
|
|
169
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
170
|
+
const kind = stepUpKind(message);
|
|
171
|
+
if (kind)
|
|
172
|
+
throw new StepUpRequiredError(operation, kind, message);
|
|
173
|
+
throw new AuthError(operation, explainFailure(message, endpoint));
|
|
174
|
+
};
|
|
175
|
+
/** The real client: `@constructive-io/sdk`'s generated auth ORM. */
|
|
176
|
+
export const sdkAuthClient = (options) => {
|
|
177
|
+
const endpoint = normalizeEndpoint(options.endpoint);
|
|
178
|
+
const token = options.token;
|
|
179
|
+
const client = auth.createClient({
|
|
180
|
+
endpoint,
|
|
181
|
+
headers: token ? { Authorization: `Bearer ${token}` } : undefined,
|
|
182
|
+
});
|
|
183
|
+
return {
|
|
184
|
+
async signIn(input) {
|
|
185
|
+
try {
|
|
186
|
+
const data = await client.mutation
|
|
187
|
+
.signIn({
|
|
188
|
+
input: {
|
|
189
|
+
email: input.email,
|
|
190
|
+
password: input.password,
|
|
191
|
+
rememberMe: input.rememberMe ?? true,
|
|
192
|
+
},
|
|
193
|
+
}, SESSION_SELECT)
|
|
194
|
+
.unwrap();
|
|
195
|
+
return readSession('signIn', data.signIn?.result);
|
|
196
|
+
}
|
|
197
|
+
catch (error) {
|
|
198
|
+
if (error instanceof AuthError)
|
|
199
|
+
throw error;
|
|
200
|
+
return rethrow('signIn', endpoint, error);
|
|
201
|
+
}
|
|
202
|
+
},
|
|
203
|
+
async signUp(input) {
|
|
204
|
+
try {
|
|
205
|
+
const data = await client.mutation
|
|
206
|
+
.signUp({ input: { email: input.email, password: input.password } }, SESSION_SELECT)
|
|
207
|
+
.unwrap();
|
|
208
|
+
return readSession('signUp', data.signUp?.result);
|
|
209
|
+
}
|
|
210
|
+
catch (error) {
|
|
211
|
+
if (error instanceof AuthError)
|
|
212
|
+
throw error;
|
|
213
|
+
return rethrow('signUp', endpoint, error);
|
|
214
|
+
}
|
|
215
|
+
},
|
|
216
|
+
async signOut() {
|
|
217
|
+
try {
|
|
218
|
+
await client.mutation
|
|
219
|
+
.signOut({ input: {} }, { select: { clientMutationId: true } })
|
|
220
|
+
.unwrap();
|
|
221
|
+
}
|
|
222
|
+
catch (error) {
|
|
223
|
+
rethrow('signOut', endpoint, error);
|
|
224
|
+
}
|
|
225
|
+
},
|
|
226
|
+
async createApiKey(options) {
|
|
227
|
+
const input = {
|
|
228
|
+
keyName: options.name,
|
|
229
|
+
expiresIn: options.expiresIn,
|
|
230
|
+
accessLevel: options.accessLevel,
|
|
231
|
+
principalId: options.principalId,
|
|
232
|
+
};
|
|
233
|
+
const select = {
|
|
234
|
+
select: {
|
|
235
|
+
result: { select: { apiKey: true, keyId: true, expiresAt: true } },
|
|
236
|
+
},
|
|
237
|
+
};
|
|
238
|
+
try {
|
|
239
|
+
const result = options.orgId
|
|
240
|
+
? (await client.mutation
|
|
241
|
+
.createOrgApiKey({ input: { ...input, orgId: options.orgId } }, select)
|
|
242
|
+
.unwrap()).createOrgApiKey?.result
|
|
243
|
+
: (await client.mutation.createApiKey({ input }, select).unwrap())
|
|
244
|
+
.createApiKey?.result;
|
|
245
|
+
if (!result?.apiKey || !result.keyId) {
|
|
246
|
+
throw new AuthError('createApiKey', 'the server returned no key');
|
|
247
|
+
}
|
|
248
|
+
return {
|
|
249
|
+
apiKey: result.apiKey,
|
|
250
|
+
keyId: result.keyId,
|
|
251
|
+
expiresAt: result.expiresAt ?? null,
|
|
252
|
+
};
|
|
253
|
+
}
|
|
254
|
+
catch (error) {
|
|
255
|
+
if (error instanceof AuthError)
|
|
256
|
+
throw error;
|
|
257
|
+
return rethrow('createApiKey', endpoint, error);
|
|
258
|
+
}
|
|
259
|
+
},
|
|
260
|
+
async listPrincipals() {
|
|
261
|
+
const read = async (select) => {
|
|
262
|
+
const data = await client.principal.findMany({ first: 200, select }).unwrap();
|
|
263
|
+
return data.principals.nodes.map(readPrincipal);
|
|
264
|
+
};
|
|
265
|
+
try {
|
|
266
|
+
return await read(PRINCIPAL_SELECT);
|
|
267
|
+
}
|
|
268
|
+
catch (error) {
|
|
269
|
+
if (error instanceof AuthError)
|
|
270
|
+
throw error;
|
|
271
|
+
if (!missingField(error instanceof Error ? error.message : String(error))) {
|
|
272
|
+
return rethrow('listPrincipals', endpoint, error);
|
|
273
|
+
}
|
|
274
|
+
try {
|
|
275
|
+
return await read(PRINCIPAL_SELECT_CORE);
|
|
276
|
+
}
|
|
277
|
+
catch (retried) {
|
|
278
|
+
if (retried instanceof AuthError)
|
|
279
|
+
throw retried;
|
|
280
|
+
return rethrow('listPrincipals', endpoint, retried);
|
|
281
|
+
}
|
|
282
|
+
}
|
|
283
|
+
},
|
|
284
|
+
async createPrincipal(options) {
|
|
285
|
+
const flags = {
|
|
286
|
+
isReadOnly: options.isReadOnly,
|
|
287
|
+
bypassStepUp: options.bypassStepUp,
|
|
288
|
+
// omitted rather than sent as null, so a server that predates
|
|
289
|
+
// the field is not asked about it at all
|
|
290
|
+
...(options.useAdminOwner === undefined
|
|
291
|
+
? {}
|
|
292
|
+
: { useAdminOwner: options.useAdminOwner }),
|
|
293
|
+
};
|
|
294
|
+
try {
|
|
295
|
+
const principalId = options.orgId
|
|
296
|
+
? (await client.mutation
|
|
297
|
+
.createOrgPrincipal({ input: { name: options.name, orgId: options.orgId, ...flags } }, { select: { result: true } })
|
|
298
|
+
.unwrap()).createOrgPrincipal?.result
|
|
299
|
+
: await createPersonalPrincipal(endpoint, token, {
|
|
300
|
+
name: options.name,
|
|
301
|
+
...flags,
|
|
302
|
+
});
|
|
303
|
+
if (!principalId) {
|
|
304
|
+
throw new AuthError('createPrincipal', 'the server returned no principal');
|
|
305
|
+
}
|
|
306
|
+
return principalId;
|
|
307
|
+
}
|
|
308
|
+
catch (error) {
|
|
309
|
+
if (error instanceof AuthError)
|
|
310
|
+
throw error;
|
|
311
|
+
return rethrow('createPrincipal', endpoint, error);
|
|
312
|
+
}
|
|
313
|
+
},
|
|
314
|
+
async deletePrincipal(principalId) {
|
|
315
|
+
try {
|
|
316
|
+
await client.mutation
|
|
317
|
+
.deletePrincipal({ input: { principalId } }, { select: { clientMutationId: true } })
|
|
318
|
+
.unwrap();
|
|
319
|
+
}
|
|
320
|
+
catch (error) {
|
|
321
|
+
if (error instanceof AuthError)
|
|
322
|
+
throw error;
|
|
323
|
+
rethrow('deletePrincipal', endpoint, error);
|
|
324
|
+
}
|
|
325
|
+
},
|
|
326
|
+
async verifyPassword(password) {
|
|
327
|
+
try {
|
|
328
|
+
const data = await client.mutation
|
|
329
|
+
.verifyPassword({ input: { password } }, { select: { result: true } })
|
|
330
|
+
.unwrap();
|
|
331
|
+
if (data.verifyPassword?.result !== true) {
|
|
332
|
+
throw new AuthError('verifyPassword', 'the password was not accepted');
|
|
333
|
+
}
|
|
334
|
+
}
|
|
335
|
+
catch (error) {
|
|
336
|
+
if (error instanceof AuthError)
|
|
337
|
+
throw error;
|
|
338
|
+
rethrow('verifyPassword', endpoint, error);
|
|
339
|
+
}
|
|
340
|
+
},
|
|
341
|
+
async verifyTotp(code) {
|
|
342
|
+
try {
|
|
343
|
+
const data = await client.mutation
|
|
344
|
+
.verifyTotp({ input: { totpValue: code } }, { select: { result: true } })
|
|
345
|
+
.unwrap();
|
|
346
|
+
if (data.verifyTotp?.result !== true) {
|
|
347
|
+
throw new AuthError('verifyTotp', 'the code was not accepted');
|
|
348
|
+
}
|
|
349
|
+
}
|
|
350
|
+
catch (error) {
|
|
351
|
+
if (error instanceof AuthError)
|
|
352
|
+
throw error;
|
|
353
|
+
rethrow('verifyTotp', endpoint, error);
|
|
354
|
+
}
|
|
355
|
+
},
|
|
356
|
+
async revokeApiKey(keyId) {
|
|
357
|
+
try {
|
|
358
|
+
const data = await client.mutation
|
|
359
|
+
.revokeApiKey({ input: { keyId } }, { select: { result: true } })
|
|
360
|
+
.unwrap();
|
|
361
|
+
if (data.revokeApiKey?.result !== true) {
|
|
362
|
+
throw new AuthError('revokeApiKey', `the server did not revoke ${keyId}`);
|
|
363
|
+
}
|
|
364
|
+
}
|
|
365
|
+
catch (error) {
|
|
366
|
+
if (error instanceof AuthError)
|
|
367
|
+
throw error;
|
|
368
|
+
rethrow('revokeApiKey', endpoint, error);
|
|
369
|
+
}
|
|
370
|
+
},
|
|
371
|
+
};
|
|
372
|
+
};
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Serves a harness its credentials out of the unlocked vault, so the harness,
|
|
3
|
+
* the CLI and any MCP host stop each keeping their own copy of a token on
|
|
4
|
+
* disk. Locking dcrypt cuts every one of them off at once, and there is a
|
|
5
|
+
* single place to revoke.
|
|
6
|
+
*
|
|
7
|
+
* Nothing is cached: every call re-reads the vault, because a token that was
|
|
8
|
+
* valid when the provider was constructed says nothing about now.
|
|
9
|
+
*/
|
|
10
|
+
export class VaultCredentials {
|
|
11
|
+
accounts;
|
|
12
|
+
options;
|
|
13
|
+
constructor(accounts, options = {}) {
|
|
14
|
+
this.accounts = accounts;
|
|
15
|
+
this.options = options;
|
|
16
|
+
}
|
|
17
|
+
/** The control-plane bearer, or null when signed out, expired or ambiguous. */
|
|
18
|
+
async accountBearer() {
|
|
19
|
+
const account = await this.account();
|
|
20
|
+
return account ? this.accounts.accessToken(account.itemId) : null;
|
|
21
|
+
}
|
|
22
|
+
/**
|
|
23
|
+
* The data-plane token for one provisioned database: the API key tagged with
|
|
24
|
+
* that database id. An untagged key is never handed over — a key minted for
|
|
25
|
+
* something else is not this database's token, and guessing would hand a
|
|
26
|
+
* caller more authority than it asked for.
|
|
27
|
+
*
|
|
28
|
+
* An API key is its own credential, so this does not require a live session;
|
|
29
|
+
* a signed-out account can still serve the key it minted.
|
|
30
|
+
*/
|
|
31
|
+
async dataToken(databaseId) {
|
|
32
|
+
const keys = await this.accounts.listApiKeys(this.options.accountItemId);
|
|
33
|
+
const matches = keys.filter((key) => key.databaseId === databaseId);
|
|
34
|
+
if (matches.length !== 1)
|
|
35
|
+
return { token: null };
|
|
36
|
+
return {
|
|
37
|
+
token: await this.accounts.revealApiKey(matches[0].itemId),
|
|
38
|
+
origin: 'vault',
|
|
39
|
+
};
|
|
40
|
+
}
|
|
41
|
+
/**
|
|
42
|
+
* Which account to serve. With no explicit choice, exactly one account must
|
|
43
|
+
* be signed in: picking for the caller when several are would silently act
|
|
44
|
+
* as the wrong user, which is worse than refusing.
|
|
45
|
+
*/
|
|
46
|
+
async account() {
|
|
47
|
+
if (this.options.accountItemId) {
|
|
48
|
+
return this.accounts.getAccount(this.options.accountItemId);
|
|
49
|
+
}
|
|
50
|
+
const signedIn = (await this.accounts.listAccounts()).filter((account) => account.signedIn);
|
|
51
|
+
return signedIn.length === 1 ? signedIn[0] : null;
|
|
52
|
+
}
|
|
53
|
+
}
|
package/esm/endpoint.js
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
/** Raised when an endpoint cannot be read as a URL at all. */
|
|
2
|
+
export class EndpointError extends Error {
|
|
3
|
+
constructor(message) {
|
|
4
|
+
super(message);
|
|
5
|
+
this.name = 'EndpointError';
|
|
6
|
+
}
|
|
7
|
+
}
|
|
8
|
+
/** Hosts that are never reachable over TLS in a dev setup. */
|
|
9
|
+
const isLocal = (host) => host === 'localhost' ||
|
|
10
|
+
host.endsWith('.localhost') ||
|
|
11
|
+
host === '::1' ||
|
|
12
|
+
/^127\./.test(host);
|
|
13
|
+
/**
|
|
14
|
+
* Turn what a human types into the GraphQL URL the SDK needs: a bare host gets
|
|
15
|
+
* `/graphql`, and a scheme is assumed (http for localhost, https otherwise).
|
|
16
|
+
* Everything else is left alone, so an endpoint that is already a full URL —
|
|
17
|
+
* including one on a non-standard path — round-trips unchanged.
|
|
18
|
+
*/
|
|
19
|
+
export const normalizeEndpoint = (input) => {
|
|
20
|
+
const trimmed = input.trim();
|
|
21
|
+
if (!trimmed)
|
|
22
|
+
throw new EndpointError('an auth endpoint is required');
|
|
23
|
+
const hostOnly = !/^[a-z][a-z0-9+.-]*:\/\//i.test(trimmed);
|
|
24
|
+
const scheme = isLocal(trimmed.split(/[:/]/)[0]) ? 'http://' : 'https://';
|
|
25
|
+
let url;
|
|
26
|
+
try {
|
|
27
|
+
url = new URL(hostOnly ? scheme + trimmed : trimmed);
|
|
28
|
+
}
|
|
29
|
+
catch {
|
|
30
|
+
throw new EndpointError(`not a URL: ${input}`);
|
|
31
|
+
}
|
|
32
|
+
if (url.protocol !== 'http:' && url.protocol !== 'https:') {
|
|
33
|
+
throw new EndpointError(`unsupported scheme ${url.protocol} in ${input}`);
|
|
34
|
+
}
|
|
35
|
+
if (url.pathname === '/' || url.pathname === '')
|
|
36
|
+
url.pathname = '/graphql';
|
|
37
|
+
url.hash = '';
|
|
38
|
+
return url.toString();
|
|
39
|
+
};
|