@lostgradient/api-key-settings 0.0.0-stage → 0.1.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/LICENSE +21 -0
- package/README.md +16 -2
- package/dist/ApiKeySettings.svelte +235 -0
- package/dist/ApiKeySettings.svelte.d.ts +3 -0
- package/dist/backchannel.d.ts +61 -0
- package/dist/backchannel.js +239 -0
- package/dist/generated/api-keys-operations.generated.d.ts +57 -0
- package/dist/generated/api-keys-operations.generated.js +2 -0
- package/dist/generated/operation-client.generated.d.ts +2 -0
- package/dist/generated/operation-client.generated.js +1 -0
- package/dist/generated/operation-client.svelte.d.ts +83 -0
- package/dist/generated/operation-client.svelte.js +17 -0
- package/dist/svelte.d.ts +1 -0
- package/dist/svelte.js +1 -0
- package/package.json +45 -3
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2024–2026 Steve Kinney
|
|
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,17 @@
|
|
|
1
|
-
#
|
|
1
|
+
# API key settings
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
`@lostgradient/api-key-settings/backchannel` exposes API key management operations and a Fetch handler. Supply the existing Credentials API key service, a session authenticator, current manager and target policy, row actions, an overlap cutoff, a public origin, and a browser write guard. Policies must use current authority for each invocation; service credentials are not management actors.
|
|
4
|
+
|
|
5
|
+
Mount the handler at `/key-admin/jsonrpc`. Its responses are private and non-cacheable. If composing the operations into another catalog, the host must apply the same session admission, origin and write-guard checks and response cache policy.
|
|
6
|
+
|
|
7
|
+
For an explicitly trusted local operator without an `Origin` header, supply `guardTrustedOperatorWrite` to verify that operator at the request boundary. The handler never infers that trust from a loopback address.
|
|
8
|
+
|
|
9
|
+
`@lostgradient/api-key-settings/svelte` exports the scoped provider and generated read and command bindings. Keep the provider mounted across route changes, and supply a distinct scope whenever the actor, workspace, or membership authority changes. The optional `@lostgradient/api-key-settings/ui` entry renders the standard page and requires Cinder; headless bindings do not import it. Issue and rotate return secrets only to the submitting caller. Copy the secret before dismissing it.
|
|
10
|
+
|
|
11
|
+
Commands are never replayed automatically. If a response is lost, the outcome is uncertain; the page reads metadata once so the operator can reconcile before another attempt.
|
|
12
|
+
|
|
13
|
+
## Installation
|
|
14
|
+
|
|
15
|
+
```sh
|
|
16
|
+
npm install @lostgradient/api-key-settings
|
|
17
|
+
```
|
|
@@ -0,0 +1,235 @@
|
|
|
1
|
+
<script lang="ts">
|
|
2
|
+
import { activateResource } from '@lostgradient/backchannel-svelte';
|
|
3
|
+
import { Button, Checkbox, ConfirmDialog, DatePicker, Input, Select } from '@lostgradient/cinder';
|
|
4
|
+
import { onDestroy } from 'svelte';
|
|
5
|
+
import {
|
|
6
|
+
getApiKeySettingsHost,
|
|
7
|
+
useApiKeysIssue,
|
|
8
|
+
useApiKeysList,
|
|
9
|
+
useApiKeysRevoke,
|
|
10
|
+
useApiKeysRotate,
|
|
11
|
+
} from "./svelte.js";
|
|
12
|
+
|
|
13
|
+
let { showHeading = true }: { showHeading?: boolean } = $props();
|
|
14
|
+
|
|
15
|
+
const host = getApiKeySettingsHost();
|
|
16
|
+
const list = useApiKeysList(host, () => ({}));
|
|
17
|
+
const issue = useApiKeysIssue(host);
|
|
18
|
+
const rotate = useApiKeysRotate(host);
|
|
19
|
+
const revoke = useApiKeysRevoke(host);
|
|
20
|
+
let label = $state('');
|
|
21
|
+
let subject = $state('');
|
|
22
|
+
let scopes = $state<string[]>([]);
|
|
23
|
+
let expiresAt = $state<string | undefined>();
|
|
24
|
+
const available = $derived(
|
|
25
|
+
list.data?.targets.find((target) => target.subject === subject)?.scopes ?? [],
|
|
26
|
+
);
|
|
27
|
+
let secret = $state<string | undefined>();
|
|
28
|
+
let secretPending = $state(false);
|
|
29
|
+
let revokeTarget = $state<{ id: string; label: string } | undefined>();
|
|
30
|
+
let revoking = false;
|
|
31
|
+
let message = $state('');
|
|
32
|
+
let destroyed = false;
|
|
33
|
+
onDestroy(() => {
|
|
34
|
+
destroyed = true;
|
|
35
|
+
secret = undefined;
|
|
36
|
+
});
|
|
37
|
+
|
|
38
|
+
async function submit() {
|
|
39
|
+
if (secretPending || secret !== undefined || !subject) return;
|
|
40
|
+
secretPending = true;
|
|
41
|
+
message = '';
|
|
42
|
+
try {
|
|
43
|
+
const result = await issue.mutateAsync({
|
|
44
|
+
label,
|
|
45
|
+
subject,
|
|
46
|
+
scopes,
|
|
47
|
+
...(expiresAt ? { expiresAt: new Date(expiresAt).getTime() } : {}),
|
|
48
|
+
});
|
|
49
|
+
if (!destroyed && !host.disposed) secret = result.secret;
|
|
50
|
+
} catch {
|
|
51
|
+
if (!destroyed && !host.disposed) {
|
|
52
|
+
message = 'The outcome is uncertain. Check the refreshed list before trying again.';
|
|
53
|
+
const metadata = await issue.reconcile('api.keys.list', {}).catch(() => undefined);
|
|
54
|
+
if (metadata !== undefined && !host.disposed)
|
|
55
|
+
host.cache.setQueryData(host.key('api.keys.list', {}), metadata);
|
|
56
|
+
}
|
|
57
|
+
} finally {
|
|
58
|
+
secretPending = false;
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
async function rotateKey(id: string) {
|
|
62
|
+
if (secretPending || secret !== undefined) return;
|
|
63
|
+
secretPending = true;
|
|
64
|
+
message = '';
|
|
65
|
+
try {
|
|
66
|
+
const result = await rotate.mutateAsync({ id });
|
|
67
|
+
if (!destroyed && !host.disposed) {
|
|
68
|
+
secret = result.secret;
|
|
69
|
+
message = `The old key expires at ${new Date(result.retiresAt).toLocaleString()}.`;
|
|
70
|
+
}
|
|
71
|
+
} catch {
|
|
72
|
+
if (!destroyed && !host.disposed) {
|
|
73
|
+
message = 'The outcome is uncertain. Check the refreshed list before trying again.';
|
|
74
|
+
const metadata = await rotate.reconcile('api.keys.list', {}).catch(() => undefined);
|
|
75
|
+
if (metadata !== undefined && !host.disposed)
|
|
76
|
+
host.cache.setQueryData(host.key('api.keys.list', {}), metadata);
|
|
77
|
+
}
|
|
78
|
+
} finally {
|
|
79
|
+
secretPending = false;
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
async function revokeKey(id: string) {
|
|
83
|
+
if (revoking) return;
|
|
84
|
+
revoking = true;
|
|
85
|
+
message = '';
|
|
86
|
+
try {
|
|
87
|
+
await revoke.mutateAsync({ id });
|
|
88
|
+
} catch {
|
|
89
|
+
if (!destroyed && !host.disposed) {
|
|
90
|
+
message = 'The outcome is uncertain. Check the refreshed list before trying again.';
|
|
91
|
+
const metadata = await revoke.reconcile('api.keys.list', {}).catch(() => undefined);
|
|
92
|
+
if (metadata !== undefined && !host.disposed)
|
|
93
|
+
host.cache.setQueryData(host.key('api.keys.list', {}), metadata);
|
|
94
|
+
}
|
|
95
|
+
} finally {
|
|
96
|
+
revoking = false;
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
</script>
|
|
100
|
+
|
|
101
|
+
<section class="api-key-settings" {@attach activateResource(list)}>
|
|
102
|
+
{#if showHeading}<h1>API keys</h1>{/if}
|
|
103
|
+
{#if message}<p role="status">{message}</p>{/if}
|
|
104
|
+
{#if secret}
|
|
105
|
+
<section class="key-secret" aria-label="New API key">
|
|
106
|
+
<p>Copy this secret now. It will not be shown again.</p>
|
|
107
|
+
<code>{secret}</code>
|
|
108
|
+
<Button
|
|
109
|
+
onclick={() => {
|
|
110
|
+
secret = undefined;
|
|
111
|
+
}}>Dismiss</Button
|
|
112
|
+
>
|
|
113
|
+
</section>
|
|
114
|
+
{/if}
|
|
115
|
+
{#if list.initialError}<p>Unable to load API keys.</p>{/if}
|
|
116
|
+
{#if list.data}
|
|
117
|
+
<form
|
|
118
|
+
class="key-form"
|
|
119
|
+
onsubmit={(event) => {
|
|
120
|
+
event.preventDefault();
|
|
121
|
+
void submit();
|
|
122
|
+
}}
|
|
123
|
+
>
|
|
124
|
+
<Input id="api-key-label" label="Label" bind:value={label} required />
|
|
125
|
+
<Select
|
|
126
|
+
id="api-key-target"
|
|
127
|
+
label="Target"
|
|
128
|
+
placeholder="Choose a target"
|
|
129
|
+
bind:value={subject}
|
|
130
|
+
options={list.data.targets.map((target) => ({
|
|
131
|
+
value: target.subject,
|
|
132
|
+
label: target.subject,
|
|
133
|
+
}))}
|
|
134
|
+
onchange={() => {
|
|
135
|
+
scopes = [];
|
|
136
|
+
}}
|
|
137
|
+
required
|
|
138
|
+
/>
|
|
139
|
+
|
|
140
|
+
{#if available.length}
|
|
141
|
+
<fieldset>
|
|
142
|
+
<legend>Permissions</legend>
|
|
143
|
+
{#each available as scope (scope)}
|
|
144
|
+
<Checkbox
|
|
145
|
+
label={scope}
|
|
146
|
+
checked={scopes.includes(scope)}
|
|
147
|
+
onValueChange={(checked) => {
|
|
148
|
+
scopes = checked ? [...scopes, scope] : scopes.filter((entry) => entry !== scope);
|
|
149
|
+
}}
|
|
150
|
+
/>
|
|
151
|
+
{/each}
|
|
152
|
+
</fieldset>
|
|
153
|
+
{/if}
|
|
154
|
+
<DatePicker
|
|
155
|
+
id="api-key-expires-at"
|
|
156
|
+
label="Expires at"
|
|
157
|
+
granularity="minute"
|
|
158
|
+
bind:value={expiresAt}
|
|
159
|
+
/>
|
|
160
|
+
<Button type="submit" disabled={secretPending || secret !== undefined}>Issue key</Button>
|
|
161
|
+
</form>
|
|
162
|
+
<ul class="key-list">
|
|
163
|
+
{#each list.data.keys as key (key.id)}
|
|
164
|
+
<li>
|
|
165
|
+
{key.label} ({key.subject}) <code>{key.id}</code>
|
|
166
|
+
{#if key.actions.includes('rotate')}<Button
|
|
167
|
+
disabled={secretPending || secret !== undefined}
|
|
168
|
+
onclick={() => void rotateKey(key.id)}>Rotate</Button
|
|
169
|
+
>{/if}
|
|
170
|
+
{#if key.actions.includes('revoke')}<Button
|
|
171
|
+
onclick={() => {
|
|
172
|
+
revokeTarget = { id: key.id, label: key.label };
|
|
173
|
+
}}>Revoke</Button
|
|
174
|
+
>{/if}
|
|
175
|
+
</li>
|
|
176
|
+
{/each}
|
|
177
|
+
</ul>
|
|
178
|
+
{/if}
|
|
179
|
+
<ConfirmDialog
|
|
180
|
+
open={revokeTarget !== undefined}
|
|
181
|
+
title={`Revoke ${revokeTarget?.label ?? ''}`}
|
|
182
|
+
description="This key will no longer authenticate requests."
|
|
183
|
+
confirmLabel="Revoke key"
|
|
184
|
+
destructive
|
|
185
|
+
onCancel={() => {
|
|
186
|
+
revokeTarget = undefined;
|
|
187
|
+
}}
|
|
188
|
+
onConfirm={() => {
|
|
189
|
+
const target = revokeTarget;
|
|
190
|
+
revokeTarget = undefined;
|
|
191
|
+
if (target) void revokeKey(target.id);
|
|
192
|
+
}}
|
|
193
|
+
/>
|
|
194
|
+
</section>
|
|
195
|
+
|
|
196
|
+
<style>
|
|
197
|
+
.api-key-settings,
|
|
198
|
+
.key-form,
|
|
199
|
+
.key-secret {
|
|
200
|
+
display: grid;
|
|
201
|
+
gap: var(--cinder-space-4);
|
|
202
|
+
max-inline-size: 32rem;
|
|
203
|
+
min-inline-size: 0;
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
.key-form :global(.cinder-button),
|
|
207
|
+
.key-secret :global(.cinder-button) {
|
|
208
|
+
justify-self: start;
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
fieldset {
|
|
212
|
+
display: grid;
|
|
213
|
+
gap: var(--cinder-space-2);
|
|
214
|
+
margin: 0;
|
|
215
|
+
padding: 0;
|
|
216
|
+
border: 0;
|
|
217
|
+
min-inline-size: 0;
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
legend {
|
|
221
|
+
margin-block-end: var(--cinder-space-2);
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
.key-list {
|
|
225
|
+
display: grid;
|
|
226
|
+
gap: var(--cinder-space-3);
|
|
227
|
+
margin: 0;
|
|
228
|
+
padding: 0;
|
|
229
|
+
list-style: none;
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
code {
|
|
233
|
+
overflow-wrap: anywhere;
|
|
234
|
+
}
|
|
235
|
+
</style>
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
import { type OperationHandlerAuthenticate, type Principal } from '@lostgradient/backchannel';
|
|
2
|
+
import type { ApiKeyMetadata, createApiKeys } from '@lostgradient/credentials/api-keys';
|
|
3
|
+
import { z } from 'zod';
|
|
4
|
+
type KeyService = ReturnType<typeof createApiKeys<Principal>>;
|
|
5
|
+
type Target = {
|
|
6
|
+
subject: string;
|
|
7
|
+
scopes: string[];
|
|
8
|
+
};
|
|
9
|
+
/** Host policy is consulted again for every request, including each command. */
|
|
10
|
+
export type ApiKeyManagementHost = {
|
|
11
|
+
keys: KeyService;
|
|
12
|
+
currentManager: (principal: Principal) => Promise<boolean>;
|
|
13
|
+
targets: (principal: Principal) => Promise<Target[]>;
|
|
14
|
+
allowedActions: (principal: Principal, key: ApiKeyMetadata) => Promise<('rotate' | 'revoke')[]>;
|
|
15
|
+
overlapCutoff: () => number;
|
|
16
|
+
};
|
|
17
|
+
export declare const apiKeyManagementOperations: readonly [import("@lostgradient/backchannel").UnarySchemaOperationDefinition<z.ZodObject<{}, z.core.$strip>, z.ZodObject<{
|
|
18
|
+
keys: z.ZodArray<z.ZodObject<{
|
|
19
|
+
id: z.ZodString;
|
|
20
|
+
label: z.ZodString;
|
|
21
|
+
workspaceId: z.ZodString;
|
|
22
|
+
subject: z.ZodString;
|
|
23
|
+
scopes: z.ZodArray<z.ZodString>;
|
|
24
|
+
expiresAt: z.ZodOptional<z.ZodNumber>;
|
|
25
|
+
revokedAt: z.ZodOptional<z.ZodNumber>;
|
|
26
|
+
retiresAt: z.ZodOptional<z.ZodNumber>;
|
|
27
|
+
actions: z.ZodArray<z.ZodString>;
|
|
28
|
+
}, z.core.$strip>>;
|
|
29
|
+
targets: z.ZodArray<z.ZodObject<{
|
|
30
|
+
subject: z.ZodString;
|
|
31
|
+
scopes: z.ZodArray<z.ZodString>;
|
|
32
|
+
}, z.core.$strip>>;
|
|
33
|
+
}, z.core.$strip>, ApiKeyManagementHost>, import("@lostgradient/backchannel").UnarySchemaOperationDefinition<z.ZodObject<{
|
|
34
|
+
label: z.ZodString;
|
|
35
|
+
subject: z.ZodString;
|
|
36
|
+
scopes: z.ZodArray<z.ZodString>;
|
|
37
|
+
expiresAt: z.ZodOptional<z.ZodNumber>;
|
|
38
|
+
}, z.core.$strip>, z.ZodObject<{
|
|
39
|
+
id: z.ZodString;
|
|
40
|
+
secret: z.ZodString;
|
|
41
|
+
}, z.core.$strip>, ApiKeyManagementHost>, import("@lostgradient/backchannel").UnarySchemaOperationDefinition<z.ZodObject<{
|
|
42
|
+
id: z.ZodString;
|
|
43
|
+
}, z.core.$strip>, z.ZodObject<{
|
|
44
|
+
id: z.ZodString;
|
|
45
|
+
secret: z.ZodString;
|
|
46
|
+
retiresAt: z.ZodNumber;
|
|
47
|
+
}, z.core.$strip>, ApiKeyManagementHost>, import("@lostgradient/backchannel").UnarySchemaOperationDefinition<z.ZodObject<{
|
|
48
|
+
id: z.ZodString;
|
|
49
|
+
}, z.core.$strip>, z.ZodObject<{
|
|
50
|
+
id: z.ZodString;
|
|
51
|
+
revoked: z.ZodBoolean;
|
|
52
|
+
}, z.core.$strip>, ApiKeyManagementHost>];
|
|
53
|
+
/** Serve the management catalog behind a session authenticator and browser write guard. */
|
|
54
|
+
export declare function createApiKeyManagementHandler(options: {
|
|
55
|
+
host: ApiKeyManagementHost;
|
|
56
|
+
authenticateSession: OperationHandlerAuthenticate;
|
|
57
|
+
publicOrigin: string;
|
|
58
|
+
guardWrite: (request: Request) => Promise<boolean>;
|
|
59
|
+
guardTrustedOperatorWrite?: (request: Request) => Promise<boolean>;
|
|
60
|
+
}): (request: Request) => Promise<Response>;
|
|
61
|
+
export {};
|
|
@@ -0,0 +1,239 @@
|
|
|
1
|
+
import { createOperationHandler, defineOperation, } from '@lostgradient/backchannel';
|
|
2
|
+
import { readRestBodyBounded } from '@lostgradient/backchannel/internals';
|
|
3
|
+
import { z } from 'zod';
|
|
4
|
+
const keyMetadata = z.object({
|
|
5
|
+
id: z.string(),
|
|
6
|
+
label: z.string(),
|
|
7
|
+
workspaceId: z.string(),
|
|
8
|
+
subject: z.string(),
|
|
9
|
+
scopes: z.array(z.string()),
|
|
10
|
+
expiresAt: z.number().optional(),
|
|
11
|
+
revokedAt: z.number().optional(),
|
|
12
|
+
retiresAt: z.number().optional(),
|
|
13
|
+
});
|
|
14
|
+
const empty = z.object({});
|
|
15
|
+
const idInput = z.object({ id: z.string().min(1) });
|
|
16
|
+
const issueInput = z.object({
|
|
17
|
+
label: z.string().min(1),
|
|
18
|
+
subject: z.string().min(1),
|
|
19
|
+
scopes: z.array(z.string().min(1)),
|
|
20
|
+
expiresAt: z.number().optional(),
|
|
21
|
+
});
|
|
22
|
+
const issueOutput = z.object({ id: z.string(), secret: z.string() });
|
|
23
|
+
const rotateOutput = issueOutput.extend({ retiresAt: z.number() });
|
|
24
|
+
const revokeOutput = z.object({ id: z.string(), revoked: z.boolean() });
|
|
25
|
+
const common = {
|
|
26
|
+
mcpExposable: false,
|
|
27
|
+
tags: ['API keys'],
|
|
28
|
+
access: { kind: 'authenticated' },
|
|
29
|
+
transports: { http: false, jsonRpcHttp: true, jsonRpcWebSocket: false, jsonRpcStdio: false },
|
|
30
|
+
unknownKeyPolicy: { http: 'reject', jsonRpc: 'reject' },
|
|
31
|
+
};
|
|
32
|
+
async function admitted(principal, host) {
|
|
33
|
+
return (principal.method !== 'unauthenticated' &&
|
|
34
|
+
principal.method !== 'api-key' &&
|
|
35
|
+
principal.workspace !== undefined &&
|
|
36
|
+
principal.workspace.actorKind !== 'service' &&
|
|
37
|
+
principal.workspace.capabilities.includes('workspace:use') &&
|
|
38
|
+
principal.workspace.capabilities.includes('workspace:manage') &&
|
|
39
|
+
(await host.currentManager(principal)));
|
|
40
|
+
}
|
|
41
|
+
async function authority(principal, host) {
|
|
42
|
+
const workspaceId = principal.method === 'unauthenticated' ? undefined : principal.workspace?.workspaceId;
|
|
43
|
+
if (!workspaceId || !(await admitted(principal, host)))
|
|
44
|
+
throw new Error('Forbidden');
|
|
45
|
+
return { workspaceId, targets: await host.targets(principal) };
|
|
46
|
+
}
|
|
47
|
+
async function visible(principal, host) {
|
|
48
|
+
const context = await authority(principal, host);
|
|
49
|
+
const entries = await Promise.all(context.targets.map(async ({ subject }) => host.keys.list(principal, { workspaceId: context.workspaceId, subject })));
|
|
50
|
+
return { ...context, keys: entries.flat() };
|
|
51
|
+
}
|
|
52
|
+
async function findKey(principal, host, id) {
|
|
53
|
+
const context = await visible(principal, host);
|
|
54
|
+
const key = context.keys.find((entry) => entry.id === id);
|
|
55
|
+
if (!key)
|
|
56
|
+
throw new Error('Credential unavailable');
|
|
57
|
+
return { ...context, key };
|
|
58
|
+
}
|
|
59
|
+
const authorize = async ({ principal, host, }) => (await admitted(principal, host))
|
|
60
|
+
? { allowed: true }
|
|
61
|
+
: { allowed: false, classification: 'forbidden', reason: 'Forbidden' };
|
|
62
|
+
const listOutput = z.object({
|
|
63
|
+
keys: z.array(keyMetadata.extend({ actions: z.array(z.string()) })),
|
|
64
|
+
targets: z.array(z.object({ subject: z.string(), scopes: z.array(z.string()) })),
|
|
65
|
+
});
|
|
66
|
+
const list = defineOperation({
|
|
67
|
+
...common,
|
|
68
|
+
name: 'api.keys.list',
|
|
69
|
+
summary: 'List API keys',
|
|
70
|
+
destructive: false,
|
|
71
|
+
inputSchema: empty,
|
|
72
|
+
outputSchema: listOutput,
|
|
73
|
+
behavior: { kind: 'read' },
|
|
74
|
+
authorize,
|
|
75
|
+
invoke: async ({ principal, host }) => {
|
|
76
|
+
const result = await visible(principal, host);
|
|
77
|
+
return {
|
|
78
|
+
keys: await Promise.all(result.keys.map(async (key) => ({
|
|
79
|
+
...key,
|
|
80
|
+
actions: await host.allowedActions(principal, key),
|
|
81
|
+
}))),
|
|
82
|
+
targets: result.targets,
|
|
83
|
+
};
|
|
84
|
+
},
|
|
85
|
+
});
|
|
86
|
+
const issue = defineOperation({
|
|
87
|
+
...common,
|
|
88
|
+
name: 'api.keys.issue',
|
|
89
|
+
summary: 'Issue an API key',
|
|
90
|
+
destructive: true,
|
|
91
|
+
inputSchema: issueInput,
|
|
92
|
+
outputSchema: issueOutput,
|
|
93
|
+
behavior: { kind: 'command', responseDisposition: 'one-time', invalidates: ['api.keys.list'] },
|
|
94
|
+
authorize,
|
|
95
|
+
invoke: async ({ input, principal, host }) => {
|
|
96
|
+
const { label, subject, expiresAt } = input;
|
|
97
|
+
const scopes = [...input.scopes];
|
|
98
|
+
const context = await authority(principal, host);
|
|
99
|
+
const target = context.targets.find((entry) => entry.subject === subject);
|
|
100
|
+
if (!target || scopes.some((scope) => !target.scopes.includes(scope)))
|
|
101
|
+
throw new Error('Forbidden');
|
|
102
|
+
const result = await host.keys.issue(principal, {
|
|
103
|
+
label,
|
|
104
|
+
subject,
|
|
105
|
+
scopes,
|
|
106
|
+
workspaceId: context.workspaceId,
|
|
107
|
+
...(expiresAt === undefined ? {} : { expiresAt }),
|
|
108
|
+
});
|
|
109
|
+
return { id: result.id, secret: result.secret };
|
|
110
|
+
},
|
|
111
|
+
});
|
|
112
|
+
const rotate = defineOperation({
|
|
113
|
+
...common,
|
|
114
|
+
name: 'api.keys.rotate',
|
|
115
|
+
summary: 'Rotate an API key',
|
|
116
|
+
destructive: true,
|
|
117
|
+
inputSchema: idInput,
|
|
118
|
+
outputSchema: rotateOutput,
|
|
119
|
+
behavior: { kind: 'command', responseDisposition: 'one-time', invalidates: ['api.keys.list'] },
|
|
120
|
+
authorize,
|
|
121
|
+
invoke: async ({ input, principal, host }) => {
|
|
122
|
+
const { id } = input;
|
|
123
|
+
const context = await findKey(principal, host, id);
|
|
124
|
+
const actions = await host.allowedActions(principal, context.key);
|
|
125
|
+
if (!actions.includes('rotate'))
|
|
126
|
+
throw new Error('Forbidden');
|
|
127
|
+
const retiresAt = host.overlapCutoff();
|
|
128
|
+
const result = await host.keys.rotate(principal, {
|
|
129
|
+
workspaceId: context.workspaceId,
|
|
130
|
+
subject: context.key.subject,
|
|
131
|
+
id,
|
|
132
|
+
retiresAt,
|
|
133
|
+
});
|
|
134
|
+
return { id: result.id, secret: result.secret, retiresAt };
|
|
135
|
+
},
|
|
136
|
+
});
|
|
137
|
+
const revoke = defineOperation({
|
|
138
|
+
...common,
|
|
139
|
+
name: 'api.keys.revoke',
|
|
140
|
+
summary: 'Revoke an API key',
|
|
141
|
+
destructive: true,
|
|
142
|
+
inputSchema: idInput,
|
|
143
|
+
outputSchema: revokeOutput,
|
|
144
|
+
behavior: { kind: 'command', invalidates: ['api.keys.list'] },
|
|
145
|
+
authorize,
|
|
146
|
+
invoke: async ({ input, principal, host }) => {
|
|
147
|
+
const { id } = input;
|
|
148
|
+
const context = await findKey(principal, host, id);
|
|
149
|
+
const actions = await host.allowedActions(principal, context.key);
|
|
150
|
+
if (!actions.includes('revoke'))
|
|
151
|
+
throw new Error('Forbidden');
|
|
152
|
+
await host.keys.revoke(principal, {
|
|
153
|
+
workspaceId: context.workspaceId,
|
|
154
|
+
subject: context.key.subject,
|
|
155
|
+
id,
|
|
156
|
+
});
|
|
157
|
+
return { id, revoked: true };
|
|
158
|
+
},
|
|
159
|
+
});
|
|
160
|
+
export const apiKeyManagementOperations = [list, issue, rotate, revoke];
|
|
161
|
+
/** Serve the management catalog behind a session authenticator and browser write guard. */
|
|
162
|
+
export function createApiKeyManagementHandler(options) {
|
|
163
|
+
const origin = new URL(options.publicOrigin).origin;
|
|
164
|
+
const handler = createOperationHandler({
|
|
165
|
+
operations: apiKeyManagementOperations,
|
|
166
|
+
host: options.host,
|
|
167
|
+
authenticate: options.authenticateSession,
|
|
168
|
+
publicPaths: [],
|
|
169
|
+
});
|
|
170
|
+
return async (request) => {
|
|
171
|
+
const url = new URL(request.url);
|
|
172
|
+
if (url.pathname !== '/key-admin/jsonrpc' || request.method !== 'POST')
|
|
173
|
+
return new Response('Not found', {
|
|
174
|
+
status: 404,
|
|
175
|
+
headers: { 'Cache-Control': 'private, no-store' },
|
|
176
|
+
});
|
|
177
|
+
let bytes;
|
|
178
|
+
try {
|
|
179
|
+
bytes = await readRestBodyBounded(request);
|
|
180
|
+
}
|
|
181
|
+
catch (error) {
|
|
182
|
+
const tooLarge = typeof error === 'object' &&
|
|
183
|
+
error !== null &&
|
|
184
|
+
Object.hasOwn(error, 'code') &&
|
|
185
|
+
error.code === 'PayloadTooLarge';
|
|
186
|
+
return new Response(tooLarge ? 'Payload Too Large' : 'Bad Request', {
|
|
187
|
+
status: tooLarge ? 413 : 400,
|
|
188
|
+
headers: { 'Cache-Control': 'private, no-store' },
|
|
189
|
+
});
|
|
190
|
+
}
|
|
191
|
+
const buffered = new Request(request, { method: 'POST', body: bytes.buffer });
|
|
192
|
+
let body;
|
|
193
|
+
try {
|
|
194
|
+
body = JSON.parse(new TextDecoder().decode(bytes));
|
|
195
|
+
}
|
|
196
|
+
catch {
|
|
197
|
+
body = undefined;
|
|
198
|
+
}
|
|
199
|
+
const calls = Array.isArray(body) ? body : [body];
|
|
200
|
+
const writes = calls.some((call) => typeof call === 'object' &&
|
|
201
|
+
call !== null &&
|
|
202
|
+
'method' in call &&
|
|
203
|
+
(call.method === 'api.keys.issue' ||
|
|
204
|
+
call.method === 'api.keys.rotate' ||
|
|
205
|
+
call.method === 'api.keys.revoke'));
|
|
206
|
+
if (writes) {
|
|
207
|
+
const requestOrigin = request.headers.get('origin');
|
|
208
|
+
let allowed = false;
|
|
209
|
+
try {
|
|
210
|
+
allowed =
|
|
211
|
+
requestOrigin === origin
|
|
212
|
+
? await options.guardWrite(buffered.clone())
|
|
213
|
+
: requestOrigin === null &&
|
|
214
|
+
options.guardTrustedOperatorWrite !== undefined &&
|
|
215
|
+
(await options.guardTrustedOperatorWrite(buffered.clone()));
|
|
216
|
+
}
|
|
217
|
+
catch {
|
|
218
|
+
return new Response('Write guard unavailable', {
|
|
219
|
+
status: 503,
|
|
220
|
+
headers: { 'Cache-Control': 'private, no-store' },
|
|
221
|
+
});
|
|
222
|
+
}
|
|
223
|
+
if (!allowed)
|
|
224
|
+
return new Response('Forbidden', {
|
|
225
|
+
status: 403,
|
|
226
|
+
headers: { 'Cache-Control': 'private, no-store' },
|
|
227
|
+
});
|
|
228
|
+
}
|
|
229
|
+
url.pathname = '/jsonrpc';
|
|
230
|
+
const response = await handler(new Request(url, buffered));
|
|
231
|
+
const headers = new Headers(response.headers);
|
|
232
|
+
headers.set('Cache-Control', 'private, no-store');
|
|
233
|
+
return new Response(response.body, {
|
|
234
|
+
status: response.status,
|
|
235
|
+
statusText: response.statusText,
|
|
236
|
+
headers,
|
|
237
|
+
});
|
|
238
|
+
};
|
|
239
|
+
}
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
export type APIKeysOperationTypes = {
|
|
2
|
+
'api.keys.issue': {
|
|
3
|
+
readonly input: {
|
|
4
|
+
readonly expiresAt?: number;
|
|
5
|
+
readonly label: string;
|
|
6
|
+
readonly scopes: ReadonlyArray<string>;
|
|
7
|
+
readonly subject: string;
|
|
8
|
+
};
|
|
9
|
+
readonly output: {
|
|
10
|
+
readonly id: string;
|
|
11
|
+
readonly secret: string;
|
|
12
|
+
};
|
|
13
|
+
readonly faults: never;
|
|
14
|
+
};
|
|
15
|
+
'api.keys.list': {
|
|
16
|
+
readonly input: {};
|
|
17
|
+
readonly output: {
|
|
18
|
+
readonly keys: ReadonlyArray<{
|
|
19
|
+
readonly actions: ReadonlyArray<string>;
|
|
20
|
+
readonly expiresAt?: number;
|
|
21
|
+
readonly id: string;
|
|
22
|
+
readonly label: string;
|
|
23
|
+
readonly retiresAt?: number;
|
|
24
|
+
readonly revokedAt?: number;
|
|
25
|
+
readonly scopes: ReadonlyArray<string>;
|
|
26
|
+
readonly subject: string;
|
|
27
|
+
readonly workspaceId: string;
|
|
28
|
+
}>;
|
|
29
|
+
readonly targets: ReadonlyArray<{
|
|
30
|
+
readonly scopes: ReadonlyArray<string>;
|
|
31
|
+
readonly subject: string;
|
|
32
|
+
}>;
|
|
33
|
+
};
|
|
34
|
+
readonly faults: never;
|
|
35
|
+
};
|
|
36
|
+
'api.keys.revoke': {
|
|
37
|
+
readonly input: {
|
|
38
|
+
readonly id: string;
|
|
39
|
+
};
|
|
40
|
+
readonly output: {
|
|
41
|
+
readonly id: string;
|
|
42
|
+
readonly revoked: boolean;
|
|
43
|
+
};
|
|
44
|
+
readonly faults: never;
|
|
45
|
+
};
|
|
46
|
+
'api.keys.rotate': {
|
|
47
|
+
readonly input: {
|
|
48
|
+
readonly id: string;
|
|
49
|
+
};
|
|
50
|
+
readonly output: {
|
|
51
|
+
readonly id: string;
|
|
52
|
+
readonly retiresAt: number;
|
|
53
|
+
readonly secret: string;
|
|
54
|
+
};
|
|
55
|
+
readonly faults: never;
|
|
56
|
+
};
|
|
57
|
+
};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
import { type CatalogHost } from '@lostgradient/backchannel-svelte';
|
|
2
|
+
import type { ClientOperationTypes } from "./operation-client.generated.js";
|
|
3
|
+
export { getCatalogHost as getApiKeySettingsHost } from '@lostgradient/backchannel-svelte';
|
|
4
|
+
export { default as ApiKeySettingsProvider } from '@lostgradient/backchannel-svelte/provider';
|
|
5
|
+
export declare function useApiKeysIssue(host: CatalogHost): {
|
|
6
|
+
pending: import("svelte/store").Readable<boolean>;
|
|
7
|
+
fault: import("svelte/store").Readable<"unknown" | undefined>;
|
|
8
|
+
mutateAsync(input: {
|
|
9
|
+
readonly expiresAt?: number;
|
|
10
|
+
readonly label: string;
|
|
11
|
+
readonly scopes: ReadonlyArray<string>;
|
|
12
|
+
readonly subject: string;
|
|
13
|
+
}): Promise<{
|
|
14
|
+
readonly id: string;
|
|
15
|
+
readonly secret: string;
|
|
16
|
+
}>;
|
|
17
|
+
reconcile(read: string, input: unknown): Promise<unknown>;
|
|
18
|
+
};
|
|
19
|
+
export declare function useApiKeysList(host: CatalogHost, input: () => ClientOperationTypes['api.keys.list']['input']): {
|
|
20
|
+
readonly data: {
|
|
21
|
+
readonly keys: ReadonlyArray<{
|
|
22
|
+
readonly actions: ReadonlyArray<string>;
|
|
23
|
+
readonly expiresAt?: number;
|
|
24
|
+
readonly id: string;
|
|
25
|
+
readonly label: string;
|
|
26
|
+
readonly retiresAt?: number;
|
|
27
|
+
readonly revokedAt?: number;
|
|
28
|
+
readonly scopes: ReadonlyArray<string>;
|
|
29
|
+
readonly subject: string;
|
|
30
|
+
readonly workspaceId: string;
|
|
31
|
+
}>;
|
|
32
|
+
readonly targets: ReadonlyArray<{
|
|
33
|
+
readonly scopes: ReadonlyArray<string>;
|
|
34
|
+
readonly subject: string;
|
|
35
|
+
}>;
|
|
36
|
+
} | undefined;
|
|
37
|
+
readonly isInitialLoading: boolean;
|
|
38
|
+
readonly isRefreshing: boolean;
|
|
39
|
+
readonly initialError: Error | null | undefined;
|
|
40
|
+
readonly refreshError: Error | null | undefined;
|
|
41
|
+
activate(): () => void;
|
|
42
|
+
refresh(): Promise<{
|
|
43
|
+
readonly keys: ReadonlyArray<{
|
|
44
|
+
readonly actions: ReadonlyArray<string>;
|
|
45
|
+
readonly expiresAt?: number;
|
|
46
|
+
readonly id: string;
|
|
47
|
+
readonly label: string;
|
|
48
|
+
readonly retiresAt?: number;
|
|
49
|
+
readonly revokedAt?: number;
|
|
50
|
+
readonly scopes: ReadonlyArray<string>;
|
|
51
|
+
readonly subject: string;
|
|
52
|
+
readonly workspaceId: string;
|
|
53
|
+
}>;
|
|
54
|
+
readonly targets: ReadonlyArray<{
|
|
55
|
+
readonly scopes: ReadonlyArray<string>;
|
|
56
|
+
readonly subject: string;
|
|
57
|
+
}>;
|
|
58
|
+
}>;
|
|
59
|
+
dispose: () => void;
|
|
60
|
+
};
|
|
61
|
+
export declare function useApiKeysRevoke(host: CatalogHost): {
|
|
62
|
+
pending: import("svelte/store").Readable<boolean>;
|
|
63
|
+
fault: import("svelte/store").Readable<"unknown" | undefined>;
|
|
64
|
+
mutateAsync(input: {
|
|
65
|
+
readonly id: string;
|
|
66
|
+
}): Promise<{
|
|
67
|
+
readonly id: string;
|
|
68
|
+
readonly revoked: boolean;
|
|
69
|
+
}>;
|
|
70
|
+
reconcile(read: string, input: unknown): Promise<unknown>;
|
|
71
|
+
};
|
|
72
|
+
export declare function useApiKeysRotate(host: CatalogHost): {
|
|
73
|
+
pending: import("svelte/store").Readable<boolean>;
|
|
74
|
+
fault: import("svelte/store").Readable<"unknown" | undefined>;
|
|
75
|
+
mutateAsync(input: {
|
|
76
|
+
readonly id: string;
|
|
77
|
+
}): Promise<{
|
|
78
|
+
readonly id: string;
|
|
79
|
+
readonly retiresAt: number;
|
|
80
|
+
readonly secret: string;
|
|
81
|
+
}>;
|
|
82
|
+
reconcile(read: string, input: unknown): Promise<unknown>;
|
|
83
|
+
};
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
/* generated by scripts/generate-operation-client.ts; do not edit by hand */
|
|
2
|
+
import { createCommand, createReactiveRead, } from '@lostgradient/backchannel-svelte';
|
|
3
|
+
export { getCatalogHost as getApiKeySettingsHost } from '@lostgradient/backchannel-svelte';
|
|
4
|
+
export { default as ApiKeySettingsProvider } from '@lostgradient/backchannel-svelte/provider';
|
|
5
|
+
export function useApiKeysIssue(host) {
|
|
6
|
+
return createCommand(host, 'api.keys.issue', ['api.keys.list']);
|
|
7
|
+
}
|
|
8
|
+
export function useApiKeysList(host, input) {
|
|
9
|
+
const read = createReactiveRead(host, 'api.keys.list', input);
|
|
10
|
+
return read;
|
|
11
|
+
}
|
|
12
|
+
export function useApiKeysRevoke(host) {
|
|
13
|
+
return createCommand(host, 'api.keys.revoke', ['api.keys.list']);
|
|
14
|
+
}
|
|
15
|
+
export function useApiKeysRotate(host) {
|
|
16
|
+
return createCommand(host, 'api.keys.rotate', ['api.keys.list']);
|
|
17
|
+
}
|
package/dist/svelte.d.ts
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { ApiKeySettingsProvider, getApiKeySettingsHost, useApiKeysIssue, useApiKeysList, useApiKeysRevoke, useApiKeysRotate, } from "./generated/operation-client.svelte.js";
|
package/dist/svelte.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { ApiKeySettingsProvider, getApiKeySettingsHost, useApiKeysIssue, useApiKeysList, useApiKeysRevoke, useApiKeysRotate, } from "./generated/operation-client.svelte.js";
|
package/package.json
CHANGED
|
@@ -1,6 +1,48 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@lostgradient/api-key-settings",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Optional API key management operations and settings for applications.",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"license": "MIT",
|
|
7
|
+
"sideEffects": false,
|
|
8
|
+
"repository": {
|
|
9
|
+
"type": "git",
|
|
10
|
+
"url": "git+https://github.com/stevekinney/corvidae.git",
|
|
11
|
+
"directory": "packages/api-key-settings"
|
|
12
|
+
},
|
|
13
|
+
"engines": {
|
|
14
|
+
"node": ">=22",
|
|
15
|
+
"bun": ">=1.4.0"
|
|
16
|
+
},
|
|
17
|
+
"exports": {
|
|
18
|
+
"./backchannel": {
|
|
19
|
+
"types": "./dist/backchannel.d.ts",
|
|
20
|
+
"default": "./dist/backchannel.js"
|
|
21
|
+
},
|
|
22
|
+
"./svelte": {
|
|
23
|
+
"types": "./dist/svelte.d.ts",
|
|
24
|
+
"default": "./dist/svelte.js"
|
|
25
|
+
},
|
|
26
|
+
"./ui": {
|
|
27
|
+
"types": "./dist/ApiKeySettings.svelte.d.ts",
|
|
28
|
+
"svelte": "./dist/ApiKeySettings.svelte",
|
|
29
|
+
"default": "./dist/ApiKeySettings.svelte"
|
|
30
|
+
}
|
|
31
|
+
},
|
|
32
|
+
"dependencies": {
|
|
33
|
+
"@lostgradient/backchannel": "0.1.1",
|
|
34
|
+
"@lostgradient/backchannel-svelte": "0.1.1",
|
|
35
|
+
"@lostgradient/credentials": "0.2.0"
|
|
36
|
+
},
|
|
37
|
+
"peerDependencies": {
|
|
38
|
+
"@lostgradient/cinder": "^0.30.0",
|
|
39
|
+
"@tanstack/svelte-query": "^6.2.1",
|
|
40
|
+
"svelte": "^5.57.1",
|
|
41
|
+
"zod": "^4.6.6"
|
|
42
|
+
},
|
|
43
|
+
"peerDependenciesMeta": {
|
|
44
|
+
"@lostgradient/cinder": {
|
|
45
|
+
"optional": true
|
|
46
|
+
}
|
|
47
|
+
}
|
|
6
48
|
}
|