@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.
- package/LICENSE +23 -0
- package/README.md +207 -2
- package/account-store.d.ts +78 -0
- package/account-store.js +162 -0
- package/agent-store.d.ts +79 -0
- package/agent-store.js +251 -0
- package/agent.d.ts +137 -0
- package/agent.js +514 -0
- package/api-key.d.ts +53 -0
- package/api-key.js +60 -0
- package/app-session.d.ts +48 -0
- package/app-session.js +105 -0
- package/auth-error.d.ts +54 -0
- package/auth-error.js +186 -0
- package/auth.d.ts +169 -0
- package/auth.js +514 -0
- package/backend-store.d.ts +134 -0
- package/backend-store.js +259 -0
- package/env.d.ts +9 -0
- package/env.js +10 -0
- package/esm/account-store.d.ts +78 -0
- package/esm/account-store.js +146 -0
- package/esm/agent-store.d.ts +79 -0
- package/esm/agent-store.js +201 -0
- package/esm/agent.d.ts +137 -0
- package/esm/agent.js +503 -0
- package/esm/api-key.d.ts +53 -0
- package/esm/api-key.js +52 -0
- package/esm/app-session.d.ts +48 -0
- package/esm/app-session.js +66 -0
- package/esm/auth-error.d.ts +54 -0
- package/esm/auth-error.js +171 -0
- package/esm/auth.d.ts +169 -0
- package/esm/auth.js +467 -0
- package/esm/backend-store.d.ts +134 -0
- package/esm/backend-store.js +239 -0
- package/esm/env.d.ts +9 -0
- package/esm/env.js +6 -0
- package/esm/index.d.ts +12 -0
- package/esm/index.js +11 -0
- package/esm/operation.d.ts +45 -0
- package/esm/operation.js +87 -0
- package/esm/session.d.ts +192 -0
- package/esm/session.js +297 -0
- package/esm/tools-host.d.ts +29 -0
- package/esm/tools-host.js +71 -0
- package/index.d.ts +12 -0
- package/index.js +63 -0
- package/operation.d.ts +45 -0
- package/operation.js +92 -0
- package/package.json +40 -3
- package/session.d.ts +192 -0
- package/session.js +307 -0
- package/tools-host.d.ts +29 -0
- package/tools-host.js +74 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
The MIT License (MIT)
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2025 Dan Lynch <pyramation@gmail.com>
|
|
4
|
+
Copyright (c) 2025 Constructive <developers@constructive.io>
|
|
5
|
+
Copyright (c) 2020-present, Interweb, Inc.
|
|
6
|
+
|
|
7
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
8
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
9
|
+
in the Software without restriction, including without limitation the rights
|
|
10
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
11
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
12
|
+
furnished to do so, subject to the following conditions:
|
|
13
|
+
|
|
14
|
+
The above copyright notice and this permission notice shall be included in all
|
|
15
|
+
copies or substantial portions of the Software.
|
|
16
|
+
|
|
17
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
18
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
19
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
20
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
21
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
22
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
23
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,208 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @agentic-kit/session
|
|
2
2
|
|
|
3
|
-
|
|
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/constructive/actions/workflows/run-tests.yaml">
|
|
9
|
+
<img height="20" src="https://github.com/constructive-io/constructive/actions/workflows/run-tests.yaml/badge.svg" />
|
|
10
|
+
</a>
|
|
11
|
+
<a href="https://github.com/constructive-io/constructive/blob/main/LICENSE"><img height="20" src="https://img.shields.io/badge/license-MIT-blue.svg"/></a>
|
|
12
|
+
<a href="https://www.npmjs.com/package/@agentic-kit/session"><img height="20" src="https://img.shields.io/github/package-json/v/constructive-io/constructive?filename=agentic%2Fsession%2Fpackage.json"/></a>
|
|
13
|
+
</p>
|
|
14
|
+
|
|
15
|
+
The Constructive sign-in that every binary shares: backend contexts, email and password sign-in, the stored session, agent credentials, and the `CONSTRUCTIVE_*` environment overrides. The binaries (the `agent` CLI, the `constructive` CLI, the desktop app) read the same [appstash](https://github.com/constructive-io/appstash) store under the stash name `constructive`, so a sign-in through one is a sign-in through the others when its session records the whole backend it was issued for. A session that records only its auth endpoint, as the desktop app writes it, is not used (`issuer-mismatch`), and a new sign-in replaces it. The package has no coding-agent SDK and ships no backend URL.
|
|
16
|
+
|
|
17
|
+
```bash
|
|
18
|
+
npm install @agentic-kit/session
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
## The session
|
|
22
|
+
|
|
23
|
+
`resolveSession({ context?, env?, store? })` answers "who talks to which backend" once, from the environment and the store together, and returns one of eight states:
|
|
24
|
+
|
|
25
|
+
| `kind` | Meaning |
|
|
26
|
+
| --- | --- |
|
|
27
|
+
| `no-backend` | No context is chosen (`context: null`), or the named one does not exist |
|
|
28
|
+
| `incomplete-backend` | The stored context lacks planes (`missing`), for example one another app wrote; no plane is filled in |
|
|
29
|
+
| `invalid-backend` | The stored context holds an endpoint that fails the endpoint check (`plane`, `problem`), for example plain http to another machine; nothing is sent to it |
|
|
30
|
+
| `invalid-override` | An environment variable is missing, empty or wrong; `variable`, `problem` and `fix` say which and what to do |
|
|
31
|
+
| `conflict` | A `context` was named, but an environment variable (`variable`) decides the session; drop one of the two |
|
|
32
|
+
| `issuer-mismatch` | A session is stored under the context, but it was issued for another backend (`differs` names the planes whose endpoints changed; `issuedFor` is what it was issued for), or it does not record its backend (`issuedFor: null`); it is never used or sent, and a new sign-in replaces it |
|
|
33
|
+
| `signed-out` | A usable backend (`source: 'env'` or `'store'`) and no credential for it |
|
|
34
|
+
| `signed-in` | The backend, the account and its key, all from one source |
|
|
35
|
+
|
|
36
|
+
A credential is only paired with the backend of its own source. Every stored session records the whole backend it was issued for (`issuedFor`, all five endpoints), and it is used only while the context it is filed under names exactly those five endpoints; the compare is exact, so a trailing slash or another letter case is a difference. The session also keeps `authEndpoint`, the field Constructive Desktop reads and writes, so Desktop still sees which auth plane issued it. A session that records only `authEndpoint`, as Desktop writes it, or nothing, cannot show which api, modules, agent and compute endpoints it belongs to: it is never used, and a new sign-in replaces it. Its key can still be revoked, at the recorded `authEndpoint` only, since that is where the token came from. A stored session is used with the endpoints of the context it is filed under, and never with a backend that `CONSTRUCTIVE_API_ENDPOINT` names, unless the override names exactly that context's backend. An environment credential needs the backend from the environment too. `sessionToolsHost({ signInHint, repairHint?, context?, env? })` builds the host of [`@agentic-kit/db-tools`](https://www.npmjs.com/package/@agentic-kit/db-tools) on it. It resolves again on every call, so a sign-in mid-session is picked up. With no backend, `backendConfig()` is undefined and `account()` is null; signed out, `backendConfig()` gives the backend and `account()` is null; for `issuer-mismatch`, `backendConfig()` gives the backend and `account()` throws `sessionProblem`, which names the planes that differ. For `invalid-override`, `conflict`, `incomplete-backend` and `invalid-backend` both getters throw an `Error` with `sessionProblem(session, repairHint)`, the problem and its fix, and a store that cannot be read throws its own error. The db tools turn such a throw into a failure that carries the message. `repairHint` is the binary's command that stores a complete context, for example ``Run `agent login` to store a complete backend.``
|
|
37
|
+
|
|
38
|
+
```ts
|
|
39
|
+
import { createConstructiveDbTools } from '@agentic-kit/db-tools';
|
|
40
|
+
import { sessionToolsHost } from '@agentic-kit/session';
|
|
41
|
+
|
|
42
|
+
const tools = createConstructiveDbTools(sessionToolsHost({ signInHint: 'Run `constructive login` to sign in.' }));
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
## Signing in and out
|
|
46
|
+
|
|
47
|
+
```ts
|
|
48
|
+
import { backendFromEndpoints, keyEndsSoon, openStore, resolveSession, signIn, signOut, verifySession } from '@agentic-kit/session';
|
|
49
|
+
|
|
50
|
+
const store = openStore();
|
|
51
|
+
const backend = backendFromEndpoints({ api: 'https://api.example.com/graphql' });
|
|
52
|
+
const { session, previousKey } = await signIn({ store, backend, email, password });
|
|
53
|
+
|
|
54
|
+
const resolved = resolveSession({ store });
|
|
55
|
+
if (resolved.kind === 'signed-in') {
|
|
56
|
+
await verifySession(resolved); // accepted | rejected | unchecked
|
|
57
|
+
if (resolved.account.key.kind === 'active' && keyEndsSoon({ expiresAt: resolved.account.key.expiresAt })) {
|
|
58
|
+
// ask the person to sign in again
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
const result = await signOut({ store, session: resolved });
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
`signIn` stores a new session with a new key, or changes nothing. It runs these steps, filed under `context` when the caller passes one (see [Operations](#operations)):
|
|
65
|
+
|
|
66
|
+
```text
|
|
67
|
+
check the store -> sign in [undo: end it] -> make a 30-day key [undo: revoke it]
|
|
68
|
+
-> store the endpoints [undo: put the old ones back] -> choose the context [undo: choose the old one]
|
|
69
|
+
-> COMMIT: store the session -> revoke the replaced key (previousKey) -> end the password sign-in
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
The stored bearer is the key, so no password sign-in session is left behind, and the new session records its issuer. A key is revoked only after its replacement is stored, so a failed store never leaves the old session pointing to a revoked key. When no key can be made, for example at the account's key limit, the sign-in throws a `SignInError` and stores nothing: at the limit, sign out of that backend first, which revokes the key this computer holds, or revoke a key in the app. A failed sign-in throws a `SignInError` whose `kind` is `invalid-input`, `invalid-credentials`, `second-factor-required`, `second-factor-unsupported` (the account's only second factor gives no code, such as a security key), `refused` (a locked account, too many attempts, a disabled method, the key limit, a code not sent again so soon, a challenge that ended; `code` is the server's, or `MFA_CODE_NOT_SENT`), `backend-unreachable` or `server-error`, and leaves the store as it was. The mint and the revoke have the same 10 s timeout as the sign-in.
|
|
73
|
+
|
|
74
|
+
An account with a second factor signs in in two steps. The password step throws `SecondFactorRequired`, whose `challenge` (`SignInChallenge`: the auth endpoint, the email, the user, the challenge token and the `method`) waits for a code: the backend emails it (`email`), or texts it when email codes are off (`sms`), or the person's authenticator app shows it (`totp`, which takes a backup code too). Pass `{ challenge, code }` in place of `password` to `signIn`, `createAgent`, `renewAgentKey` or `appSignIn`, within the backend's 10 minutes, and the same operation goes on. A challenge is sent only to the auth endpoint that issued it, for its own email. A host that can't ask for the code in the same run keeps the challenge with `saveSignInChallenge(store, context, challenge)` (mode 0600), reads it back with `loadSignInChallenge(store, context, authEndpoint)`, and drops it with `clearSignInChallenge` once its code was used.
|
|
75
|
+
|
|
76
|
+
`signInTarget({ api?, context?, env?, store? })` is where a sign-in goes, the same for every binary: the backend the session resolves to (the environment's, else the context's), with all its planes, also when `api` names its api endpoint; another `api` is a new backend whose planes are derived. It is `no-backend` when nothing is chosen and no `api` is given, and `unusable` (with the session) when the resolved backend cannot be used.
|
|
77
|
+
|
|
78
|
+
`signOut({ store, session })` acts on exactly the session `resolveSession` gave, so a CLI's `logout` removes what its `whoami` reported. It clears the stored session first, in every state, then revokes the API key at the auth endpoint the credential records (from `issuedFor`, else Desktop's `authEndpoint`, checked like any endpoint), with that credential's own bearer, never at whatever the context names now. It returns `{ kind: 'cleared', key }`, where `key` says whether the API key was `revoked`, `absent`, or `failed` and why (a session with no recorded issuer, or one that fails the check, sends nothing and says so). A key that was not revoked stays valid until it ends; revoke it in the app. It returns `{ kind: 'from-environment' }` for a session from the environment, which leaves the store alone, or `{ kind: 'not-signed-in' }`, and it throws the problem of an `invalid-override` or `conflict` session. It takes a person's session only: an agent's session, usable or not, carries the person's context, so `signOut` refuses it and changes nothing.
|
|
79
|
+
|
|
80
|
+
`verifySession(session)` asks the backend once whether a signed-in session's credential is accepted: `accepted`, `rejected` (HTTP 401 or 403, `UNAUTHENTICATED`, no user, or another user), or `unchecked` when the backend cannot answer. It has the 10 s timeout and classifies by status and code only. Nothing renews a key on its own, because a new key needs a fresh password sign-in: `keyEndsSoon({ expiresAt })` says when a key has ended or ends within 7 days (`SIGN_IN_AGAIN_WITHIN_MS`), so a binary can ask the person to sign in again. None of these throws for a server answer, and the package prints nothing. A message names the server's error codes, never its message text, which may name backend internals.
|
|
81
|
+
|
|
82
|
+
## Agents
|
|
83
|
+
|
|
84
|
+
An agent is a principal of the signed-in person, with its own key, for a coding agent or a CI job to act as.
|
|
85
|
+
|
|
86
|
+
```ts
|
|
87
|
+
import { agentSession, createAgent, listAgents, removeAgent, renewAgentKey, resolveSession, sessionToolsHost } from '@agentic-kit/session';
|
|
88
|
+
|
|
89
|
+
const person = resolveSession({ store });
|
|
90
|
+
await createAgent({ store, session: person, password, name: 'helper', allowSchemaChanges: false });
|
|
91
|
+
const host = sessionToolsHost({ signInHint: 'Run `constructive agent add helper` to set it up again.', agent: 'helper' });
|
|
92
|
+
listAgents({ store }); // [{ name: 'helper', state: 'ready', keyExpiresAt, ... }]
|
|
93
|
+
await renewAgentKey({ store, session: person, password, name: 'helper' }); // { agent, previousKey }
|
|
94
|
+
await removeAgent({ store, session: person, name: 'helper' });
|
|
95
|
+
```
|
|
96
|
+
|
|
97
|
+
- **What it may do.** `createAgent` creates the principal without the person's admin flag (`useAdminOwner: false`, also on every scope call, whose own default is true). By default its org scope masks `manage_database`, so it cannot change the schema; `allowSchemaChanges`, `grantSchemaChanges` and `revokeSchemaChanges` set or clear that mask. `organization` holds it to one organization. A key for a principal needs a recent password sign-in, so `createAgent` and `renewAgentKey` take the person's `password`, sign in afresh (the stored session names the account and the backend), and end that sign-in on the server when done; a wrong password is a `SignInError`. `grantSchemaChanges`, `revokeSchemaChanges` and `removeAgent` go with the person's stored key.
|
|
98
|
+
- **Its key.** `createAgent` caps every key of the principal at 30 days (`apiKeyMaxDuration`), then creates one key for it that asks for 30 days. The key is stored in a 0600 file under the person's context (`<config>/agents/<context>/<name>.json`), bound to the five endpoints it was issued for, like a person's session. `renewAgentKey` gives the same principal a new 30-day key, so it keeps its grants: it stores the new key, drops the cached token, then revokes the old key, which ends every token minted with it (`previousKey` says whether that worked).
|
|
99
|
+
- **Its cached token.** The cache only saves a mint: a token is used only for the key that minted it, so reading, writing or deleting the cache never fails an operation, and a token that cannot be cached is minted again next time.
|
|
100
|
+
- **Its access tokens.** This package uses the key only to mint access tokens for the principal. The backend accepts the key itself on requests too, so whoever holds it can act as the agent until it ends, `renewAgentKey` replaces it, or `removeAgent` deletes the agent; it stays in its 0600 file. `agentSession` gives the cached access token while more than 30 s of it is left, else it mints a new one and caches it in a 0600 file (`<cache>/agents/<context>/<name>.json`), written through a temporary file and a rename. There is no lock: a token may be used many times, so processes that mint at once all work, and the cache keeps one of their tokens. The refresh token the backend makes with each mint is never asked for or stored. With `agent`, `sessionToolsHost`'s `account()` is asynchronous and gives that token; requests never carry the key.
|
|
101
|
+
- **A refused token.** After the backend refuses the agent's access token as signed out, pass it back once: `agentSession({ store, name, rejectedToken })` drops it from the cache and mints one token from the key, or uses the token another process already minted. It never retries on its own. If the key is refused too, the answer is `set-up-again`.
|
|
102
|
+
- **When it stops.** `agentSession` answers `agent-unusable` with `set-up-again` once the key has ended or the backend refuses it (the fix is to renew the key), `unreadable` when the record cannot be read (the fix is to remove and add the agent), and `mint-failed` (retry) when no token could be minted. The person's `signOut` leaves every agent working until its key ends; `listAgents` says which agents those are, and `removeAgent` deletes the principal, which ends its key and every token minted with it at once. When its entry cannot be removed after that, the answer is `entry-left`, and removing the agent again removes it.
|
|
103
|
+
- **A record edited by hand** that no longer parses makes the agent `unreadable`; `removeAgent` then removes the entry, and the principal is deleted in the app.
|
|
104
|
+
- **Managing agents** needs the person's own stored session; an agent, or a credential from the environment, gets `AgentError` `not-a-person`. A refusal for a recent sign-in is `step-up-required`, and the fix is to sign in again.
|
|
105
|
+
|
|
106
|
+
## Backends
|
|
107
|
+
|
|
108
|
+
`backendFromEndpoints({ api, auth?, modules?, agent?, compute? })` builds a backend. Every endpoint is https, or plain http on this machine only (a host whose last label is localhost, an address in 127/8, or ::1): plain http to another host would send the password and keys unencrypted, so it is refused (`EndpointError` with the reason `insecure`). A `BackendConfig` is made only by `backendFromEndpoints` or by reading the store, which checks a stored context the same way (one that fails is `invalid-backend`), so no request goes to an endpoint that was not checked. A request that carries a password or a key never follows a redirect: the error names where the server pointed, to use as the endpoint if it is the right one. A plane that is not given is derived from the api host only when the host is `api.<rest>` (`api.example.com` gives `auth.example.com`). Any other host must give every plane, so a password never goes to a host the caller did not name. It throws an `EndpointError` (`reason`: `not-a-url`, `scheme`, `userinfo` or `not-derivable`) for anything else; only `http` and `https` are accepted, and a user name or password in a URL is refused.
|
|
109
|
+
|
|
110
|
+
A backend is a named context in the store, named after the api host without a leading `api.` (`https://api.example.com/graphql` is `example.com`). A context name is the stem of a file in the store, so every function that takes one checks it first with `checkContextName`: 1 to 100 characters, lower-case letters, digits, `.`, `-` and `_`, starting with a letter or a digit, with no `..`. Upper case is refused so that two names never reach one file on a disk that ignores letter case (macOS): `PROD` cannot delete the file of `prod`. A bad name throws `ContextNameError` before any file is touched, and `contextNameFor` only produces names that pass. `listBackends` lists a stored context whose name does not pass, for example one with upper-case letters that another program wrote, as `status: 'invalid-name'` with the `reason`, and goes on with the others; no function acts on it, so it is removed by hand (the file under `<base>/.constructive/config/contexts/`). `listBackends`, `readBackend`, `addBackend`, `selectBackend` and `removeBackend` manage the contexts. No function drops a stored session while its key stays valid: `addBackend` keeps the session of a context when it was issued for exactly the new five endpoints, and otherwise throws `ContextInUseError`, as `removeBackend` does while any session is filed under the context. `signOut` first, which clears the session and revokes its key (check `key`: a revoke that failed leaves the key valid until it ends); `signIn` replaces a session of another backend itself, and revokes that session's key once the new session is stored.
|
|
111
|
+
|
|
112
|
+
## Operations
|
|
113
|
+
|
|
114
|
+
Every operation that changes the backend and the store runs as steps with one commit point. Before the commit, a failed step undoes the steps done so far, last first, and the error says what was undone; after the commit nothing is undone, and what is left cannot fail the operation.
|
|
115
|
+
|
|
116
|
+
| Operation | Steps before the commit (undo) | Commit | After the commit |
|
|
117
|
+
| --- | --- | --- | --- |
|
|
118
|
+
| `signIn` | sign in (end it), make a key (revoke it), store the endpoints (put the old ones back), choose the context (choose the old one) | store the session | revoke the replaced key, end the sign-in |
|
|
119
|
+
| `signOut` | none | clear the session | revoke its key |
|
|
120
|
+
| `createAgent` | create the principal (delete it), set its scope, cap its keys, create its key | store the agent | none |
|
|
121
|
+
| `renewAgentKey` | create the new key (revoke it) | store it | drop the cached token, revoke the old key |
|
|
122
|
+
| `grantSchemaChanges`, `revokeSchemaChanges` | change the scope (set it back) | store the record | none |
|
|
123
|
+
| `removeAgent` | none | delete the principal | remove the entry (`entry-left` when it fails) |
|
|
124
|
+
|
|
125
|
+
## Environment
|
|
126
|
+
|
|
127
|
+
`getConstructiveEnv(env?)` is the one reader of these variables: it returns the `CONSTRUCTIVE_*` variables of `env`, or of the process when none is given, and every function here takes that view (`env` in `resolveSession`, `agentBinding`, `agentSession`, `sessionToolsHost`, `stashBaseDir`), so a host or a test passes its own.
|
|
128
|
+
|
|
129
|
+
- `CONSTRUCTIVE_STASH_DIR` sets the base directory of the store (`<dir>/.constructive/`) in place of the home directory, for tests and isolated runs. Constructive Desktop reads the same variable. An empty value is an error. `stashDirectories(env)` lists every directory the store uses (root, config, cache, data, logs, tmp) from the same resolution as `openStore`, without creating any, so a caller can refuse a path inside the store.
|
|
130
|
+
- `CONSTRUCTIVE_USER_ID` and `CONSTRUCTIVE_ACCESS_TOKEN`, with an optional `CONSTRUCTIVE_API_KEY`, give the credential. Any one of them selects the environment as the credential source, so the set must be complete, and `CONSTRUCTIVE_API_ENDPOINT` must name the backend.
|
|
131
|
+
- `CONSTRUCTIVE_API_ENDPOINT` picks the backend. `CONSTRUCTIVE_AUTH_ENDPOINT`, `CONSTRUCTIVE_MODULES_ENDPOINT`, `CONSTRUCTIVE_AGENT_ENDPOINT` and `CONSTRUCTIVE_COMPUTE_ENDPOINT` give one plane each, and are required for an api host that is not `api.<rest>`. A plane variable without `CONSTRUCTIVE_API_ENDPOINT` is an error.
|
|
132
|
+
|
|
133
|
+
The store file `<base>/.constructive/config/credentials.json` holds the tokens in plaintext with mode `0600`.
|
|
134
|
+
|
|
135
|
+
---
|
|
136
|
+
|
|
137
|
+
## Education and Tutorials
|
|
138
|
+
|
|
139
|
+
1. 🚀 [Quickstart: Getting Up and Running](https://constructive.io/learn/quickstart)
|
|
140
|
+
Get started with modular databases in minutes. Install prerequisites and deploy your first module.
|
|
141
|
+
|
|
142
|
+
2. 📦 [Modular PostgreSQL Development with Database Packages](https://constructive.io/learn/modular-postgres)
|
|
143
|
+
Learn to organize PostgreSQL projects with pgpm workspaces and reusable database modules.
|
|
144
|
+
|
|
145
|
+
3. ✏️ [Authoring Database Changes](https://constructive.io/learn/authoring-database-changes)
|
|
146
|
+
Master the workflow for adding, organizing, and managing database changes with pgpm.
|
|
147
|
+
|
|
148
|
+
4. 🧪 [End-to-End PostgreSQL Testing with TypeScript](https://constructive.io/learn/e2e-postgres-testing)
|
|
149
|
+
Master end-to-end PostgreSQL testing with ephemeral databases, RLS testing, and CI/CD automation.
|
|
150
|
+
|
|
151
|
+
5. ⚡ [Supabase Testing](https://constructive.io/learn/supabase)
|
|
152
|
+
Use TypeScript-first tools to test Supabase projects with realistic RLS, policies, and auth contexts.
|
|
153
|
+
|
|
154
|
+
6. 💧 [Drizzle ORM Testing](https://constructive.io/learn/drizzle-testing)
|
|
155
|
+
Run full-stack tests with Drizzle ORM, including database setup, teardown, and RLS enforcement.
|
|
156
|
+
|
|
157
|
+
7. 🔧 [Troubleshooting](https://constructive.io/learn/troubleshooting)
|
|
158
|
+
Common issues and solutions for pgpm, PostgreSQL, and testing.
|
|
159
|
+
|
|
160
|
+
## Related Constructive Tooling
|
|
161
|
+
|
|
162
|
+
### 📦 Package Management
|
|
163
|
+
|
|
164
|
+
* [pgpm](https://github.com/constructive-io/constructive/tree/main/pgpm/pgpm): **🖥️ PostgreSQL Package Manager** for modular Postgres development. Works with database workspaces, scaffolding, migrations, seeding, and installing database packages.
|
|
165
|
+
|
|
166
|
+
### 🧪 Testing
|
|
167
|
+
|
|
168
|
+
* [pgsql-test](https://github.com/constructive-io/constructive/tree/main/postgres/pgsql-test): **📊 Isolated testing environments** with per-test transaction rollbacks—ideal for integration tests, complex migrations, and RLS simulation.
|
|
169
|
+
* [pglite-test](https://github.com/constructive-io/constructive/tree/main/postgres/pglite-test): **🪶 Drop-in pgsql-test replacement backed by PGlite** — in-process Postgres, no server required, instance-per-suite isolation.
|
|
170
|
+
* [pgsql-seed](https://github.com/constructive-io/constructive/tree/main/postgres/pgsql-seed): **🌱 PostgreSQL seeding utilities** for CSV, JSON, SQL data loading, and pgpm deployment.
|
|
171
|
+
* [supabase-test](https://github.com/constructive-io/constructive/tree/main/postgres/supabase-test): **🧪 Supabase-native test harness** preconfigured for the local Supabase stack—per-test rollbacks, JWT/role context helpers, and CI/GitHub Actions ready.
|
|
172
|
+
* [graphile-test](https://github.com/constructive-io/constructive/tree/main/graphile/graphile-test): **🔐 Authentication mocking** for Graphile-focused test helpers and emulating row-level security contexts.
|
|
173
|
+
* [pg-query-context](https://github.com/constructive-io/constructive/tree/main/postgres/pg-query-context): **🔒 Session context injection** to add session-local context (e.g., `SET LOCAL`) into queries—ideal for setting `role`, `jwt.claims`, and other session settings.
|
|
174
|
+
|
|
175
|
+
### 🧠 Parsing & AST
|
|
176
|
+
|
|
177
|
+
* [pgsql-parser](https://www.npmjs.com/package/pgsql-parser): **🔄 SQL conversion engine** that interprets and converts PostgreSQL syntax.
|
|
178
|
+
* [libpg-query-node](https://www.npmjs.com/package/libpg-query): **🌉 Node.js bindings** for `libpg_query`, converting SQL into parse trees.
|
|
179
|
+
* [pg-proto-parser](https://www.npmjs.com/package/pg-proto-parser): **📦 Protobuf parser** for parsing PostgreSQL Protocol Buffers definitions to generate TypeScript interfaces, utility functions, and JSON mappings for enums.
|
|
180
|
+
* [@pgsql/enums](https://www.npmjs.com/package/@pgsql/enums): **🏷️ TypeScript enums** for PostgreSQL AST for safe and ergonomic parsing logic.
|
|
181
|
+
* [@pgsql/types](https://www.npmjs.com/package/@pgsql/types): **📝 Type definitions** for PostgreSQL AST nodes in TypeScript.
|
|
182
|
+
* [@pgsql/utils](https://www.npmjs.com/package/@pgsql/utils): **🛠️ AST utilities** for constructing and transforming PostgreSQL syntax trees.
|
|
183
|
+
|
|
184
|
+
### 📚 Documentation & Skills
|
|
185
|
+
|
|
186
|
+
* [constructive-skills](https://github.com/constructive-io/constructive-skills): **📖 Platform documentation and AI agent skills** — feature catalog, blueprint reference, SDK guides (i18n, billing, limits, events, uploads, security, entities, search, AI), and deployment guides.
|
|
187
|
+
|
|
188
|
+
Install skills for AI coding agents:
|
|
189
|
+
|
|
190
|
+
```bash
|
|
191
|
+
# All platform skills (security, blueprints, codegen, billing, etc.)
|
|
192
|
+
npx skills add constructive-io/constructive-skills
|
|
193
|
+
|
|
194
|
+
# Individual repo skills (pgpm, safegres, testing, CLI, search, etc.)
|
|
195
|
+
npx skills add constructive-io/constructive --skill pgpm
|
|
196
|
+
npx skills add constructive-io/constructive --skill safegres
|
|
197
|
+
npx skills add constructive-io/constructive --skill constructive-testing
|
|
198
|
+
```
|
|
199
|
+
|
|
200
|
+
## Credits
|
|
201
|
+
|
|
202
|
+
**🛠 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).**
|
|
203
|
+
|
|
204
|
+
## Disclaimer
|
|
205
|
+
|
|
206
|
+
AS DESCRIBED IN THE LICENSES, THE SOFTWARE IS PROVIDED "AS IS", AT YOUR OWN RISK, AND WITHOUT WARRANTIES OF ANY KIND.
|
|
207
|
+
|
|
208
|
+
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.
|
|
@@ -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;
|
package/account-store.js
ADDED
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.isContextName = exports.ContextNameError = exports.STASH_DIR_ENV = exports.STASH_NAME = void 0;
|
|
4
|
+
exports.stashBaseDir = stashBaseDir;
|
|
5
|
+
exports.openStore = openStore;
|
|
6
|
+
exports.storeDirs = storeDirs;
|
|
7
|
+
exports.stashDirectories = stashDirectories;
|
|
8
|
+
exports.checkContextName = checkContextName;
|
|
9
|
+
exports.issuedForOf = issuedForOf;
|
|
10
|
+
exports.currentContextName = currentContextName;
|
|
11
|
+
exports.loadSession = loadSession;
|
|
12
|
+
exports.saveSession = saveSession;
|
|
13
|
+
exports.clearSession = clearSession;
|
|
14
|
+
const appstash_1 = require("appstash");
|
|
15
|
+
const env_1 = require("./env");
|
|
16
|
+
/**
|
|
17
|
+
* Directory identity shared by every Constructive binary and the desktop app,
|
|
18
|
+
* so a sign-in through one is a sign-in through all of them.
|
|
19
|
+
*/
|
|
20
|
+
exports.STASH_NAME = 'constructive';
|
|
21
|
+
var env_2 = require("./env");
|
|
22
|
+
Object.defineProperty(exports, "STASH_DIR_ENV", { enumerable: true, get: function () { return env_2.STASH_DIR_ENV; } });
|
|
23
|
+
/** An empty value is an error: treating it as unset would open the real store under the home directory. */
|
|
24
|
+
function stashBaseDir(env = (0, env_1.getConstructiveEnv)()) {
|
|
25
|
+
const dir = env[env_1.STASH_DIR_ENV];
|
|
26
|
+
if (dir === '') {
|
|
27
|
+
throw new Error(`${env_1.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.`);
|
|
28
|
+
}
|
|
29
|
+
return dir;
|
|
30
|
+
}
|
|
31
|
+
const STORE_DIRS = new WeakMap();
|
|
32
|
+
/**
|
|
33
|
+
* The store under `baseDir`, or under the home directory when `baseDir` is
|
|
34
|
+
* undefined. Called with no argument, it reads CONSTRUCTIVE_STASH_DIR from the
|
|
35
|
+
* process's environment; a caller that resolved an injected environment passes its
|
|
36
|
+
* result, undefined included, so the ambient variable never overrides it.
|
|
37
|
+
*/
|
|
38
|
+
function openStore(...args) {
|
|
39
|
+
const baseDir = args.length ? args[0] : stashBaseDir();
|
|
40
|
+
const store = (0, appstash_1.createConfigStore)(exports.STASH_NAME, { stashName: exports.STASH_NAME, baseDir });
|
|
41
|
+
const { config, cache } = (0, appstash_1.appstash)(exports.STASH_NAME, { baseDir });
|
|
42
|
+
STORE_DIRS.set(store, { config, cache });
|
|
43
|
+
return store;
|
|
44
|
+
}
|
|
45
|
+
/**
|
|
46
|
+
* The directories of a store `openStore` opened: `config` holds files beside
|
|
47
|
+
* the credentials, `cache` files that may be deleted at any time.
|
|
48
|
+
*/
|
|
49
|
+
function storeDirs(store) {
|
|
50
|
+
const dirs = STORE_DIRS.get(store);
|
|
51
|
+
if (!dirs)
|
|
52
|
+
throw new Error('This store was not opened with openStore, so its directory is unknown. Open it with openStore().');
|
|
53
|
+
return dirs;
|
|
54
|
+
}
|
|
55
|
+
/**
|
|
56
|
+
* Every directory the store `openStore` opens uses (root, config, cache, data,
|
|
57
|
+
* logs, tmp), from the same appstash resolution, so a caller can refuse a path
|
|
58
|
+
* inside the store. Creates nothing.
|
|
59
|
+
*/
|
|
60
|
+
function stashDirectories(env = (0, env_1.getConstructiveEnv)()) {
|
|
61
|
+
const dirs = (0, appstash_1.appstash)(exports.STASH_NAME, { baseDir: stashBaseDir(env) });
|
|
62
|
+
return [...new Set([dirs.root, dirs.config, dirs.cache, dirs.data, dirs.logs, dirs.tmp])];
|
|
63
|
+
}
|
|
64
|
+
const CONTEXT_NAME = /^[a-z0-9][a-z0-9._-]{0,99}$/;
|
|
65
|
+
/** A context name that cannot name a file in the store's contexts directory. */
|
|
66
|
+
class ContextNameError extends Error {
|
|
67
|
+
value;
|
|
68
|
+
constructor(value) {
|
|
69
|
+
super(`"${value.length > 120 ? `${value.slice(0, 120)}…` : value}" is not a valid context name. ` +
|
|
70
|
+
'A context name has 1 to 100 characters: lower-case letters, digits, ".", "-" and "_", starting with a letter or a digit, with no "..".');
|
|
71
|
+
this.value = value;
|
|
72
|
+
this.name = 'ContextNameError';
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
exports.ContextNameError = ContextNameError;
|
|
76
|
+
/**
|
|
77
|
+
* A context name is the stem of a file in the store, so it is checked before
|
|
78
|
+
* any read or write: no separator, no `..`, no leading dot, and lower case
|
|
79
|
+
* only, so two names never reach one file on a disk that ignores letter case.
|
|
80
|
+
*/
|
|
81
|
+
const isContextName = (name) => typeof name === 'string' && CONTEXT_NAME.test(name) && !name.includes('..');
|
|
82
|
+
exports.isContextName = isContextName;
|
|
83
|
+
function checkContextName(name) {
|
|
84
|
+
if (!(0, exports.isContextName)(name))
|
|
85
|
+
throw new ContextNameError(String(name));
|
|
86
|
+
return name;
|
|
87
|
+
}
|
|
88
|
+
const BACKEND_KEYS = ['apiEndpoint', 'authEndpoint', 'modulesEndpoint', 'agentEndpoint', 'computeEndpoint'];
|
|
89
|
+
/** `value` as the five recorded endpoints, or undefined when it lacks one. */
|
|
90
|
+
function issuedForOf(value) {
|
|
91
|
+
if (!value || typeof value !== 'object')
|
|
92
|
+
return undefined;
|
|
93
|
+
const record = value;
|
|
94
|
+
if (!BACKEND_KEYS.every((key) => typeof record[key] === 'string' && record[key] !== ''))
|
|
95
|
+
return undefined;
|
|
96
|
+
return Object.fromEntries(BACKEND_KEYS.map((key) => [key, record[key]]));
|
|
97
|
+
}
|
|
98
|
+
/**
|
|
99
|
+
* Sessions live in the shared Constructive stash, as the credentials of a
|
|
100
|
+
* backend context. The store owns the file layout, the atomic 0600 writes and
|
|
101
|
+
* the at-rest encoding; this module only maps between its `ContextCredentials`
|
|
102
|
+
* and the session shape callers pass around.
|
|
103
|
+
*/
|
|
104
|
+
function currentContextName(store) {
|
|
105
|
+
const name = store.loadSettings().currentContext;
|
|
106
|
+
// A name this package never writes, such as one another tool stored, is no context of ours: nothing is chosen.
|
|
107
|
+
if (!(0, exports.isContextName)(name))
|
|
108
|
+
return null;
|
|
109
|
+
return store.loadContext(name) ? name : null;
|
|
110
|
+
}
|
|
111
|
+
/** The active context; a session is never filed under a backend nobody chose. */
|
|
112
|
+
function ensureContextName(store) {
|
|
113
|
+
const name = currentContextName(store);
|
|
114
|
+
if (!name)
|
|
115
|
+
throw new Error('No backend chosen: select a backend before saving a session.');
|
|
116
|
+
return name;
|
|
117
|
+
}
|
|
118
|
+
function loadSession(store, context) {
|
|
119
|
+
const contextName = context === undefined ? currentContextName(store) : checkContextName(context);
|
|
120
|
+
if (!contextName)
|
|
121
|
+
return null;
|
|
122
|
+
const creds = store.getCredentials(contextName);
|
|
123
|
+
if (!creds?.token || !creds.userId)
|
|
124
|
+
return null;
|
|
125
|
+
return {
|
|
126
|
+
userId: creds.userId,
|
|
127
|
+
email: creds.email ?? '',
|
|
128
|
+
accessToken: creds.token,
|
|
129
|
+
accessTokenExpiresAt: creds.expiresAt,
|
|
130
|
+
apiKey: creds.apiKey,
|
|
131
|
+
keyId: creds.keyId,
|
|
132
|
+
apiKeyExpiresAt: creds.apiKeyExpiresAt,
|
|
133
|
+
signedInAt: creds.signedInAt ?? 0,
|
|
134
|
+
...(issuedForOf(creds.issuedFor) ? { issuedFor: issuedForOf(creds.issuedFor) } : {}),
|
|
135
|
+
...(typeof creds.authEndpoint === 'string' && creds.authEndpoint ? { authEndpoint: creds.authEndpoint } : {})
|
|
136
|
+
};
|
|
137
|
+
}
|
|
138
|
+
/**
|
|
139
|
+
* `context` names the backend the session belongs to; it does not have to exist
|
|
140
|
+
* as a context yet, so a sign-in can be filed before the backend is committed
|
|
141
|
+
* and a failed sign-in leaves nothing behind.
|
|
142
|
+
*/
|
|
143
|
+
function saveSession(store, session, context) {
|
|
144
|
+
const credentials = {
|
|
145
|
+
token: session.accessToken,
|
|
146
|
+
expiresAt: session.accessTokenExpiresAt,
|
|
147
|
+
userId: session.userId,
|
|
148
|
+
email: session.email,
|
|
149
|
+
apiKey: session.apiKey,
|
|
150
|
+
keyId: session.keyId,
|
|
151
|
+
apiKeyExpiresAt: session.apiKeyExpiresAt,
|
|
152
|
+
signedInAt: session.signedInAt,
|
|
153
|
+
...(session.issuedFor ? { issuedFor: session.issuedFor } : {}),
|
|
154
|
+
...(session.issuedFor || session.authEndpoint ? { authEndpoint: session.issuedFor?.authEndpoint ?? session.authEndpoint } : {})
|
|
155
|
+
};
|
|
156
|
+
store.setCredentials(context === undefined ? ensureContextName(store) : checkContextName(context), credentials);
|
|
157
|
+
}
|
|
158
|
+
function clearSession(store, context) {
|
|
159
|
+
const contextName = context === undefined ? currentContextName(store) : checkContextName(context);
|
|
160
|
+
if (contextName)
|
|
161
|
+
store.removeCredentials(contextName);
|
|
162
|
+
}
|
package/agent-store.d.ts
ADDED
|
@@ -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;
|