@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 ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2025 Constructive <developers@constructive.io>
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,177 @@
1
- # Temporary Holding Version
1
+ # @decryption/accounts
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ <p align="center" width="100%">
4
+ <img height="250" src="https://raw.githubusercontent.com/constructive-io/constructive/refs/heads/main/assets/outline-logo.svg" />
5
+ </p>
6
+
7
+ <p align="center" width="100%">
8
+ <a href="https://github.com/constructive-io/decryption/actions/workflows/ci.yml">
9
+ <img height="20" src="https://github.com/constructive-io/decryption/actions/workflows/ci.yml/badge.svg" />
10
+ </a>
11
+ <a href="https://github.com/constructive-io/decryption/blob/main/LICENSE">
12
+ <img height="20" alt="MIT license" src="https://img.shields.io/badge/license-MIT-blue.svg" />
13
+ </a>
14
+ <a href="https://www.npmjs.com/package/@decryption/accounts"><img height="20" src="https://img.shields.io/github/package-json/v/constructive-io/decryption?filename=packages%2Faccounts%2Fpackage.json"/></a>
15
+ </p>
16
+
17
+ Constructive accounts and API keys, held in the local dcrypt vault. Sign in against an auth
18
+ endpoint with [`@constructive-io/sdk`](https://www.npmjs.com/package/@constructive-io/sdk), mint and
19
+ revoke API keys, and keep every token and key secret inside the same encrypted file as the rest of
20
+ the vault — covered by the master passphrase, by lock, and by backup and restore.
21
+
22
+ ## Installation
23
+
24
+ ```bash
25
+ npm install @decryption/accounts
26
+ ```
27
+
28
+ ## Usage
29
+
30
+ ```typescript
31
+ import { AccountManager } from '@decryption/accounts';
32
+ import { Vault, defaultModulePath } from '@decryption/vault';
33
+
34
+ const vault = await Vault.open({
35
+ file: '~/.dcrypt/data/db/vault.dcrypt',
36
+ passphrase,
37
+ modulePath: defaultModulePath(),
38
+ });
39
+
40
+ const accounts = new AccountManager(vault);
41
+
42
+ const account = await accounts.signIn({
43
+ endpoint: 'http://auth.localhost:3000/graphql',
44
+ email: 'dev@example.com',
45
+ password,
46
+ });
47
+
48
+ const key = await accounts.createApiKey(account.itemId, {
49
+ name: 'ci',
50
+ expiresIn: { days: 30 },
51
+ });
52
+
53
+ // the secret is only ever read back out of the vault
54
+ const secret = await accounts.revealApiKey(key.itemId);
55
+
56
+ await accounts.revokeApiKey(key.itemId);
57
+ ```
58
+
59
+ ## What is stored
60
+
61
+ Each account is an `account` item and each key an `api_key` item, so both are searchable, taggable
62
+ and audited like every other vault entry.
63
+
64
+ | Item | Fields |
65
+ | --------- | ------------------------------------------------------------------ |
66
+ | `account` | `endpoint`, `email`, `user_id`, `access_token`\*, `access_token_expires_at` |
67
+ | `api_key` | `endpoint`, `account_id`, `key_id`, `api_key`\*, `expires_at`, `database_id`, `principal_id`, `org_id` |
68
+
69
+ \* concealed. `accessToken()` returns `null` rather than an expired token, so a caller cannot
70
+ present a dead credential by accident.
71
+
72
+ ## Principals
73
+
74
+ A principal is a scoped sub-identity — what an API key or an agent actually acts as. It is owned by
75
+ a human account and can only ever *narrow* that human: read-only, restricted per scope by a
76
+ permission mask, and optionally allowed to skip MFA step-up so CI is not blocked on a phone.
77
+
78
+ ```typescript
79
+ const principalId = await accounts.createPrincipal(account.itemId, {
80
+ name: 'ci-deploy',
81
+ orgId,
82
+ isReadOnly: true,
83
+ bypassStepUp: true,
84
+ });
85
+
86
+ // mint the key *as* the principal, so it carries the principal's scope
87
+ await accounts.createApiKey(account.itemId, { name: 'ci', principalId, orgId });
88
+
89
+ for (const principal of await accounts.listPrincipals(account.itemId)) {
90
+ principal.entityIds; // what it reaches
91
+ principal.scopes; // per-scope overrides: allowedMask, isActive, isReadOnly
92
+ }
93
+ ```
94
+
95
+ A scope with no override row means the principal inherits its owner there; `allowedMask` is
96
+ AND-ed with the owner's permissions during the SPRT cascade, so an override can only take access
97
+ away. Principals are read from the server on demand rather than cached, because a stale local copy
98
+ of someone's permissions is worse than none.
99
+
100
+ ## Serving a harness
101
+
102
+ `VaultCredentials` is a credential provider shaped like the harness contract, reading from the
103
+ unlocked vault instead of a plaintext `account.json`:
104
+
105
+ ```typescript
106
+ const credentials = new VaultCredentials(accounts);
107
+
108
+ await credentials.accountBearer(); // the signed-in account's token, or null
109
+ await credentials.dataToken(databaseId); // { token, origin: 'vault' }
110
+ ```
111
+
112
+ It refuses rather than guesses: `null` when no account is signed in, when several are and none was
113
+ named, when the token has expired, and when no key — or more than one — is tagged for that
114
+ database. Tag one with `accounts.assignKeyToDatabase(keyItemId, databaseId)` or
115
+ `createApiKey({ databaseId })`. Nothing is cached; every call re-reads the vault, so locking the
116
+ vault cuts every consumer off at once.
117
+
118
+ ## Testing without a server
119
+
120
+ `AccountManager` takes an `AuthClientFactory`, so the whole vault side runs against a fake:
121
+
122
+ ```typescript
123
+ const accounts = new AccountManager(vault, {
124
+ createClient: () => myFakeAuthClient,
125
+ });
126
+ ```
127
+
128
+ ## License
129
+
130
+ MIT
131
+
132
+ ## Credits
133
+
134
+ **🛠 Built by the [Constructive](https://constructive.io) team — creators of modular Postgres tooling for secure, composable backends. If you like our work, contribute on [GitHub](https://github.com/constructive-io).**
135
+
136
+ ## Disclaimer
137
+
138
+ AS DESCRIBED IN THE LICENSES, THE SOFTWARE IS PROVIDED "AS IS", AT YOUR OWN RISK, AND WITHOUT WARRANTIES OF ANY KIND.
139
+
140
+ No developer or entity involved in creating this software will be liable for any claims or damages whatsoever associated with your use, inability to use, or your interaction with other users of the code, including any direct, indirect, incidental, special, exemplary, punitive or consequential damages, or loss of profits, cryptocurrencies, tokens, or anything else of value.
141
+
142
+ ---
143
+
144
+ ## Development
145
+
146
+ ### Setup
147
+
148
+ 1. Clone the repository:
149
+
150
+ ```bash
151
+ git clone https://github.com/constructive-io/decryption.git
152
+ ```
153
+
154
+ 2. Install dependencies:
155
+
156
+ ```bash
157
+ cd decryption
158
+ pnpm install
159
+ pnpm build
160
+ ```
161
+
162
+ 3. Test the package of interest:
163
+
164
+ ```bash
165
+ cd packages/<packagename>
166
+ pnpm test:watch
167
+ ```
168
+
169
+ ## Credits
170
+
171
+ **🛠 Built by the [Constructive](https://constructive.io) team — creators of modular Postgres tooling for secure, composable backends. If you like our work, contribute on [GitHub](https://github.com/constructive-io).**
172
+
173
+ ## Disclaimer
174
+
175
+ AS DESCRIBED IN THE LICENSES, THE SOFTWARE IS PROVIDED "AS IS", AT YOUR OWN RISK, AND WITHOUT WARRANTIES OF ANY KIND.
176
+
177
+ No developer or entity involved in creating this software will be liable for any claims or damages whatsoever associated with your use, inability to use, or your interaction with other users of the code, including any direct, indirect, incidental, special, exemplary, punitive or consequential damages, or loss of profits, cryptocurrencies, tokens, or anything else of value.
package/client.d.ts ADDED
@@ -0,0 +1,77 @@
1
+ import { AuthSession, CreateApiKeyOptions, CreatedApiKey, CreatePrincipalOptions, PrincipalRecord } from './types';
2
+ /** Raised when the auth server refuses a call, with the server's own wording. */
3
+ export declare class AuthError extends Error {
4
+ readonly operation: string;
5
+ constructor(operation: string, message: string);
6
+ }
7
+ /**
8
+ * What the server wants re-proved before it will run a sensitive mutation.
9
+ * Mirrors the `STEP_UP_REQUIRED_*` exceptions raised by `require_step_up()`.
10
+ */
11
+ export type StepUpKind = 'password' | 'mfa' | 'fresh_auth';
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 declare class StepUpRequiredError extends AuthError {
17
+ readonly kind: StepUpKind;
18
+ constructor(operation: string, kind: StepUpKind, message: string);
19
+ }
20
+ /** A freshly proved factor, supplied to retry an operation that needed one. */
21
+ export interface StepUpProof {
22
+ password?: string;
23
+ totpCode?: string;
24
+ }
25
+ export interface SignInInput {
26
+ email: string;
27
+ password: string;
28
+ rememberMe?: boolean;
29
+ }
30
+ /**
31
+ * The slice of the Constructive auth API this package uses. Narrow on purpose:
32
+ * it keeps the vault side testable without a server, and it is the seam where
33
+ * a different transport (a proxy, a recorded fixture) can be dropped in.
34
+ */
35
+ export interface AuthClient {
36
+ signIn(input: SignInInput): Promise<AuthSession>;
37
+ signUp(input: SignInInput): Promise<AuthSession>;
38
+ signOut(): Promise<void>;
39
+ createApiKey(options: CreateApiKeyOptions): Promise<CreatedApiKey>;
40
+ revokeApiKey(keyId: string): Promise<void>;
41
+ /** Re-prove the password, refreshing the session's step-up window. */
42
+ verifyPassword(password: string): Promise<void>;
43
+ /** Re-prove MFA with a one-time code. */
44
+ verifyTotp(code: string): Promise<void>;
45
+ /** The caller's scoped sub-identities, with their scopes and masks. */
46
+ listPrincipals(): Promise<PrincipalRecord[]>;
47
+ /** Create a principal scoped to an organization; returns its id. */
48
+ createPrincipal(options: CreatePrincipalOptions): Promise<string>;
49
+ deletePrincipal(principalId: string): Promise<void>;
50
+ }
51
+ export interface AuthClientOptions {
52
+ /** Auth GraphQL endpoint, e.g. `http://auth.localhost:3000/graphql`. */
53
+ endpoint: string;
54
+ /** Bearer token for calls that need an authenticated caller. */
55
+ token?: string;
56
+ }
57
+ export type AuthClientFactory = (options: AuthClientOptions) => AuthClient;
58
+ export declare const explainFailure: (message: string, endpoint: string) => string;
59
+ /**
60
+ * Which factor a message is asking for, or null. Exported because a step-up
61
+ * error arrives at a UI as plain text once it has crossed a process boundary,
62
+ * and the server's own code is the only trustworthy thing to key off.
63
+ *
64
+ * The bare `STEP_UP_REQUIRED` raised by the generated guard means the session
65
+ * has no recent password verification, so it asks for a password.
66
+ */
67
+ export declare const stepUpKind: (message: string) => StepUpKind | null;
68
+ /**
69
+ * Whether the server rejected a *field*, rather than the request.
70
+ *
71
+ * The published SDK's types are generated from one schema and an auth plane may
72
+ * be running an older one, so a field the types promise can still be absent —
73
+ * something no amount of type-checking on this side can catch.
74
+ */
75
+ export declare const missingField: (message: string) => boolean;
76
+ /** The real client: `@constructive-io/sdk`'s generated auth ORM. */
77
+ export declare const sdkAuthClient: AuthClientFactory;
package/client.js ADDED
@@ -0,0 +1,381 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.sdkAuthClient = exports.missingField = exports.stepUpKind = exports.explainFailure = exports.StepUpRequiredError = exports.AuthError = void 0;
4
+ const sdk_1 = require("@constructive-io/sdk");
5
+ const endpoint_1 = require("./endpoint");
6
+ /** Raised when the auth server refuses a call, with the server's own wording. */
7
+ class AuthError extends Error {
8
+ operation;
9
+ constructor(operation, message) {
10
+ super(message);
11
+ this.operation = operation;
12
+ this.name = 'AuthError';
13
+ }
14
+ }
15
+ exports.AuthError = AuthError;
16
+ /**
17
+ * The session is authenticated but not *recently* verified. Recoverable: prove
18
+ * the factor, then run the very same request again.
19
+ */
20
+ class StepUpRequiredError extends AuthError {
21
+ kind;
22
+ constructor(operation, kind, message) {
23
+ super(operation, message);
24
+ this.kind = kind;
25
+ this.name = 'StepUpRequiredError';
26
+ }
27
+ }
28
+ exports.StepUpRequiredError = StepUpRequiredError;
29
+ const SESSION_SELECT = {
30
+ select: {
31
+ result: {
32
+ select: { userId: true, accessToken: true, accessTokenExpiresAt: true },
33
+ },
34
+ },
35
+ };
36
+ const readSession = (operation, payload) => {
37
+ if (!payload?.userId || !payload.accessToken) {
38
+ throw new AuthError(operation, 'the server returned no session');
39
+ }
40
+ return {
41
+ userId: payload.userId,
42
+ accessToken: payload.accessToken,
43
+ accessTokenExpiresAt: payload.accessTokenExpiresAt ?? null,
44
+ };
45
+ };
46
+ /**
47
+ * An auth plane old enough to still keep `allowed_mask` on `principals` derives
48
+ * the mask from `bit_length(permissions)` in the general permission table, and
49
+ * inserts NULL when that lookup finds nothing — so the constraint, not the
50
+ * lookup, is what fails, and the raw message names a column the caller never
51
+ * sent. Later schemas moved the mask onto `principal_scope_overrides`, where
52
+ * absent means "inherits", and the personal path simply works.
53
+ */
54
+ const PERSONAL_MASK = /null value in column "allowed_mask" of relation "principals"/i;
55
+ const explainFailure = (message, endpoint) => {
56
+ if (PERSONAL_MASK.test(message)) {
57
+ return ('this auth plane cannot create a personal principal: it still stores a ' +
58
+ 'permission mask on the principal itself and found no permission row to ' +
59
+ 'size it from — scope the principal to an organization instead, or ' +
60
+ 'update the auth plane');
61
+ }
62
+ // a 404 means the URL is not a GraphQL route at all, which is by far the
63
+ // most common way to get this wrong — say so instead of passing on `HTTP 404`
64
+ if (!/\b404\b/.test(message))
65
+ return message;
66
+ const suffix = endpoint.endsWith('/graphql')
67
+ ? 'check the host and that the auth plane is running'
68
+ : `try ${endpoint.replace(/\/$/, '')}/graphql`;
69
+ return `no GraphQL endpoint at ${endpoint} — ${suffix}`;
70
+ };
71
+ exports.explainFailure = explainFailure;
72
+ const STEP_UP = /STEP_UP_REQUIRED(?:_(PASSWORD|MFA|FRESH_AUTH))?/;
73
+ /**
74
+ * Which factor a message is asking for, or null. Exported because a step-up
75
+ * error arrives at a UI as plain text once it has crossed a process boundary,
76
+ * and the server's own code is the only trustworthy thing to key off.
77
+ *
78
+ * The bare `STEP_UP_REQUIRED` raised by the generated guard means the session
79
+ * has no recent password verification, so it asks for a password.
80
+ */
81
+ const stepUpKind = (message) => {
82
+ const found = STEP_UP.exec(message);
83
+ if (!found)
84
+ return null;
85
+ return found[1]?.toLowerCase() ?? 'password';
86
+ };
87
+ exports.stepUpKind = stepUpKind;
88
+ /**
89
+ * The server's defaults are the permissive ones: a principal inherits its
90
+ * owner unless a row says otherwise, so a missing flag reads as "inherits".
91
+ */
92
+ const readPrincipal = (node) => ({
93
+ principalId: node.id,
94
+ name: node.name ?? '',
95
+ ownerId: node.ownerId ?? null,
96
+ isReadOnly: node.isReadOnly ?? false,
97
+ bypassStepUp: node.bypassStepUp ?? false,
98
+ useAdminOwner: node.useAdminOwner ?? true,
99
+ entityIds: (node.principalEntities?.nodes ?? [])
100
+ .map((entity) => entity.entityId)
101
+ .filter((id) => Boolean(id)),
102
+ scopes: (node.principalScopeOverrides?.nodes ?? []).map((scope) => ({
103
+ membershipType: scope.membershipType ?? 0,
104
+ allowedMask: scope.allowedMask ?? null,
105
+ isActive: scope.isActive ?? true,
106
+ isReadOnly: scope.isReadOnly ?? false,
107
+ useAdminOwner: scope.useAdminOwner ?? true,
108
+ })),
109
+ });
110
+ /**
111
+ * Whether the server rejected a *field*, rather than the request.
112
+ *
113
+ * The published SDK's types are generated from one schema and an auth plane may
114
+ * be running an older one, so a field the types promise can still be absent —
115
+ * something no amount of type-checking on this side can catch.
116
+ */
117
+ const missingField = (message) => /Cannot query field/i.test(message);
118
+ exports.missingField = missingField;
119
+ /**
120
+ * Everything a principal can tell us. Optimistic on purpose: ask for the whole
121
+ * picture, and fall back only when a particular server cannot supply it.
122
+ */
123
+ const PRINCIPAL_SELECT = {
124
+ id: true,
125
+ name: true,
126
+ ownerId: true,
127
+ isReadOnly: true,
128
+ bypassStepUp: true,
129
+ useAdminOwner: true,
130
+ principalEntities: { select: { entityId: true }, first: 100 },
131
+ principalScopeOverrides: {
132
+ select: {
133
+ membershipType: true,
134
+ allowedMask: true,
135
+ isActive: true,
136
+ isReadOnly: true,
137
+ useAdminOwner: true,
138
+ },
139
+ first: 100,
140
+ },
141
+ };
142
+ /**
143
+ * The fields every vintage of the auth schema has. Dropping the rest costs
144
+ * detail, never correctness: an unread flag reads as inherited, which is what
145
+ * the server means by its absence anyway.
146
+ */
147
+ const PRINCIPAL_SELECT_CORE = {
148
+ id: true,
149
+ name: true,
150
+ ownerId: true,
151
+ isReadOnly: true,
152
+ bypassStepUp: true,
153
+ principalEntities: { select: { entityId: true }, first: 100 },
154
+ principalScopeOverrides: {
155
+ select: { membershipType: true, allowedMask: true, isReadOnly: true },
156
+ first: 100,
157
+ },
158
+ };
159
+ /**
160
+ * A principal scoped to nothing but its owner — the personal CI identity.
161
+ *
162
+ * Sent by hand because the generated ORM has no `mutation.createPrincipal`: the
163
+ * codegen let the principals table's CRUD create shadow the procedure of the
164
+ * same inflected name, so the typed surface offers only the org variant. The
165
+ * auth schema itself does expose it, taking the flat input built here.
166
+ */
167
+ const createPersonalPrincipal = async (endpoint, token, input) => {
168
+ const adapter = new sdk_1.auth.FetchAdapter(endpoint, token ? { Authorization: `Bearer ${token}` } : undefined);
169
+ const result = await adapter.execute(`mutation CreatePrincipal($input: CreatePrincipalInput!) {
170
+ createPrincipal(input: $input) { result }
171
+ }`, { input });
172
+ if (!result.ok)
173
+ throw new Error(result.errors.map((e) => e.message).join('; '));
174
+ return result.data.createPrincipal?.result ?? null;
175
+ };
176
+ const rethrow = (operation, endpoint, error) => {
177
+ const message = error instanceof Error ? error.message : String(error);
178
+ const kind = (0, exports.stepUpKind)(message);
179
+ if (kind)
180
+ throw new StepUpRequiredError(operation, kind, message);
181
+ throw new AuthError(operation, (0, exports.explainFailure)(message, endpoint));
182
+ };
183
+ /** The real client: `@constructive-io/sdk`'s generated auth ORM. */
184
+ const sdkAuthClient = (options) => {
185
+ const endpoint = (0, endpoint_1.normalizeEndpoint)(options.endpoint);
186
+ const token = options.token;
187
+ const client = sdk_1.auth.createClient({
188
+ endpoint,
189
+ headers: token ? { Authorization: `Bearer ${token}` } : undefined,
190
+ });
191
+ return {
192
+ async signIn(input) {
193
+ try {
194
+ const data = await client.mutation
195
+ .signIn({
196
+ input: {
197
+ email: input.email,
198
+ password: input.password,
199
+ rememberMe: input.rememberMe ?? true,
200
+ },
201
+ }, SESSION_SELECT)
202
+ .unwrap();
203
+ return readSession('signIn', data.signIn?.result);
204
+ }
205
+ catch (error) {
206
+ if (error instanceof AuthError)
207
+ throw error;
208
+ return rethrow('signIn', endpoint, error);
209
+ }
210
+ },
211
+ async signUp(input) {
212
+ try {
213
+ const data = await client.mutation
214
+ .signUp({ input: { email: input.email, password: input.password } }, SESSION_SELECT)
215
+ .unwrap();
216
+ return readSession('signUp', data.signUp?.result);
217
+ }
218
+ catch (error) {
219
+ if (error instanceof AuthError)
220
+ throw error;
221
+ return rethrow('signUp', endpoint, error);
222
+ }
223
+ },
224
+ async signOut() {
225
+ try {
226
+ await client.mutation
227
+ .signOut({ input: {} }, { select: { clientMutationId: true } })
228
+ .unwrap();
229
+ }
230
+ catch (error) {
231
+ rethrow('signOut', endpoint, error);
232
+ }
233
+ },
234
+ async createApiKey(options) {
235
+ const input = {
236
+ keyName: options.name,
237
+ expiresIn: options.expiresIn,
238
+ accessLevel: options.accessLevel,
239
+ principalId: options.principalId,
240
+ };
241
+ const select = {
242
+ select: {
243
+ result: { select: { apiKey: true, keyId: true, expiresAt: true } },
244
+ },
245
+ };
246
+ try {
247
+ const result = options.orgId
248
+ ? (await client.mutation
249
+ .createOrgApiKey({ input: { ...input, orgId: options.orgId } }, select)
250
+ .unwrap()).createOrgApiKey?.result
251
+ : (await client.mutation.createApiKey({ input }, select).unwrap())
252
+ .createApiKey?.result;
253
+ if (!result?.apiKey || !result.keyId) {
254
+ throw new AuthError('createApiKey', 'the server returned no key');
255
+ }
256
+ return {
257
+ apiKey: result.apiKey,
258
+ keyId: result.keyId,
259
+ expiresAt: result.expiresAt ?? null,
260
+ };
261
+ }
262
+ catch (error) {
263
+ if (error instanceof AuthError)
264
+ throw error;
265
+ return rethrow('createApiKey', endpoint, error);
266
+ }
267
+ },
268
+ async listPrincipals() {
269
+ const read = async (select) => {
270
+ const data = await client.principal.findMany({ first: 200, select }).unwrap();
271
+ return data.principals.nodes.map(readPrincipal);
272
+ };
273
+ try {
274
+ return await read(PRINCIPAL_SELECT);
275
+ }
276
+ catch (error) {
277
+ if (error instanceof AuthError)
278
+ throw error;
279
+ if (!(0, exports.missingField)(error instanceof Error ? error.message : String(error))) {
280
+ return rethrow('listPrincipals', endpoint, error);
281
+ }
282
+ try {
283
+ return await read(PRINCIPAL_SELECT_CORE);
284
+ }
285
+ catch (retried) {
286
+ if (retried instanceof AuthError)
287
+ throw retried;
288
+ return rethrow('listPrincipals', endpoint, retried);
289
+ }
290
+ }
291
+ },
292
+ async createPrincipal(options) {
293
+ const flags = {
294
+ isReadOnly: options.isReadOnly,
295
+ bypassStepUp: options.bypassStepUp,
296
+ // omitted rather than sent as null, so a server that predates
297
+ // the field is not asked about it at all
298
+ ...(options.useAdminOwner === undefined
299
+ ? {}
300
+ : { useAdminOwner: options.useAdminOwner }),
301
+ };
302
+ try {
303
+ const principalId = options.orgId
304
+ ? (await client.mutation
305
+ .createOrgPrincipal({ input: { name: options.name, orgId: options.orgId, ...flags } }, { select: { result: true } })
306
+ .unwrap()).createOrgPrincipal?.result
307
+ : await createPersonalPrincipal(endpoint, token, {
308
+ name: options.name,
309
+ ...flags,
310
+ });
311
+ if (!principalId) {
312
+ throw new AuthError('createPrincipal', 'the server returned no principal');
313
+ }
314
+ return principalId;
315
+ }
316
+ catch (error) {
317
+ if (error instanceof AuthError)
318
+ throw error;
319
+ return rethrow('createPrincipal', endpoint, error);
320
+ }
321
+ },
322
+ async deletePrincipal(principalId) {
323
+ try {
324
+ await client.mutation
325
+ .deletePrincipal({ input: { principalId } }, { select: { clientMutationId: true } })
326
+ .unwrap();
327
+ }
328
+ catch (error) {
329
+ if (error instanceof AuthError)
330
+ throw error;
331
+ rethrow('deletePrincipal', endpoint, error);
332
+ }
333
+ },
334
+ async verifyPassword(password) {
335
+ try {
336
+ const data = await client.mutation
337
+ .verifyPassword({ input: { password } }, { select: { result: true } })
338
+ .unwrap();
339
+ if (data.verifyPassword?.result !== true) {
340
+ throw new AuthError('verifyPassword', 'the password was not accepted');
341
+ }
342
+ }
343
+ catch (error) {
344
+ if (error instanceof AuthError)
345
+ throw error;
346
+ rethrow('verifyPassword', endpoint, error);
347
+ }
348
+ },
349
+ async verifyTotp(code) {
350
+ try {
351
+ const data = await client.mutation
352
+ .verifyTotp({ input: { totpValue: code } }, { select: { result: true } })
353
+ .unwrap();
354
+ if (data.verifyTotp?.result !== true) {
355
+ throw new AuthError('verifyTotp', 'the code was not accepted');
356
+ }
357
+ }
358
+ catch (error) {
359
+ if (error instanceof AuthError)
360
+ throw error;
361
+ rethrow('verifyTotp', endpoint, error);
362
+ }
363
+ },
364
+ async revokeApiKey(keyId) {
365
+ try {
366
+ const data = await client.mutation
367
+ .revokeApiKey({ input: { keyId } }, { select: { result: true } })
368
+ .unwrap();
369
+ if (data.revokeApiKey?.result !== true) {
370
+ throw new AuthError('revokeApiKey', `the server did not revoke ${keyId}`);
371
+ }
372
+ }
373
+ catch (error) {
374
+ if (error instanceof AuthError)
375
+ throw error;
376
+ rethrow('revokeApiKey', endpoint, error);
377
+ }
378
+ },
379
+ };
380
+ };
381
+ exports.sdkAuthClient = sdkAuthClient;