@open33/harness-credentials 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/src/index.ts ADDED
@@ -0,0 +1,307 @@
1
+ /**
2
+ * Service Definition for the credential-reference capability seam (`ctx.credentials`). Settings and composition files carry
3
+ * *references* to secrets — environment-variable names — while providers own
4
+ * the actual values and their storage. Consumers resolve a reference once per
5
+ * operation, so a changed credential reaches the next operation without any
6
+ * plugin restart, and configuration surfaces describe a reference without
7
+ * ever seeing its full value.
8
+ * @module @open33/harness-credentials
9
+ */
10
+
11
+ import { Context, Service } from '@open33/cordis'
12
+ import { brandString } from '@open33/harness-brand'
13
+ import type { CredentialInfo, CredentialKey, CredentialRecord, CredentialRef } from './types.ts'
14
+
15
+ export type {
16
+ ApiKeyRecord, CredentialInfo, CredentialKey, CredentialRecord, CredentialRef, GrantRecord,
17
+ } from './types.ts'
18
+
19
+ const REF_PATTERN = /^[A-Za-z_][A-Za-z0-9_]*$/
20
+
21
+ /** Both halves of a {@link CredentialKey}; the `/` between them is what keeps it out of {@link REF_PATTERN}. */
22
+ const KEY_SEGMENT_PATTERN = /^[a-z][a-z0-9-]*$/
23
+
24
+ /**
25
+ * Brand a raw string as a {@link CredentialRef}.
26
+ * @param value - candidate reference; a POSIX shell identifier such as `OPEN33_API_KEY`.
27
+ * @returns the branded reference.
28
+ */
29
+ export function credentialRef(value: string): CredentialRef {
30
+ if (!isCredentialRefName(value)) {
31
+ throw new TypeError(`credential ref "${value}" must match ${String(REF_PATTERN)}`)
32
+ }
33
+ return brandString<CredentialRef>(value)
34
+ }
35
+
36
+ /**
37
+ * Whether a raw string could name a reference at all. Consumers that receive
38
+ * environment-variable names from somewhere else — a provider library's own
39
+ * ambient discovery, a hook payload — ask this before resolving, because a name
40
+ * outside the grammar has no reference to miss and should read as "not set"
41
+ * rather than as a thrown error.
42
+ * @param value - candidate reference.
43
+ * @returns true when {@link credentialRef} would accept it.
44
+ */
45
+ export function isCredentialRefName(value: string): boolean {
46
+ return REF_PATTERN.test(value)
47
+ }
48
+
49
+ /**
50
+ * Whether a raw string could be a {@link credentialKey} segment at all.
51
+ * Consumers whose addressing units come from somewhere else — a settings dict
52
+ * key, a library's own provider id — ask this before building a key, because a
53
+ * unit outside the grammar can never have stored a record and should read as
54
+ * "nothing stored" rather than as a thrown error.
55
+ * @param value - candidate segment.
56
+ * @returns true when {@link credentialKey} would accept it as either segment.
57
+ */
58
+ export function isCredentialKeySegment(value: string): boolean {
59
+ return KEY_SEGMENT_PATTERN.test(value)
60
+ }
61
+
62
+ /**
63
+ * Brand a scope and an id as a {@link CredentialKey}.
64
+ * @param scope - the owning plugin's registered name, such as `llm-pi-ai`.
65
+ * @param id - that plugin's own addressing unit, such as a provider route key.
66
+ * @returns the branded key.
67
+ * @throws TypeError when either segment is not a lowercase hyphenated identifier.
68
+ */
69
+ export function credentialKey(scope: string, id: string): CredentialKey {
70
+ for (const segment of [scope, id]) {
71
+ if (!KEY_SEGMENT_PATTERN.test(segment)) {
72
+ throw new TypeError(`credential key segment "${segment}" must match ${String(KEY_SEGMENT_PATTERN)}`)
73
+ }
74
+ }
75
+ return brandString<CredentialKey>(`${scope}/${id}`)
76
+ }
77
+
78
+ /**
79
+ * Brand a stored `<scope>/<id>` string as a {@link CredentialKey}. This is the
80
+ * read half of {@link credentialKey}, for a provider admitting keys off disk.
81
+ * @param value - candidate key in its joined form.
82
+ * @returns the branded key.
83
+ * @throws TypeError when the value is not exactly two valid segments.
84
+ */
85
+ export function parseCredentialKey(value: string): CredentialKey {
86
+ const segments = value.split('/')
87
+ const [scope, id] = segments
88
+ if (segments.length !== 2 || scope === undefined || id === undefined) {
89
+ throw new TypeError(`credential key "${value}" must be "<scope>/<id>"`)
90
+ }
91
+ return credentialKey(scope, id)
92
+ }
93
+
94
+ /**
95
+ * The owning plugin's name for one key. A record whose scope names no
96
+ * currently registered owner is an orphan, which a configuration surface must
97
+ * report as such rather than as a working credential.
98
+ * @param key - the key to read.
99
+ * @returns the scope segment.
100
+ */
101
+ export function credentialKeyScope(key: CredentialKey): string {
102
+ // The brand's only constructors both validate two segments, so the split
103
+ // cannot come back short here.
104
+ return key.slice(0, key.indexOf('/'))
105
+ }
106
+
107
+ /**
108
+ * The owning plugin's own addressing unit for one key — the half that plugin
109
+ * chose, such as a provider route.
110
+ * @param key - the key to read.
111
+ * @returns the id segment.
112
+ */
113
+ export function credentialKeyId(key: CredentialKey): string {
114
+ return key.slice(key.indexOf('/') + 1)
115
+ }
116
+
117
+ /** One resolved credential value and the source layer that supplied it. */
118
+ export interface ResolvedCredential {
119
+ /** The non-empty secret value. */
120
+ value: string
121
+ /** Provider-defined source layer id (the local provider uses `env`, `file`, `project-env`, and `user-env`). */
122
+ source: string
123
+ }
124
+
125
+ /** Presence and writability facts for one record, safe for configuration UIs — never the value. */
126
+ export interface CredentialRecordInfo {
127
+ /**
128
+ * Whether a record is stored. Unlike a reference, presence alone answers
129
+ * this: an {@link ApiKeyRecord} carrying neither a key nor environment
130
+ * values states that its owner confirmed ambient authentication, which is
131
+ * configured, not blank.
132
+ */
133
+ configured: boolean
134
+ /** Discriminant of the stored record; absent while none is stored. */
135
+ kind?: CredentialRecord['kind']
136
+ /** Whether {@link CredentialProvider.modifyRecord} would currently succeed. */
137
+ writable: boolean
138
+ }
139
+
140
+ /** One stored record's address and tag, for enumeration — never its value. */
141
+ export interface CredentialRecordEntry {
142
+ /** The record's address. */
143
+ key: CredentialKey
144
+ /** Discriminant of the stored record. */
145
+ kind: CredentialRecord['kind']
146
+ }
147
+
148
+ declare module '@open33/cordis' {
149
+ interface Context {
150
+ credentials: CredentialProvider
151
+ }
152
+ }
153
+
154
+ /**
155
+ * Abstract credential service over two key spaces that answer two questions.
156
+ *
157
+ * A {@link CredentialRef} answers "what is behind this environment-variable
158
+ * name": the provider-managed store first, then ambient fallbacks such as the
159
+ * process environment and `.env` files. One seam-wide rule binds that half: an
160
+ * empty stored value is absent everywhere — `resolve` skips it, `describe`
161
+ * reports it unconfigured — so a blank never masquerades as a configured
162
+ * secret.
163
+ *
164
+ * A {@link CredentialKey} answers "what credential does this plugin hold for
165
+ * this id". Nothing can layer here — an authorization grant has no
166
+ * environment to be read from — so presence of the record is the whole fact,
167
+ * and {@link modifyRecord} is the only write path because a correct write
168
+ * depends on the current value (a token refresh is read-decide-replace under
169
+ * one lock).
170
+ */
171
+ export abstract class CredentialProvider extends Service {
172
+ constructor(ctx: Context) {
173
+ super(ctx, 'credentials')
174
+ }
175
+
176
+ /**
177
+ * Resolve one reference to its current value. Resolution is per call:
178
+ * consumers re-resolve at each operation and must not cache across
179
+ * operations — that per-operation read is what makes a changed credential
180
+ * reach the next operation without a restart.
181
+ * @param ref - the reference to resolve.
182
+ * @returns the value and its source, or `undefined` while unconfigured.
183
+ */
184
+ abstract resolve(ref: CredentialRef): Promise<ResolvedCredential | undefined>
185
+
186
+ /**
187
+ * Describe one reference for configuration surfaces without exposing the
188
+ * full value.
189
+ * @param ref - the reference to describe.
190
+ * @returns configured state, supplying source, writability, and optional masked preview.
191
+ */
192
+ abstract describe(ref: CredentialRef): Promise<CredentialInfo>
193
+
194
+ /**
195
+ * Durably store one value in the provider-managed writable source. The stored
196
+ * value takes precedence over ambient fallbacks, and empty values are
197
+ * rejected (use {@link unset}).
198
+ * @param ref - the reference to store.
199
+ * @param value - the non-empty secret value.
200
+ */
201
+ abstract set(ref: CredentialRef, value: string): Promise<void>
202
+
203
+ /**
204
+ * Remove one reference from the provider-managed writable source; removing
205
+ * an absent reference is a no-op. Ambient fallback layers may become
206
+ * effective again after removal.
207
+ * @param ref - the reference to remove.
208
+ */
209
+ abstract unset(ref: CredentialRef): Promise<void>
210
+
211
+ /**
212
+ * Read one stored record. The value is returned as its owner wrote it; a
213
+ * {@link GrantRecord} payload is not interpreted on the way out.
214
+ * @param key - the record to read.
215
+ * @returns the record, or `undefined` while none is stored.
216
+ */
217
+ abstract readRecord(key: CredentialKey): Promise<CredentialRecord | undefined>
218
+
219
+ /**
220
+ * Describe one record for configuration surfaces without exposing its value.
221
+ * @param key - the record to describe.
222
+ * @returns presence, discriminant, and writability.
223
+ */
224
+ abstract describeRecord(key: CredentialKey): Promise<CredentialRecordInfo>
225
+
226
+ /**
227
+ * Enumerate every stored record's address and tag. Unlike the reference
228
+ * half, which has no enumeration because configuration surfaces learn which
229
+ * references exist from settings schemas, records have no such discovery
230
+ * path: a surface that cannot list them cannot show what a user is
231
+ * authorized for, nor find an orphan left by an uninstalled plugin.
232
+ * @returns every stored record, values excluded.
233
+ */
234
+ abstract listRecords(): Promise<readonly CredentialRecordEntry[]>
235
+
236
+ /**
237
+ * Serialized read-modify-write over one record — the only write path.
238
+ * `mutate` sees the record as it stands at the moment the write is
239
+ * exclusive, and returning `undefined` leaves the entry untouched. Exclusion
240
+ * holds across processes where the backing store supports it, which is what
241
+ * makes a token refresh safe: two processes rotating one refresh token
242
+ * concurrently would otherwise lose whichever wrote first.
243
+ * @param key - the record to modify.
244
+ * @param mutate - receives the current record and returns its replacement, or `undefined` to leave it.
245
+ * @returns the record after the write, or the current one when `mutate` declined.
246
+ */
247
+ abstract modifyRecord(
248
+ key: CredentialKey,
249
+ mutate: (current: CredentialRecord | undefined) => Promise<CredentialRecord | undefined>,
250
+ ): Promise<CredentialRecord | undefined>
251
+
252
+ /**
253
+ * Remove one record; removing an absent record is a no-op.
254
+ * @param key - the record to remove.
255
+ */
256
+ abstract deleteRecord(key: CredentialKey): Promise<void>
257
+
258
+ /**
259
+ * Fan `credentials/reference-updated` out with contained listener failures: every
260
+ * listener runs, and a sync throw or async rejection is logged without
261
+ * changing the committed operation's outcome. Providers call this only after the write or
262
+ * reload actually committed, so a broken observer can never make a durable
263
+ * change look failed.
264
+ * @param ref - the reference whose stored value changed.
265
+ */
266
+ protected notifyUpdated(ref: CredentialRef): void {
267
+ this.fanOut('credentials/reference-updated', ref)
268
+ }
269
+
270
+ /**
271
+ * Fan `credentials/record-updated` out on exactly the terms
272
+ * {@link notifyUpdated} documents, for the record half of the seam.
273
+ * @param key - the record whose stored value changed.
274
+ */
275
+ protected notifyRecordUpdated(key: CredentialKey): void {
276
+ this.fanOut('credentials/record-updated', key)
277
+ }
278
+
279
+ /* jscpd:ignore-start -- deliberate symmetry with the settings seam's commit
280
+ fan-out: the contained-dispatch shape is the reviewed listener-lifecycle
281
+ contract, and extracting it would couple the two seams' event semantics. */
282
+ /** The contained dispatch both notifications run through; see {@link notifyUpdated}. */
283
+ private fanOut(event: 'credentials/reference-updated' | 'credentials/record-updated', subject: string): void {
284
+ const args = [event, subject]
285
+ for (const listener of this.ctx.events.dispatch('emit', args) as Array<(...listenerArgs: unknown[]) => unknown>) {
286
+ try {
287
+ const returned = listener(subject)
288
+ if (returned != null && typeof (returned as PromiseLike<unknown>).then === 'function') {
289
+ void Promise.resolve(returned as PromiseLike<unknown>).then(undefined, (error: unknown) => {
290
+ this.warnListenerFailure(event, subject, error)
291
+ })
292
+ }
293
+ } catch (error) {
294
+ this.warnListenerFailure(event, subject, error)
295
+ }
296
+ }
297
+ }
298
+ /* jscpd:ignore-end */
299
+
300
+ /** Contained-listener diagnostic shared by the sync and async failure paths. */
301
+ private warnListenerFailure(event: string, subject: string, error: unknown): void {
302
+ this.ctx.logger.warn('credentials: a %s listener for "%s" failed', event, subject)
303
+ this.ctx.logger.warn(error)
304
+ }
305
+ }
306
+
307
+ export default CredentialProvider
package/src/types.ts ADDED
@@ -0,0 +1,102 @@
1
+ /**
2
+ * Client-safe type surface of the credential seam: the two key brands, the
3
+ * stored-record union, the reference view crossing the Remote wire, and the
4
+ * seam's Cordis event declarations. Types only — no runtime code, and nothing
5
+ * here reaches a Host-only symbol, so a Client compilation face reads exactly
6
+ * the signature the Host emits.
7
+ *
8
+ * @module @open33/harness-credentials/types
9
+ */
10
+
11
+ import type { Branded } from '@open33/harness-brand'
12
+
13
+ /** Nominal reference to one credential: a POSIX-style environment-variable name. */
14
+ export type CredentialRef = Branded<'CredentialRef'>
15
+
16
+ /**
17
+ * Nominal address of one stored credential record: `<scope>/<id>`, where
18
+ * `scope` is the registered name of the plugin that owns the record and `id`
19
+ * is that plugin's own addressing unit (an LLM adapter uses its provider route
20
+ * key).
21
+ *
22
+ * The scope is the owner rather than the domain because a record's payload is
23
+ * written in its owner's format: two plugins serving the same provider name
24
+ * would otherwise read each other's payload, and a record left behind by an
25
+ * uninstalled plugin could not be told apart from a live one. The `/` also
26
+ * keeps this grammar disjoint from {@link CredentialRef}, so the two key
27
+ * spaces can never collide.
28
+ */
29
+ export type CredentialKey = Branded<'CredentialKey'>
30
+
31
+ /**
32
+ * A credential the harness itself understands: an api key, provider
33
+ * environment values, or both. Either field may be absent — a record carrying
34
+ * neither states that the owner confirmed this route authenticates from its
35
+ * own ambient discovery, which is a different fact from having no record.
36
+ */
37
+ export interface ApiKeyRecord {
38
+ /** Discriminant. */
39
+ readonly kind: 'api-key'
40
+ /** The non-empty secret value, when this credential is a key at all. */
41
+ readonly key?: string
42
+ /** Provider environment values such as `AWS_PROFILE`; names are POSIX identifiers. */
43
+ readonly env?: Readonly<Record<string, string>>
44
+ }
45
+
46
+ /**
47
+ * The product of one authorization grant, kept verbatim for its owner. The
48
+ * seam never reads, validates, or reshapes {@link payload}: it is written in
49
+ * the owning plugin's format and only that plugin can interpret it. The single
50
+ * constraint is that it survives a JSON round trip.
51
+ */
52
+ export interface GrantRecord {
53
+ /** Discriminant. */
54
+ readonly kind: 'grant'
55
+ /** Owner-defined JSON value; opaque to the seam and to every other plugin. */
56
+ readonly payload: unknown
57
+ }
58
+
59
+ /** One durable credential record, tagged by what the seam may do with it. */
60
+ export type CredentialRecord = ApiKeyRecord | GrantRecord
61
+
62
+ /**
63
+ * Configuration facts and an optional provider-masked preview for one
64
+ * reference. The full credential is never part of this view.
65
+ */
66
+ export interface CredentialInfo {
67
+ /** Whether resolving the reference would currently return a value. */
68
+ configured: boolean
69
+ /** Source layer currently supplying the value; absent while unconfigured. */
70
+ source?: string
71
+ /** Whether the active provider can write this reference. */
72
+ writable: boolean
73
+ /** Provider-generated masked preview of a stored value; never the full value. */
74
+ masked?: string
75
+ }
76
+
77
+ declare module '@open33/cordis' {
78
+ interface Events {
79
+ /**
80
+ * Committed change to a provider-managed credential source: a `set`, an
81
+ * `unset`, or an external edit observed in storage. Ambient
82
+ * process-environment changes are not observable and never emit. Listener
83
+ * failures are contained and logged — a sync throw and an async rejection
84
+ * alike — without changing the committed operation's outcome.
85
+ * @param ref - the reference whose stored value changed.
86
+ * @mode emit
87
+ */
88
+ 'credentials/reference-updated'(ref: CredentialRef): void
89
+
90
+ /**
91
+ * Committed change to a stored credential record: a `modifyRecord` that
92
+ * wrote, a `deleteRecord` that removed, or an external edit observed in
93
+ * storage. Separate from `credentials/reference-updated` because the two key
94
+ * grammars are disjoint — a listener that received both on one event could
95
+ * not tell which space a subject belongs to. Listener failures are
96
+ * contained on the same terms as `credentials/reference-updated`.
97
+ * @param key - the record whose stored value changed.
98
+ * @mode emit
99
+ */
100
+ 'credentials/record-updated'(key: CredentialKey): void
101
+ }
102
+ }