@agentic-kit/session 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.
Files changed (55) hide show
  1. package/LICENSE +23 -0
  2. package/README.md +207 -2
  3. package/account-store.d.ts +78 -0
  4. package/account-store.js +162 -0
  5. package/agent-store.d.ts +79 -0
  6. package/agent-store.js +251 -0
  7. package/agent.d.ts +137 -0
  8. package/agent.js +514 -0
  9. package/api-key.d.ts +53 -0
  10. package/api-key.js +60 -0
  11. package/app-session.d.ts +48 -0
  12. package/app-session.js +105 -0
  13. package/auth-error.d.ts +54 -0
  14. package/auth-error.js +186 -0
  15. package/auth.d.ts +169 -0
  16. package/auth.js +514 -0
  17. package/backend-store.d.ts +134 -0
  18. package/backend-store.js +259 -0
  19. package/env.d.ts +9 -0
  20. package/env.js +10 -0
  21. package/esm/account-store.d.ts +78 -0
  22. package/esm/account-store.js +146 -0
  23. package/esm/agent-store.d.ts +79 -0
  24. package/esm/agent-store.js +201 -0
  25. package/esm/agent.d.ts +137 -0
  26. package/esm/agent.js +503 -0
  27. package/esm/api-key.d.ts +53 -0
  28. package/esm/api-key.js +52 -0
  29. package/esm/app-session.d.ts +48 -0
  30. package/esm/app-session.js +66 -0
  31. package/esm/auth-error.d.ts +54 -0
  32. package/esm/auth-error.js +171 -0
  33. package/esm/auth.d.ts +169 -0
  34. package/esm/auth.js +467 -0
  35. package/esm/backend-store.d.ts +134 -0
  36. package/esm/backend-store.js +239 -0
  37. package/esm/env.d.ts +9 -0
  38. package/esm/env.js +6 -0
  39. package/esm/index.d.ts +12 -0
  40. package/esm/index.js +11 -0
  41. package/esm/operation.d.ts +45 -0
  42. package/esm/operation.js +87 -0
  43. package/esm/session.d.ts +192 -0
  44. package/esm/session.js +297 -0
  45. package/esm/tools-host.d.ts +29 -0
  46. package/esm/tools-host.js +71 -0
  47. package/index.d.ts +12 -0
  48. package/index.js +63 -0
  49. package/operation.d.ts +45 -0
  50. package/operation.js +92 -0
  51. package/package.json +40 -3
  52. package/session.d.ts +192 -0
  53. package/session.js +307 -0
  54. package/tools-host.d.ts +29 -0
  55. package/tools-host.js +74 -0
@@ -0,0 +1,259 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.ContextInUseError = exports.EndpointError = exports.PLANES = void 0;
4
+ exports.planeEndpoint = planeEndpoint;
5
+ exports.differingPlanes = differingPlanes;
6
+ exports.isLoopback = isLoopback;
7
+ exports.checkedEndpoint = checkedEndpoint;
8
+ exports.checkedBackend = checkedBackend;
9
+ exports.backendFromEndpoints = backendFromEndpoints;
10
+ exports.contextNameFor = contextNameFor;
11
+ exports.readBackend = readBackend;
12
+ exports.listBackends = listBackends;
13
+ exports.backendConflict = backendConflict;
14
+ exports.addBackend = addBackend;
15
+ exports.writeBackend = writeBackend;
16
+ exports.restoreBackend = restoreBackend;
17
+ exports.selectBackend = selectBackend;
18
+ exports.removeBackend = removeBackend;
19
+ const db_tools_1 = require("@agentic-kit/db-tools");
20
+ const account_store_1 = require("./account-store");
21
+ const agent_store_1 = require("./agent-store");
22
+ exports.PLANES = ['api', 'auth', 'modules', 'agent', 'compute'];
23
+ const KEY = {
24
+ api: 'apiEndpoint',
25
+ auth: 'authEndpoint',
26
+ modules: 'modulesEndpoint',
27
+ agent: 'agentEndpoint',
28
+ compute: 'computeEndpoint'
29
+ };
30
+ function planeEndpoint(config, plane) {
31
+ return config[KEY[plane]];
32
+ }
33
+ /** The planes whose endpoints differ, compared exactly (no case or slash folding). */
34
+ function differingPlanes(a, b) {
35
+ return exports.PLANES.filter((plane) => planeEndpoint(a, plane) !== planeEndpoint(b, plane));
36
+ }
37
+ /**
38
+ * Whether `url` names this machine, where plain http never crosses a network: a host whose last label is localhost,
39
+ * an IPv4 address in 127/8, or ::1.
40
+ */
41
+ function isLoopback(url) {
42
+ const host = url.hostname;
43
+ return host.split('.').pop() === 'localhost' || /^127(\.\d{1,3}){3}$/.test(host) || host === '[::1]';
44
+ }
45
+ /** An endpoint that cannot name a backend. The message never shows userinfo. */
46
+ class EndpointError extends Error {
47
+ reason;
48
+ plane;
49
+ constructor(reason, plane, message) {
50
+ super(message);
51
+ this.reason = reason;
52
+ this.plane = plane;
53
+ this.name = 'EndpointError';
54
+ }
55
+ }
56
+ exports.EndpointError = EndpointError;
57
+ function shown(endpoint) {
58
+ try {
59
+ const url = new URL(endpoint);
60
+ url.username = '';
61
+ url.password = '';
62
+ return url.toString();
63
+ }
64
+ catch {
65
+ return endpoint.replace(/\/\/[^/@]*@/, '//');
66
+ }
67
+ }
68
+ /** `raw` as an endpoint of `plane`, or the `EndpointError` that says why it cannot be one. */
69
+ function checkedEndpoint(plane, raw) {
70
+ const endpoint = raw.trim();
71
+ let url;
72
+ try {
73
+ url = new URL(endpoint);
74
+ }
75
+ catch {
76
+ throw new EndpointError('not-a-url', plane, `The ${plane} endpoint "${shown(endpoint) || '(empty)'}" is not an absolute URL. Pass one such as https://${plane}.example.com/graphql.`);
77
+ }
78
+ if (url.protocol !== 'http:' && url.protocol !== 'https:') {
79
+ throw new EndpointError('scheme', plane, `The ${plane} endpoint ${shown(endpoint)} uses ${url.protocol}, but only http and https are supported. Pass an http or https URL.`);
80
+ }
81
+ if (url.protocol === 'http:' && !isLoopback(url)) {
82
+ throw new EndpointError('insecure', plane, `The ${plane} endpoint ${shown(endpoint)} uses plain http on a host that is not this machine, so the password and keys sent to it would cross the network unencrypted. Use its https URL; plain http is accepted only for localhost.`);
83
+ }
84
+ if (url.username || url.password) {
85
+ throw new EndpointError('userinfo', plane, `The ${plane} endpoint ${shown(endpoint)} has a user name or password in it, which would go to every plane. Remove it; sign in with email and password instead.`);
86
+ }
87
+ return endpoint;
88
+ }
89
+ /** Five endpoints of a backend, each checked as given, none derived. Throws `EndpointError`. */
90
+ function checkedBackend(endpoints) {
91
+ return Object.fromEntries(exports.PLANES.map((plane) => [KEY[plane], checkedEndpoint(plane, endpoints[KEY[plane]] ?? '')]));
92
+ }
93
+ /**
94
+ * The planes share the api endpoint's host scheme only when the host is
95
+ * `api.<rest>` (api.example.com -> auth.example.com). Any other host would send
96
+ * the password to a host the user never named, so it must give every plane.
97
+ */
98
+ function derivedEndpoint(api, plane) {
99
+ const labels = new URL(api).hostname.split('.');
100
+ if (labels[0] !== 'api' || labels.length < 2 || labels.some((label) => label === '')) {
101
+ throw new EndpointError('not-derivable', plane, `Cannot derive the ${plane} endpoint from ${shown(api)}: the other planes are derived only from a host that starts with "api.". Give every plane endpoint explicitly (auth, modules, agent and compute).`);
102
+ }
103
+ return (0, db_tools_1.deriveSubdomainEndpoint)(api, plane);
104
+ }
105
+ /**
106
+ * The backend that `api` names. A plane given explicitly is used as is; a
107
+ * missing one is derived from an `api.<rest>` host. Throws `EndpointError`.
108
+ */
109
+ function backendFromEndpoints(endpoints) {
110
+ const api = checkedEndpoint('api', endpoints.api ?? '');
111
+ const config = { apiEndpoint: api };
112
+ for (const plane of exports.PLANES) {
113
+ if (plane === 'api')
114
+ continue;
115
+ const given = endpoints[plane];
116
+ config[KEY[plane]] = given !== undefined ? checkedEndpoint(plane, given) : derivedEndpoint(api, plane);
117
+ }
118
+ return config;
119
+ }
120
+ /**
121
+ * A backend is a named context in the shared store, named after the api
122
+ * endpoint's host without a leading `api.` (https://api.example.com/graphql ->
123
+ * example.com), a port joined by a dash (example.com-8443). Credentials hang
124
+ * off the context, so each backend keeps an independent session.
125
+ */
126
+ function contextNameFor(config) {
127
+ const { host, hostname } = new URL(config.apiEndpoint);
128
+ const labels = hostname.split('.');
129
+ const raw = labels[0] === 'api' && labels.length >= 2 ? host.slice('api.'.length) : host;
130
+ const name = raw
131
+ .toLowerCase()
132
+ .replace(/[^a-z0-9.-]+/g, '-')
133
+ .replace(/\.{2,}/g, '.')
134
+ .replace(/^[^a-z0-9]+|[^a-z0-9]+$/g, '')
135
+ .slice(0, 100)
136
+ .replace(/[^a-z0-9]+$/, '');
137
+ return (0, account_store_1.checkContextName)(name || 'backend');
138
+ }
139
+ /** A stored context read back: its endpoints pass the same check as new ones, or it is `incomplete` or `invalid`. */
140
+ function fromTargets(name, current, targets) {
141
+ const missing = exports.PLANES.filter((plane) => !targets?.[plane]?.endpoint);
142
+ if (missing.length > 0) {
143
+ const apiEndpoint = targets?.api?.endpoint;
144
+ return { name, current, status: 'incomplete', missing, ...(apiEndpoint ? { apiEndpoint } : {}) };
145
+ }
146
+ try {
147
+ const endpoints = Object.fromEntries(exports.PLANES.map((plane) => [KEY[plane], targets[plane].endpoint]));
148
+ return { name, current, status: 'complete', backend: checkedBackend(endpoints) };
149
+ }
150
+ catch (err) {
151
+ if (!(err instanceof EndpointError))
152
+ throw err;
153
+ return { name, current, status: 'invalid', plane: err.plane, problem: err.message };
154
+ }
155
+ }
156
+ /** One stored context, or null when there is none with that name. */
157
+ function readBackend(store, name) {
158
+ const ctx = store.loadContext((0, account_store_1.checkContextName)(name));
159
+ return ctx ? fromTargets(name, name === (0, account_store_1.currentContextName)(store), ctx.targets) : null;
160
+ }
161
+ /** Every stored context. One with a name that does not pass the check is listed as `invalid-name` and stops nothing. */
162
+ function listBackends(store) {
163
+ const current = store.loadSettings().currentContext;
164
+ return store.listContexts().map((ctx) => {
165
+ const name = String(ctx.name);
166
+ try {
167
+ (0, account_store_1.checkContextName)(name);
168
+ }
169
+ catch (err) {
170
+ if (!(err instanceof account_store_1.ContextNameError))
171
+ throw err;
172
+ return { name, current: name === current, status: 'invalid-name', reason: err.message };
173
+ }
174
+ return fromTargets(name, name === current, ctx.targets);
175
+ });
176
+ }
177
+ /** Storing other endpoints under the context, or removing it, would drop the session filed there while its API key stays valid. */
178
+ class ContextInUseError extends Error {
179
+ context;
180
+ action;
181
+ agents;
182
+ constructor(context, action, agents = []) {
183
+ super(action === 'store'
184
+ ? `The context "${context}" holds a session that was not issued for these endpoints, or credentials another tool stored, so storing them would drop it while its key stays valid. Sign out of "${context}" first, which revokes that key, or store the backend under another name.`
185
+ : action === 'agents'
186
+ ? `The context "${context}" has agents set up with its endpoints (${agents.join(', ')}), and their keys work only there, so its endpoints cannot change. Delete those agents first (agent delete), or store the backend under another name.`
187
+ : agents.length
188
+ ? `The context "${context}" has agents (${agents.join(', ')}) whose keys stay valid after it is gone, with no entry left to remove them by, so it was not removed. Delete those agents first (agent delete), which ends their keys.`
189
+ : `The context "${context}" holds a session, so removing it would drop the session while its API key stays valid. Sign out of "${context}" first, which revokes that key.`);
190
+ this.context = context;
191
+ this.action = action;
192
+ this.agents = agents;
193
+ this.name = 'ContextInUseError';
194
+ }
195
+ }
196
+ exports.ContextInUseError = ContextInUseError;
197
+ /**
198
+ * Why `config` cannot be stored under `name` now, or null. Credentials filed there must be a session this package
199
+ * wrote, issued for these endpoints; `replacing` takes any session of its own, which a sign-in revokes and replaces.
200
+ * A context whose agents were set up with its endpoints keeps them. The name is checked first, then the agents, then
201
+ * the session: removing an agent needs that sign-in, so the agents must go first.
202
+ */
203
+ function backendConflict(store, config, name, { replacing = false } = {}) {
204
+ (0, account_store_1.checkContextName)(name);
205
+ const stored = readBackend(store, name);
206
+ const agents = stored ? (0, agent_store_1.listAgentNames)(store, name) : [];
207
+ if (agents.length && (stored.status !== 'complete' || differingPlanes(stored.backend, config).length > 0))
208
+ return new ContextInUseError(name, 'agents', agents);
209
+ if (store.getCredentials(name)) {
210
+ const session = (0, account_store_1.loadSession)(store, name);
211
+ if (!session || (!replacing && (!session.issuedFor || differingPlanes(session.issuedFor, config).length > 0)))
212
+ return new ContextInUseError(name, 'store');
213
+ }
214
+ return null;
215
+ }
216
+ /**
217
+ * Store the endpoints as a context (default name: `contextNameFor`), keeping
218
+ * its current choice and the session filed under that name, which must have
219
+ * been issued for exactly these five endpoints. Throws `ContextInUseError`
220
+ * when it was not, or cannot be shown to be (sign out of that context first),
221
+ * and when agents of the context were set up with other endpoints.
222
+ */
223
+ function addBackend(store, config, name = contextNameFor(config)) {
224
+ const conflict = backendConflict(store, config, name);
225
+ if (conflict)
226
+ throw conflict;
227
+ writeBackend(store, config, name);
228
+ return { name };
229
+ }
230
+ /** Write the endpoints under `name` with no check of what is filed there: for a caller that checked with `backendConflict`. */
231
+ function writeBackend(store, config, name) {
232
+ const targets = Object.fromEntries(exports.PLANES.map((plane) => [plane, { endpoint: config[KEY[plane]] }]));
233
+ store.createContext((0, account_store_1.checkContextName)(name), { endpoint: config.apiEndpoint, targets });
234
+ }
235
+ /** Put back a context `writeBackend` replaced: its old endpoints, or no context when there was none. */
236
+ function restoreBackend(store, name, previous) {
237
+ if (previous)
238
+ store.createContext((0, account_store_1.checkContextName)(name), { endpoint: previous.endpoint, targets: previous.targets });
239
+ else
240
+ store.deleteContext((0, account_store_1.checkContextName)(name));
241
+ }
242
+ function selectBackend(store, name) {
243
+ if (!store.setCurrentContext((0, account_store_1.checkContextName)(name))) {
244
+ const known = store.listContexts().map((ctx) => ctx.name);
245
+ throw new Error(`No backend context named "${name}". Known contexts: ${known.join(', ') || '(none)'}. Add the backend first.`);
246
+ }
247
+ }
248
+ /**
249
+ * Delete a context. Throws `ContextInUseError` while agents are stored under it (`removeAgent` first, which needs the
250
+ * sign-in), then while a session is filed under it (`signOut` first, which revokes its key).
251
+ */
252
+ function removeBackend(store, name) {
253
+ const agents = (0, agent_store_1.listAgentNames)(store, (0, account_store_1.checkContextName)(name));
254
+ if (agents.length)
255
+ throw new ContextInUseError(name, 'remove', agents);
256
+ if (store.getCredentials(name))
257
+ throw new ContextInUseError(name, 'remove');
258
+ return store.deleteContext(name);
259
+ }
package/env.d.ts ADDED
@@ -0,0 +1,9 @@
1
+ /**
2
+ * The CONSTRUCTIVE_* variables the agentic packages read, and the one place that reads them from the process. Every
3
+ * reader takes this view; a host or a test passes its own environment, and only the default comes from process.env.
4
+ */
5
+ export type ConstructiveEnv = Readonly<Record<string, string | undefined>>;
6
+ /** Base directory of the stash, for tests and isolated runs. Desktop reads the same variable. */
7
+ export declare const STASH_DIR_ENV = "CONSTRUCTIVE_STASH_DIR";
8
+ /** The CONSTRUCTIVE_* variables of `env` (default: the process's), as given: '' stays '', so a reader can refuse it. */
9
+ export declare function getConstructiveEnv(env?: NodeJS.ProcessEnv): ConstructiveEnv;
package/env.js ADDED
@@ -0,0 +1,10 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.STASH_DIR_ENV = void 0;
4
+ exports.getConstructiveEnv = getConstructiveEnv;
5
+ /** Base directory of the stash, for tests and isolated runs. Desktop reads the same variable. */
6
+ exports.STASH_DIR_ENV = 'CONSTRUCTIVE_STASH_DIR';
7
+ /** The CONSTRUCTIVE_* variables of `env` (default: the process's), as given: '' stays '', so a reader can refuse it. */
8
+ function getConstructiveEnv(env = process.env) {
9
+ return Object.fromEntries(Object.entries(env).filter(([name]) => name.startsWith('CONSTRUCTIVE_')));
10
+ }
@@ -0,0 +1,78 @@
1
+ import { ConfigStore } from 'appstash';
2
+ import type { BackendEndpoints } from './backend-store';
3
+ import { type ConstructiveEnv } from './env';
4
+ /**
5
+ * Directory identity shared by every Constructive binary and the desktop app,
6
+ * so a sign-in through one is a sign-in through all of them.
7
+ */
8
+ export declare const STASH_NAME = "constructive";
9
+ export { STASH_DIR_ENV } from './env';
10
+ /** An empty value is an error: treating it as unset would open the real store under the home directory. */
11
+ export declare function stashBaseDir(env?: ConstructiveEnv): string | undefined;
12
+ /**
13
+ * The store under `baseDir`, or under the home directory when `baseDir` is
14
+ * undefined. Called with no argument, it reads CONSTRUCTIVE_STASH_DIR from the
15
+ * process's environment; a caller that resolved an injected environment passes its
16
+ * result, undefined included, so the ambient variable never overrides it.
17
+ */
18
+ export declare function openStore(...args: [baseDir?: string | undefined]): ConfigStore;
19
+ /**
20
+ * The directories of a store `openStore` opened: `config` holds files beside
21
+ * the credentials, `cache` files that may be deleted at any time.
22
+ */
23
+ export declare function storeDirs(store: ConfigStore): {
24
+ config: string;
25
+ cache: string;
26
+ };
27
+ /**
28
+ * Every directory the store `openStore` opens uses (root, config, cache, data,
29
+ * logs, tmp), from the same appstash resolution, so a caller can refuse a path
30
+ * inside the store. Creates nothing.
31
+ */
32
+ export declare function stashDirectories(env?: ConstructiveEnv): string[];
33
+ /** A context name that cannot name a file in the store's contexts directory. */
34
+ export declare class ContextNameError extends Error {
35
+ readonly value: string;
36
+ constructor(value: string);
37
+ }
38
+ /**
39
+ * A context name is the stem of a file in the store, so it is checked before
40
+ * any read or write: no separator, no `..`, no leading dot, and lower case
41
+ * only, so two names never reach one file on a disk that ignores letter case.
42
+ */
43
+ export declare const isContextName: (name: unknown) => name is string;
44
+ export declare function checkContextName(name: string): string;
45
+ export interface AccountSession {
46
+ userId: string;
47
+ email: string;
48
+ accessToken: string;
49
+ accessTokenExpiresAt?: string;
50
+ apiKey?: string;
51
+ keyId?: string;
52
+ apiKeyExpiresAt?: string;
53
+ signedInAt: number;
54
+ /**
55
+ * The whole backend the session was issued for, as recorded: text from the disk, used to compare and never sent to
56
+ * unchecked. Absent for a session stored before it was recorded, or by another app.
57
+ */
58
+ issuedFor?: BackendEndpoints;
59
+ /** The auth endpoint that issued the session, the field Desktop reads and writes. Written from `issuedFor` when it is known. */
60
+ authEndpoint?: string;
61
+ }
62
+ /** `value` as the five recorded endpoints, or undefined when it lacks one. */
63
+ export declare function issuedForOf(value: unknown): BackendEndpoints | undefined;
64
+ /**
65
+ * Sessions live in the shared Constructive stash, as the credentials of a
66
+ * backend context. The store owns the file layout, the atomic 0600 writes and
67
+ * the at-rest encoding; this module only maps between its `ContextCredentials`
68
+ * and the session shape callers pass around.
69
+ */
70
+ export declare function currentContextName(store: ConfigStore): string | null;
71
+ export declare function loadSession(store: ConfigStore, context?: string): AccountSession | null;
72
+ /**
73
+ * `context` names the backend the session belongs to; it does not have to exist
74
+ * as a context yet, so a sign-in can be filed before the backend is committed
75
+ * and a failed sign-in leaves nothing behind.
76
+ */
77
+ export declare function saveSession(store: ConfigStore, session: AccountSession, context?: string): void;
78
+ export declare function clearSession(store: ConfigStore, context?: string): void;
@@ -0,0 +1,146 @@
1
+ import { appstash, createConfigStore } from 'appstash';
2
+ import { getConstructiveEnv, STASH_DIR_ENV } from './env';
3
+ /**
4
+ * Directory identity shared by every Constructive binary and the desktop app,
5
+ * so a sign-in through one is a sign-in through all of them.
6
+ */
7
+ export const STASH_NAME = 'constructive';
8
+ export { STASH_DIR_ENV } from './env';
9
+ /** An empty value is an error: treating it as unset would open the real store under the home directory. */
10
+ export function stashBaseDir(env = getConstructiveEnv()) {
11
+ const dir = env[STASH_DIR_ENV];
12
+ if (dir === '') {
13
+ throw new Error(`${STASH_DIR_ENV} is set but empty, so it names no directory. Set it to a directory, or unset it to use the store under the home directory.`);
14
+ }
15
+ return dir;
16
+ }
17
+ const STORE_DIRS = new WeakMap();
18
+ /**
19
+ * The store under `baseDir`, or under the home directory when `baseDir` is
20
+ * undefined. Called with no argument, it reads CONSTRUCTIVE_STASH_DIR from the
21
+ * process's environment; a caller that resolved an injected environment passes its
22
+ * result, undefined included, so the ambient variable never overrides it.
23
+ */
24
+ export function openStore(...args) {
25
+ const baseDir = args.length ? args[0] : stashBaseDir();
26
+ const store = createConfigStore(STASH_NAME, { stashName: STASH_NAME, baseDir });
27
+ const { config, cache } = appstash(STASH_NAME, { baseDir });
28
+ STORE_DIRS.set(store, { config, cache });
29
+ return store;
30
+ }
31
+ /**
32
+ * The directories of a store `openStore` opened: `config` holds files beside
33
+ * the credentials, `cache` files that may be deleted at any time.
34
+ */
35
+ export function storeDirs(store) {
36
+ const dirs = STORE_DIRS.get(store);
37
+ if (!dirs)
38
+ throw new Error('This store was not opened with openStore, so its directory is unknown. Open it with openStore().');
39
+ return dirs;
40
+ }
41
+ /**
42
+ * Every directory the store `openStore` opens uses (root, config, cache, data,
43
+ * logs, tmp), from the same appstash resolution, so a caller can refuse a path
44
+ * inside the store. Creates nothing.
45
+ */
46
+ export function stashDirectories(env = getConstructiveEnv()) {
47
+ const dirs = appstash(STASH_NAME, { baseDir: stashBaseDir(env) });
48
+ return [...new Set([dirs.root, dirs.config, dirs.cache, dirs.data, dirs.logs, dirs.tmp])];
49
+ }
50
+ const CONTEXT_NAME = /^[a-z0-9][a-z0-9._-]{0,99}$/;
51
+ /** A context name that cannot name a file in the store's contexts directory. */
52
+ export class ContextNameError extends Error {
53
+ value;
54
+ constructor(value) {
55
+ super(`"${value.length > 120 ? `${value.slice(0, 120)}…` : value}" is not a valid context name. ` +
56
+ 'A context name has 1 to 100 characters: lower-case letters, digits, ".", "-" and "_", starting with a letter or a digit, with no "..".');
57
+ this.value = value;
58
+ this.name = 'ContextNameError';
59
+ }
60
+ }
61
+ /**
62
+ * A context name is the stem of a file in the store, so it is checked before
63
+ * any read or write: no separator, no `..`, no leading dot, and lower case
64
+ * only, so two names never reach one file on a disk that ignores letter case.
65
+ */
66
+ export const isContextName = (name) => typeof name === 'string' && CONTEXT_NAME.test(name) && !name.includes('..');
67
+ export function checkContextName(name) {
68
+ if (!isContextName(name))
69
+ throw new ContextNameError(String(name));
70
+ return name;
71
+ }
72
+ const BACKEND_KEYS = ['apiEndpoint', 'authEndpoint', 'modulesEndpoint', 'agentEndpoint', 'computeEndpoint'];
73
+ /** `value` as the five recorded endpoints, or undefined when it lacks one. */
74
+ export function issuedForOf(value) {
75
+ if (!value || typeof value !== 'object')
76
+ return undefined;
77
+ const record = value;
78
+ if (!BACKEND_KEYS.every((key) => typeof record[key] === 'string' && record[key] !== ''))
79
+ return undefined;
80
+ return Object.fromEntries(BACKEND_KEYS.map((key) => [key, record[key]]));
81
+ }
82
+ /**
83
+ * Sessions live in the shared Constructive stash, as the credentials of a
84
+ * backend context. The store owns the file layout, the atomic 0600 writes and
85
+ * the at-rest encoding; this module only maps between its `ContextCredentials`
86
+ * and the session shape callers pass around.
87
+ */
88
+ export function currentContextName(store) {
89
+ const name = store.loadSettings().currentContext;
90
+ // A name this package never writes, such as one another tool stored, is no context of ours: nothing is chosen.
91
+ if (!isContextName(name))
92
+ return null;
93
+ return store.loadContext(name) ? name : null;
94
+ }
95
+ /** The active context; a session is never filed under a backend nobody chose. */
96
+ function ensureContextName(store) {
97
+ const name = currentContextName(store);
98
+ if (!name)
99
+ throw new Error('No backend chosen: select a backend before saving a session.');
100
+ return name;
101
+ }
102
+ export function loadSession(store, context) {
103
+ const contextName = context === undefined ? currentContextName(store) : checkContextName(context);
104
+ if (!contextName)
105
+ return null;
106
+ const creds = store.getCredentials(contextName);
107
+ if (!creds?.token || !creds.userId)
108
+ return null;
109
+ return {
110
+ userId: creds.userId,
111
+ email: creds.email ?? '',
112
+ accessToken: creds.token,
113
+ accessTokenExpiresAt: creds.expiresAt,
114
+ apiKey: creds.apiKey,
115
+ keyId: creds.keyId,
116
+ apiKeyExpiresAt: creds.apiKeyExpiresAt,
117
+ signedInAt: creds.signedInAt ?? 0,
118
+ ...(issuedForOf(creds.issuedFor) ? { issuedFor: issuedForOf(creds.issuedFor) } : {}),
119
+ ...(typeof creds.authEndpoint === 'string' && creds.authEndpoint ? { authEndpoint: creds.authEndpoint } : {})
120
+ };
121
+ }
122
+ /**
123
+ * `context` names the backend the session belongs to; it does not have to exist
124
+ * as a context yet, so a sign-in can be filed before the backend is committed
125
+ * and a failed sign-in leaves nothing behind.
126
+ */
127
+ export function saveSession(store, session, context) {
128
+ const credentials = {
129
+ token: session.accessToken,
130
+ expiresAt: session.accessTokenExpiresAt,
131
+ userId: session.userId,
132
+ email: session.email,
133
+ apiKey: session.apiKey,
134
+ keyId: session.keyId,
135
+ apiKeyExpiresAt: session.apiKeyExpiresAt,
136
+ signedInAt: session.signedInAt,
137
+ ...(session.issuedFor ? { issuedFor: session.issuedFor } : {}),
138
+ ...(session.issuedFor || session.authEndpoint ? { authEndpoint: session.issuedFor?.authEndpoint ?? session.authEndpoint } : {})
139
+ };
140
+ store.setCredentials(context === undefined ? ensureContextName(store) : checkContextName(context), credentials);
141
+ }
142
+ export function clearSession(store, context) {
143
+ const contextName = context === undefined ? currentContextName(store) : checkContextName(context);
144
+ if (contextName)
145
+ store.removeCredentials(contextName);
146
+ }
@@ -0,0 +1,79 @@
1
+ import type { ConfigStore } from 'appstash';
2
+ import type { BackendEndpoints } from './backend-store';
3
+ /**
4
+ * The stored credential of one agent: a principal of the person, filed under
5
+ * the person's context, bound to the five endpoints it was issued for, and the
6
+ * principal's own API key, which this package uses only to mint access tokens.
7
+ * The backend accepts the key itself on requests too, so it is kept in one 0600
8
+ * file per agent.
9
+ */
10
+ export interface AgentRecord {
11
+ name: string;
12
+ context: string;
13
+ /** The principal's user id, which every principal call takes. */
14
+ principalId: string;
15
+ /** The person's user id: the account id every request names. */
16
+ ownerId: string;
17
+ organization?: string;
18
+ schemaChanges: boolean;
19
+ createdAt: string;
20
+ /** The five endpoints the key was issued for, as recorded: compared with the context's, never sent to. */
21
+ issuedFor: BackendEndpoints;
22
+ apiKey: string;
23
+ keyId: string;
24
+ keyExpiresAt: string;
25
+ }
26
+ /** An access token minted with the agent's key, cached beside it. `keyId` names the key that minted it. */
27
+ export interface CachedToken {
28
+ keyId: string;
29
+ accessToken: string;
30
+ accessExpiresAt: string;
31
+ }
32
+ export declare class AgentNameError extends Error {
33
+ readonly value: string;
34
+ constructor(value: string, reason?: string);
35
+ }
36
+ /**
37
+ * An agent name is the stem of a file in the store, so it follows the
38
+ * context-name rule, and it may not end like the store's own files.
39
+ */
40
+ export declare function checkAgentName(name: string): string;
41
+ export declare const agentFile: (store: ConfigStore, context: string, name: string) => string;
42
+ /**
43
+ * Write `content` with mode 0600 through a temporary file, so a reader sees the
44
+ * old file or the new one, never half of one. `create` fails with EEXIST when
45
+ * the file exists (a hard link never replaces), so of two creates one wins.
46
+ */
47
+ export declare function writeAtomic(file: string, content: string, mode: 'create' | 'replace'): void;
48
+ /** Whether a record file exists under the name, readable or not. */
49
+ export declare function agentEntryExists(store: ConfigStore, context: string, name: string): boolean;
50
+ /** A record file that does not parse, or lacks what an agent record holds: an edit by hand, since the store writes it atomically. */
51
+ export declare class AgentRecordUnreadable extends Error {
52
+ readonly file: string;
53
+ constructor(file: string, problem: string);
54
+ }
55
+ export declare function readAgent(store: ConfigStore, context: string, name: string): AgentRecord | null;
56
+ /** Store a new agent; throws an error with code EEXIST when an agent of that name is stored already. */
57
+ export declare function createAgentEntry(store: ConfigStore, record: AgentRecord): void;
58
+ export declare function writeAgent(store: ConfigStore, record: AgentRecord): void;
59
+ /**
60
+ * Delete the agent's cached token, best effort (see `readCachedToken`): a session takes a cached token only for the
61
+ * key that minted it, so a token left behind is never used again.
62
+ */
63
+ export declare function dropCachedToken(store: ConfigStore, context: string, name: string): void;
64
+ /** Delete the agent's record, then its cached token. Throws when the record cannot be deleted. */
65
+ export declare function deleteAgent(store: ConfigStore, context: string, name: string): void;
66
+ /** The names of the agents stored under `context`, valid names only, sorted. */
67
+ export declare function listAgentNames(store: ConfigStore, context: string): string[];
68
+ /** The cached token, or null when there is none or it does not parse: a missing cache only costs one more mint. */
69
+ /**
70
+ * The cached token, or null when there is none that can be read. The cache only saves a mint, so reading, writing
71
+ * and deleting it never fail an operation: a token that cannot be cached is minted again next time.
72
+ */
73
+ export declare function readCachedToken(store: ConfigStore, context: string, name: string): CachedToken | null;
74
+ /**
75
+ * Cache a minted token, best effort (see `readCachedToken`). Processes write it without a lock: a token may be used
76
+ * many times, so when two write at once, the one renamed last stays, and the other process's token still works
77
+ * until it ends.
78
+ */
79
+ export declare function writeCachedToken(store: ConfigStore, context: string, name: string, token: CachedToken): void;