@yaks/connections 0.0.0-stage → 0.2.36

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 (184) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +609 -2
  3. package/_dist/authorize.d.ts +38 -0
  4. package/_dist/authorize.d.ts.map +1 -0
  5. package/_dist/authorize_cli.d.ts +12 -0
  6. package/_dist/authorize_cli.d.ts.map +1 -0
  7. package/_dist/brokers.d.ts +66 -0
  8. package/_dist/brokers.d.ts.map +1 -0
  9. package/_dist/catalog.d.ts +33 -0
  10. package/_dist/catalog.d.ts.map +1 -0
  11. package/_dist/cli.d.ts +3 -0
  12. package/_dist/cli.d.ts.map +1 -0
  13. package/_dist/clients.d.ts +18 -0
  14. package/_dist/clients.d.ts.map +1 -0
  15. package/_dist/connections.d.ts +296 -0
  16. package/_dist/connections.d.ts.map +1 -0
  17. package/_dist/effects.d.ts +15 -0
  18. package/_dist/effects.d.ts.map +1 -0
  19. package/_dist/field.d.ts +17 -0
  20. package/_dist/field.d.ts.map +1 -0
  21. package/_dist/form.d.ts +49 -0
  22. package/_dist/form.d.ts.map +1 -0
  23. package/_dist/given.d.ts +10 -0
  24. package/_dist/given.d.ts.map +1 -0
  25. package/_dist/graph.d.ts +15 -0
  26. package/_dist/graph.d.ts.map +1 -0
  27. package/_dist/history.d.ts +4 -0
  28. package/_dist/history.d.ts.map +1 -0
  29. package/_dist/identity.d.ts +9 -0
  30. package/_dist/identity.d.ts.map +1 -0
  31. package/_dist/integrations.d.ts +196 -0
  32. package/_dist/integrations.d.ts.map +1 -0
  33. package/_dist/loopback.d.ts +7 -0
  34. package/_dist/loopback.d.ts.map +1 -0
  35. package/_dist/mcp-retirement.d.ts +33 -0
  36. package/_dist/mcp-retirement.d.ts.map +1 -0
  37. package/_dist/mcp.d.ts +179 -0
  38. package/_dist/mcp.d.ts.map +1 -0
  39. package/_dist/mod.d.ts +70 -0
  40. package/_dist/mod.d.ts.map +1 -0
  41. package/_dist/paste.d.ts +13 -0
  42. package/_dist/paste.d.ts.map +1 -0
  43. package/_dist/requests.d.ts +30 -0
  44. package/_dist/requests.d.ts.map +1 -0
  45. package/_dist/services.d.ts +25 -0
  46. package/_dist/services.d.ts.map +1 -0
  47. package/_dist/sign-in.d.ts +9 -0
  48. package/_dist/sign-in.d.ts.map +1 -0
  49. package/_dist/signin-mail.d.ts +12 -0
  50. package/_dist/signin-mail.d.ts.map +1 -0
  51. package/_dist/signin.d.ts +19 -0
  52. package/_dist/signin.d.ts.map +1 -0
  53. package/_dist/sources.d.ts +61 -0
  54. package/_dist/sources.d.ts.map +1 -0
  55. package/_dist/tools.d.ts +3 -0
  56. package/_dist/tools.d.ts.map +1 -0
  57. package/_dist/views.d.ts +3 -0
  58. package/_dist/views.d.ts.map +1 -0
  59. package/_dist/vocab.d.ts +6 -0
  60. package/_dist/vocab.d.ts.map +1 -0
  61. package/_dist/yaks-app.d.ts +29 -0
  62. package/_dist/yaks-app.d.ts.map +1 -0
  63. package/anthropic.json +12 -0
  64. package/auth_command.js +69 -0
  65. package/auth_command.js.map +1 -0
  66. package/auth_command.ts +74 -0
  67. package/authorize.js +89 -0
  68. package/authorize.js.map +1 -0
  69. package/authorize.ts +138 -0
  70. package/authorize_cli.js +167 -0
  71. package/authorize_cli.js.map +1 -0
  72. package/authorize_cli.ts +211 -0
  73. package/brokers.js +318 -0
  74. package/brokers.js.map +1 -0
  75. package/brokers.ts +423 -0
  76. package/canva.json +32 -0
  77. package/catalog.js +178 -0
  78. package/catalog.js.map +1 -0
  79. package/catalog.ts +216 -0
  80. package/cli.js +30 -0
  81. package/cli.js.map +1 -0
  82. package/cli.ts +26 -0
  83. package/clients.js +34 -0
  84. package/clients.js.map +1 -0
  85. package/clients.ts +65 -0
  86. package/connections.js +1961 -0
  87. package/connections.js.map +1 -0
  88. package/connections.ts +2561 -0
  89. package/deno.json +1 -0
  90. package/discord-account.json +22 -0
  91. package/discord-bot.json +20 -0
  92. package/discord.json +26 -0
  93. package/effects.js +168 -0
  94. package/effects.js.map +1 -0
  95. package/effects.ts +160 -0
  96. package/elevenlabs.json +18 -0
  97. package/facebook.json +18 -0
  98. package/field.js +19 -0
  99. package/field.js.map +1 -0
  100. package/field.ts +31 -0
  101. package/form.js +112 -0
  102. package/form.js.map +1 -0
  103. package/form.ts +178 -0
  104. package/git-config.js +44 -0
  105. package/git-config.js.map +1 -0
  106. package/git-config.ts +26 -0
  107. package/given.js +83 -0
  108. package/given.js.map +1 -0
  109. package/given.ts +88 -0
  110. package/gmail-mailbox.json +29 -0
  111. package/gmail.json +31 -0
  112. package/google-calendar.json +31 -0
  113. package/google-drive.json +31 -0
  114. package/google-search-console.json +29 -0
  115. package/graph.js +36 -0
  116. package/graph.js.map +1 -0
  117. package/graph.ts +52 -0
  118. package/history.js +31 -0
  119. package/history.js.map +1 -0
  120. package/history.ts +32 -0
  121. package/identity.js +15 -0
  122. package/identity.js.map +1 -0
  123. package/identity.ts +18 -0
  124. package/integrations.js +493 -0
  125. package/integrations.js.map +1 -0
  126. package/integrations.ts +725 -0
  127. package/loopback.js +72 -0
  128. package/loopback.js.map +1 -0
  129. package/loopback.ts +89 -0
  130. package/lulu.json +32 -0
  131. package/mcp-retirement.js +133 -0
  132. package/mcp-retirement.js.map +1 -0
  133. package/mcp-retirement.ts +200 -0
  134. package/mcp-signin.js +14 -0
  135. package/mcp-signin.js.map +1 -0
  136. package/mcp-signin.ts +13 -0
  137. package/mcp.js +1036 -0
  138. package/mcp.js.map +1 -0
  139. package/mcp.ts +1283 -0
  140. package/mod.js +70 -0
  141. package/mod.js.map +1 -0
  142. package/mod.ts +216 -0
  143. package/openai-api.json +12 -0
  144. package/openai.json +25 -0
  145. package/openrouter.json +14 -0
  146. package/package.json +89 -4
  147. package/paste.js +36 -0
  148. package/paste.js.map +1 -0
  149. package/paste.ts +55 -0
  150. package/requests.js +137 -0
  151. package/requests.js.map +1 -0
  152. package/requests.ts +200 -0
  153. package/services.js +84 -0
  154. package/services.js.map +1 -0
  155. package/services.ts +111 -0
  156. package/sign-in.js +36 -0
  157. package/sign-in.js.map +1 -0
  158. package/sign-in.ts +53 -0
  159. package/signin-mail.js +29 -0
  160. package/signin-mail.js.map +1 -0
  161. package/signin-mail.ts +56 -0
  162. package/signin.js +68 -0
  163. package/signin.js.map +1 -0
  164. package/signin.ts +109 -0
  165. package/slack.json +90 -0
  166. package/sources.js +178 -0
  167. package/sources.js.map +1 -0
  168. package/sources.ts +237 -0
  169. package/tools.js +39 -0
  170. package/tools.js.map +1 -0
  171. package/tools.ts +46 -0
  172. package/views.js +85 -0
  173. package/views.js.map +1 -0
  174. package/views.ts +89 -0
  175. package/visitor-defaults.json +8 -0
  176. package/vocab.js +17 -0
  177. package/vocab.js.map +1 -0
  178. package/vocab.json +863 -0
  179. package/vocab.ts +18 -0
  180. package/voipms.json +32 -0
  181. package/yaks-app.js +159 -0
  182. package/yaks-app.js.map +1 -0
  183. package/yaks-app.ts +177 -0
  184. package/youtube.json +26 -0
package/connections.ts ADDED
@@ -0,0 +1,2561 @@
1
+ // Connections: one link between a space or a person and an outside service,
2
+ // through an integration, and the verbs over it.
3
+ //
4
+ // A connection is one entity wearing two components. `connection` says what it
5
+ // is — which integration, whose, which account, what was granted, and whether
6
+ // it works — and `secret` (@yaks/secrets) is its credential: a pasted key, the
7
+ // fields its integration names as a JSON object by name (S3's access key ID,
8
+ // secret key and region), or an OAuth grant's tokens as a JSON record. An app
9
+ // is handed a sentinel for each field, and the egress swaps in each one alone. The graph holds the secret's handle
10
+ // and the vault holds what it stands for, so a key goes from the person
11
+ // straight to the vault, and nothing that reads the graph — an agent, a sync, a
12
+ // backup — ever holds more than the handle. Being one entity is what makes its
13
+ // end one: deleting a connection, or the space or person it belongs to, drops
14
+ // its credential from the vault once the batch commits.
15
+ //
16
+ // The secret's name is `connection:` and a random id, and the entity's id is
17
+ // derived from that name (@yaks/secrets `secretEid`), so a refreshed token
18
+ // written under the vault's lock (`records`) lands on this same entity. It is
19
+ // also why a disconnect deletes the connection rather than clearing it: the
20
+ // name is the entity's identity, and a secret component removed would take the
21
+ // name with it. Every app that used it is linked to a new, needed connection
22
+ // in the same batch, so the space still shows what those apps need.
23
+ //
24
+ // Either order: an app says what it needs (`need`), which makes a connection
25
+ // with no credential and a `uses` link from the app; or a person connects
26
+ // first, and the app is linked to that connection afterwards. `need` never
27
+ // links an app to a connection that already holds a credential: giving an app
28
+ // a person's account is the person's act, not the app's.
29
+ //
30
+ // An app may instead ask each person who uses it to connect their own: a
31
+ // calendar app reads the calendar of whoever is looking. Its `uses` link says
32
+ // `each`, and so does the link to every person's own connection through that
33
+ // integration, made when they connect (`need` again, owned by them). A link
34
+ // marked `each` is spent only by the person who owns its connection, so one
35
+ // person's calendar is never read on another's behalf; the needed connection
36
+ // the space holds for it is only the ask, and nobody calls out through it.
37
+ //
38
+ // A copy of an app, made in another space from the same code, asks for what
39
+ // the app it was copied from uses (`carry`): a needed connection in its own
40
+ // space for each, by the same name, so its person connects their own and the
41
+ // copy works without anyone saying again what it needs.
42
+ //
43
+ // Or the app's space lends the copies its connection (`lend`): its link says
44
+ // `lends`, and each copy is linked to that same connection instead of asking,
45
+ // its link capped at that many calls per month and naming the `lender`. The
46
+ // copy calls out through it at once and never holds the key. A space knows
47
+ // which of its apps' links are borrowed by their `lender`, and which copies
48
+ // borrow its own connection the same way. Stopping a lend (`recall`) gives the
49
+ // copy the ask it would have had, in its own space; a key of its own replaces
50
+ // the borrowed link (`attach`); and the lender's connection stays as it was
51
+ // either way. Only a sentinel is lent: never a direct key, nor a link where
52
+ // each person connects their own. Which space a copy is in is the host's to
53
+ // say (`Owners`), since an app is the host's word.
54
+ //
55
+ // The two verbs an untrusted caller may ask, `need` and `list`, are the tools,
56
+ // and answer bundles like every tool, for the caller to write in its own name.
57
+ // Attaching an existing credential is the owner's act through a host that
58
+ // checks ownership. The rest are for trusted code (the dashboard connecting,
59
+ // the egress finding
60
+ // a sentinel among an app's connections, swapping in the credential and
61
+ // refreshing a token), and act on the graph and vault they are given.
62
+
63
+ import { type Built, line, sub } from '@yaks/query'
64
+ import { CallError } from '@yaks/tools/errors'
65
+ import type { Bundle, Comp, Eid } from 'jsr:@yaks/graph@0.2.36'
66
+ import { Stale } from '@yaks/graph/errors'
67
+ import { identityEid } from '@yaks/graph/identity'
68
+ import { token } from '@yaks/graph/sha256'
69
+ import { edgeEid, link } from '@yaks/edge'
70
+ import {
71
+ type Attempt,
72
+ claims,
73
+ type Client,
74
+ client,
75
+ OAuthError,
76
+ type Tokens,
77
+ } from '@yaks/oauth'
78
+ import {
79
+ records,
80
+ reveal,
81
+ reveals,
82
+ secretEid,
83
+ sentinelOf,
84
+ type Vault,
85
+ } from '@yaks/secrets'
86
+ import {
87
+ type About,
88
+ connectable,
89
+ type Field,
90
+ fieldsOf,
91
+ installed,
92
+ type Integration,
93
+ keyed,
94
+ known,
95
+ knownAll,
96
+ knownIn,
97
+ type Read,
98
+ set,
99
+ told,
100
+ } from './integrations.js'
101
+ import type { Place } from 'jsr:@yaks/host@0.2.36/keepers'
102
+ import {
103
+ APPROVING,
104
+ ASKS,
105
+ CONNECTION,
106
+ INTEGRATION,
107
+ integrationEid,
108
+ USES,
109
+ } from './identity.js'
110
+ import { through } from './graph.js'
111
+ import { pasted } from './paste.js'
112
+ import { loginFields } from './field.js'
113
+ import { clientOf } from './clients.js'
114
+ import { type Broker, BrokerError, brokerOf, type Grant } from './brokers.js'
115
+ import { mcpAlternative, useIntegration } from './mcp-signin.js'
116
+
117
+ let SECRET = 'secret'
118
+ let RECONNECTING = 'reconnecting'
119
+ let EDGE = 'edge'
120
+
121
+ /** An explicit account name did not select one connection: a refusal of the
122
+ * caller's own input, not a fault. */
123
+ export class AccountError extends CallError {
124
+ constructor(message: string) {
125
+ super('arguments', message)
126
+ this.name = 'AccountError'
127
+ }
128
+ }
129
+
130
+ /** needed: no credential yet; connected: one is kept; broken: the service
131
+ * refused it. */
132
+ export type Status = 'needed' | 'connected' | 'broken'
133
+
134
+ /** What an app, or a person, asks for, and for a custom integration what a
135
+ * person reads about it: its owner's to say, when it is made or later. */
136
+ export type Need = About & {
137
+ /** the space or person it belongs to */
138
+ owner: Eid
139
+ /** the integration, by name */
140
+ integration: string
141
+ /** the app that needs it; none when a person connects first */
142
+ app?: Eid
143
+ scopes?: string[]
144
+ /** for a custom key: the hosts it may be sent to */
145
+ hosts?: string[]
146
+ /** for a custom key: what a person gives to connect it, when it is more
147
+ * than one key */
148
+ fields?: Field[]
149
+ /** each person connects their own, and only they call out through it */
150
+ each?: boolean
151
+ /** the name the app's code reads it by (default: the integration's name in
152
+ * capitals) */
153
+ binding?: string
154
+ /** ask for a separate shared connection under this binding */
155
+ separate?: boolean
156
+ /** hand the app's code the key itself rather than a sentinel */
157
+ direct?: boolean
158
+ /** the task that asks a person for the key, linked to it by `asks` */
159
+ task?: Eid
160
+ /** where else the key goes once it is given, besides the vault */
161
+ keep?: Place[]
162
+ }
163
+
164
+ /** What the acting verbs work with. */
165
+ export type Ctx = {
166
+ graph: {
167
+ read: Read
168
+ apply: (bundles: Bundle[]) => Bundle[] | Promise<Bundle[]>
169
+ }
170
+ vault: Vault
171
+ /** where the service sends the person back after they sign in */
172
+ redirect?: string
173
+ /** where the host serves its OAuth client's metadata document, whose URL
174
+ * is the client's id at a service that takes one (@yaks/mcp-client/oauth
175
+ * `client`) */
176
+ document?: string
177
+ fetch?: typeof fetch
178
+ now?: () => number
179
+ /** where a failure is reported that the verb answering is not stopped by:
180
+ * a broker's connection left behind by a disconnect */
181
+ report?: (e: unknown) => void
182
+ /** asked before `owner` comes to hold one more connection with a key or a
183
+ * grant: before a needed one's sign-in begins, and before its key or grant
184
+ * is kept. It throws to refuse, as a host's plan limit does; signing in
185
+ * again, or a connection that already holds one, is not asked. */
186
+ admit?: (owner: Eid) => Promise<void>
187
+ }
188
+
189
+ /** Whose space each app is in, by its eid: who is asked for what it needs. The
190
+ * host says, since an app is its word; an app it does not know is missing. */
191
+ export type Owners = (apps: Eid[]) => Promise<Record<Eid, Eid>>
192
+
193
+ /** What a caller calling out through a connection is given: the connection,
194
+ * the `uses` link to it from the app, and the sentinel for each field of its
195
+ * credential, by the field's name: `key` for one key or a sign-in's token. */
196
+ export type Resolved = {
197
+ connection: Bundle
198
+ link: Bundle
199
+ sentinels: Record<string, string>
200
+ }
201
+
202
+ /** How a connection's credential arrives: a pasted key, each field its
203
+ * integration names, or the return from the service's sign-in page with the
204
+ * attempt `begin` gave. */
205
+ export type Given = { key: string; expect?: Status } | {
206
+ fields: Record<string, string>
207
+ } | {
208
+ attempt: Attempt
209
+ callback: string | URL
210
+ /** A website session obtained alongside a bot OAuth sign-in, kept only in the vault. */
211
+ session?: string
212
+ /** the person who signed in, whose own account the sign-in also names
213
+ * where its integration `links` one */
214
+ person?: Eid
215
+ } | {
216
+ /** the broker's own id for a sign-in that finished there (`settle`) */
217
+ brokered: string
218
+ /** its grant, where the broker was already asked for it */
219
+ grant?: Grant
220
+ }
221
+
222
+ /** A direct sign-in started without an app's existing connection request. */
223
+ export type NewSignIn = { owner: Eid; integration: string }
224
+
225
+ let comp = (b: Bundle | undefined, name: string): Comp =>
226
+ (b?.[name] ?? {}) as Comp
227
+
228
+ let strs = (v: unknown): string[] => Array.isArray(v) ? v.map(String) : []
229
+
230
+ // Reads are filter lines, the form every door to a graph takes, so these verbs
231
+ // run over a graph in this process or one behind HTTP alike (yaks.app's
232
+ // directory). What a line here spells is an eid or a word of this package's,
233
+ // never a name somebody chose, which a line would have to quote: a connection's
234
+ // integration is compared here, after the read. A line answers the components
235
+ // it names, so one that needs the rest of an entity asks for them (`*`).
236
+ let ALL = line`&*`
237
+
238
+ let nameOf = (b: Bundle): string => String(comp(b, SECRET).name)
239
+ let integrated = (b: Bundle): string => String(comp(b, CONNECTION).integration)
240
+
241
+ // A new connection, needing a credential, under a name of its own.
242
+ let fresh = (
243
+ owner: Eid,
244
+ integration: string,
245
+ scopes: string[],
246
+ account?: string,
247
+ ): Bundle => {
248
+ let id = account
249
+ ? identityEid('connection-account', [
250
+ owner,
251
+ integration,
252
+ account.toLowerCase(),
253
+ ])
254
+ : crypto.randomUUID()
255
+ let name = `${CONNECTION}:${id}`
256
+ return {
257
+ entity: { eid: secretEid(name) },
258
+ [CONNECTION]: {
259
+ integration,
260
+ owner,
261
+ ...scopes.length ? { scopes } : {},
262
+ status: 'needed',
263
+ },
264
+ [SECRET]: { name },
265
+ }
266
+ }
267
+
268
+ // The connection as the graph holds it, or a refusal naming it.
269
+ let held = async (read: Read, eid: Eid): Promise<Bundle> => {
270
+ let [b] = await read(line`.entity.eid=${eid}&.${CONNECTION}${sub(ALL)}`)
271
+ if (!b) throw new Error(`no connection ${eid}`)
272
+ return b
273
+ }
274
+
275
+ let signing = (read: Read, connection: Eid | NewSignIn) =>
276
+ typeof connection == 'string'
277
+ ? held(read, connection)
278
+ : fresh(connection.owner, connection.integration, [])
279
+
280
+ // An exchange may outlast the connection it started on.
281
+ let stillHeld = (row: Bundle): Bundle => ({
282
+ entity: row.entity,
283
+ $was: {
284
+ entity: { eid: token(row.entity.eid) },
285
+ tombstone: { '': null },
286
+ },
287
+ })
288
+
289
+ let keeping = (c: Ctx, b: Bundle) =>
290
+ records<Tokens & Kept>(
291
+ {
292
+ apply: (rows) => c.graph.apply([stillHeld(b), ...rows]),
293
+ },
294
+ c.vault,
295
+ '',
296
+ )
297
+
298
+ // The `uses` links at one end, and the far end of one.
299
+ let links = (read: Read, at: 'from' | 'to', eid: Eid | Eid[]) =>
300
+ read(line`.${EDGE}.${at}=${eid}&.${USES}${sub(ALL)}`)
301
+ let far = (l: Bundle, at: 'from' | 'to'): Eid =>
302
+ String(comp(l, EDGE)[at == 'from' ? 'to' : 'from'])
303
+
304
+ type Use = {
305
+ app: Eid
306
+ integration: string
307
+ owner?: Eid
308
+ each?: boolean
309
+ binding?: string
310
+ }
311
+
312
+ type AppUse = { connection: Bundle; link: Bundle }
313
+
314
+ let appUses = async (
315
+ read: Read,
316
+ a: Use,
317
+ ): Promise<AppUse[]> => {
318
+ let out = (await links(read, 'from', a.app))
319
+ .filter((l) => !comp(l, USES).each == !a.each)
320
+ if (!out.length) return []
321
+ let found = await read(
322
+ line`.entity.eid=${out.map((l) => far(l, 'from'))}&.${CONNECTION}`,
323
+ )
324
+ return found.flatMap((b) => {
325
+ let c = comp(b, CONNECTION)
326
+ if (c.integration != a.integration || a.each && c.owner != a.owner) {
327
+ return []
328
+ }
329
+ return [{
330
+ connection: b,
331
+ link: out.find((l) => far(l, 'from') == b.entity.eid)!,
332
+ }]
333
+ })
334
+ }
335
+
336
+ let boundAs = <T extends AppUse>(uses: T[], binding: string): T | undefined =>
337
+ uses.find((m) => comp(m.link, USES).binding == binding)
338
+ let shared = <T extends AppUse>(uses: T[]): T | undefined =>
339
+ uses.find((m) => !comp(m.link, USES).separate)
340
+ let byIntegration = <T extends AppUse>(uses: T[]): T | undefined =>
341
+ shared(uses) ?? (uses.length == 1 ? uses[0] : undefined)
342
+ let usingLink = async (read: Read, a: Use) => {
343
+ let uses = await appUses(read, a)
344
+ return a.binding == null ? byIntegration(uses) : boundAs(uses, a.binding)
345
+ }
346
+
347
+ /** The connection an app uses through an integration, optionally by binding.
348
+ * With `each`, it is the one `owner` holds. */
349
+ export let using = async (read: Read, a: Use): Promise<Bundle | undefined> =>
350
+ (await usingLink(read, a))?.connection
351
+
352
+ let same = (a: string[], b: string[]) =>
353
+ [...a].sort().join('\n') == [...b].sort().join('\n')
354
+
355
+ // What a custom integration's fields say, checked: each a name an app can
356
+ // read, said once, with a label a person reads.
357
+ let FIELD = /^[a-z][a-z0-9_]{0,31}$/
358
+ let fielded = (fields: Field[]): Field[] => {
359
+ let out = fields.map((f) => ({
360
+ name: String(f.name ?? ''),
361
+ label: String(f.label ?? '').trim(),
362
+ ...f.shown ? { shown: true } : {},
363
+ ...f.example ? { example: f.example } : {},
364
+ }))
365
+ for (let f of out) {
366
+ if (!FIELD.test(f.name)) {
367
+ throw new CallError(
368
+ 'fields',
369
+ `${f.name} is not a field name: lowercase letters, digits and ` +
370
+ `underscores, starting with a letter`,
371
+ )
372
+ }
373
+ if (!f.label) throw new CallError('fields', `${f.name} needs a label`)
374
+ }
375
+ if (new Set(out.map((f) => f.name)).size < out.length) {
376
+ throw new CallError('fields', 'each field is named once')
377
+ }
378
+ return out
379
+ }
380
+
381
+ // A binding is a name in the app's own code, so it must be one.
382
+ let NAME = /^[A-Za-z_][A-Za-z0-9_]{0,63}$/
383
+
384
+ /** The names an app's code reads a connection by, by field name: its
385
+ * binding, for one key or a sign-in, or for several fields the binding and
386
+ * each field's name in capitals, `S3_ACCESS_KEY_ID`. */
387
+ export let namesOf = (
388
+ binding: string,
389
+ fields: string[],
390
+ ): Record<string, string> =>
391
+ fields.length == 1 ? { [fields[0]]: binding } : Object.fromEntries(
392
+ fields.map((f) => [f, `${binding}_${f.toUpperCase()}`]),
393
+ )
394
+
395
+ /** The name an app reads an integration's connection by when it names none:
396
+ * `google-calendar` is `GOOGLE_CALENDAR`. */
397
+ export let bindingOf = (integration: string): string =>
398
+ integration.toUpperCase().replace(/[^A-Z0-9]+/g, '_').replace(/^(?=\d)/, '_')
399
+ .slice(0, 64)
400
+
401
+ // The link from an app, saying what its code reads the connection by,
402
+ // whether each person connects their own, and whether visitors call out
403
+ // through it where that was said.
404
+ let linked = (
405
+ app: Eid,
406
+ to: Eid,
407
+ u: {
408
+ binding: string
409
+ direct: boolean
410
+ each?: boolean
411
+ separate?: boolean
412
+ anyone?: boolean
413
+ },
414
+ ): Bundle => ({
415
+ ...link(app, USES, to),
416
+ [USES]: {
417
+ binding: u.binding,
418
+ ...u.direct ? { direct: true } : {},
419
+ ...u.each ? { each: true } : {},
420
+ ...u.separate ? { separate: true } : {},
421
+ ...u.anyone == null ? {} : { anyone: u.anyone },
422
+ },
423
+ })
424
+
425
+ // The asks `owner` has standing through an integration for these scopes:
426
+ // shared connections needing a credential, grouped by binding for separate asks.
427
+ let withScopes = async (
428
+ read: Read,
429
+ owner: Eid,
430
+ integration: string,
431
+ scopes: string[],
432
+ status: Status,
433
+ ): Promise<Bundle[]> =>
434
+ (await read(
435
+ line`.${CONNECTION}.owner=${owner}&.${CONNECTION}.integration=${integration}&.${CONNECTION}.status=${status}`,
436
+ )).filter((b) => same(strs(comp(b, CONNECTION).scopes), scopes))
437
+
438
+ let inGroup = async (
439
+ read: Read,
440
+ needed: Bundle[],
441
+ binding?: string,
442
+ ): Promise<Bundle[]> => {
443
+ if (!needed.length) return []
444
+ let used = await links(read, 'to', needed.map((b) => b.entity.eid))
445
+ return needed.filter((b) => {
446
+ let uses = used.filter((l) => far(l, 'from') == b.entity.eid)
447
+ .map((l) => comp(l, USES))
448
+ return binding == null
449
+ ? uses.every((u) => !u.each && !u.separate)
450
+ : uses.length > 0 && uses.every((u) => u.separate && u.binding == binding)
451
+ })
452
+ }
453
+
454
+ let asksOf = async (
455
+ read: Read,
456
+ owner: Eid,
457
+ integration: string,
458
+ scopes: string[],
459
+ binding?: string,
460
+ ): Promise<Bundle[]> =>
461
+ inGroup(
462
+ read,
463
+ await withScopes(read, owner, integration, scopes, 'needed'),
464
+ binding,
465
+ )
466
+
467
+ let firstAsk = async (
468
+ read: Read,
469
+ owner: Eid,
470
+ integration: string,
471
+ scopes: string[],
472
+ ) => {
473
+ let [ask] = await asksOf(read, owner, integration, scopes)
474
+ return ask &&
475
+ (await read(line`.entity.eid=${ask.entity.eid}&.${CONNECTION}${sub(ALL)}`))[
476
+ 0
477
+ ]
478
+ }
479
+
480
+ let stillNeeded = (b: Bundle): Bundle => {
481
+ let held = stillHeld(b)
482
+ held.$was![CONNECTION] = { status: token('needed') }
483
+ return held
484
+ }
485
+
486
+ // A separate credential only answers other asks for its binding.
487
+ let separately = async (read: Read, eid: Eid) =>
488
+ (await links(read, 'to', eid)).map((l) => comp(l, USES))
489
+ .find((u) => u.separate)?.binding as string | undefined
490
+
491
+ let movedUses = async (read: Read, from: Eid[], to: Eid): Promise<Bundle[]> => {
492
+ let uses = await links(read, 'to', [...from, to])
493
+ let kept = new Set(
494
+ uses.filter((l) => far(l, 'from') == to).map((l) => far(l, 'to')),
495
+ )
496
+ let moved: Bundle[] = []
497
+ for (let l of uses) {
498
+ if (far(l, 'from') == to) continue
499
+ let app = far(l, 'to')
500
+ if (kept.has(app)) continue
501
+ kept.add(app)
502
+ moved.push({ ...link(app, USES, to), [USES]: comp(l, USES) })
503
+ }
504
+ return moved
505
+ }
506
+
507
+ // What connecting `b` answers: every other ask its owner has standing through
508
+ // the same integration and scopes closes, and each app it served is linked to
509
+ // `to`, the connection now connected, as it was to the ask.
510
+ let answered = async (read: Read, b: Bundle, to: Eid): Promise<Bundle[]> => {
511
+ let c = comp(b, CONNECTION)
512
+ let needed = (await withScopes(
513
+ read,
514
+ String(c.owner),
515
+ String(c.integration),
516
+ strs(c.scopes),
517
+ 'needed',
518
+ )).filter((o) => o.entity.eid != b.entity.eid && o.entity.eid != to)
519
+ if (!needed.length) return []
520
+ let asks = await inGroup(read, needed, await separately(read, b.entity.eid))
521
+ if (!asks.length) return []
522
+ return [
523
+ ...asks.map((o) => ({ ...stillNeeded(o), tombstone: {} })),
524
+ ...await movedUses(read, asks.map((o) => o.entity.eid), to),
525
+ ]
526
+ }
527
+
528
+ /** Make a connection needing a credential, linked from the app that needs it,
529
+ * with the custom integration a key for an unbuilt service needs — made only
530
+ * where no integration holds the name, so it never writes over one, and owned
531
+ * by whoever made it. Its hosts may wait: a key kept before anyone uses it is
532
+ * sent nowhere, and its owner may name them once. On a new integration the
533
+ * owner can correct hosts until its first credential. What is said about it (`About`) is written with it, or
534
+ * changed by its owner asking again. An ask the owner already has standing
535
+ * through that integration for the same scopes is reused. With `separate`,
536
+ * the binding also identifies the ask. With `each`, each owner asks for
537
+ * their own. The connection comes first. */
538
+ export let need = async (
539
+ read: Read,
540
+ a: Need,
541
+ request = false,
542
+ ): Promise<Bundle[]> => {
543
+ let keep = placesOf(a.keep)
544
+ if (keep.length) {
545
+ let i = await known(read, a.integration)
546
+ if (i && !keyed(i)) {
547
+ throw new CallError(
548
+ 'keep',
549
+ `${a.integration} is connected by signing in, and only a pasted key ` +
550
+ `is kept anywhere but the vault`,
551
+ )
552
+ }
553
+ }
554
+ let [made, ...rest] = await asked(read, a, request)
555
+ let eid = made.entity.eid
556
+ return [
557
+ keep.length
558
+ ? { ...made, [CONNECTION]: { ...comp(made, CONNECTION), keep } }
559
+ : made,
560
+ ...rest,
561
+ ...a.task ? [{ ...link(a.task, ASKS, eid), [ASKS]: {} }] : [],
562
+ ]
563
+ }
564
+
565
+ // The places a key is kept, each a keeper's name and its address there.
566
+ let placesOf = (keep: Place[] = []): Place[] =>
567
+ keep.map(({ via, at }) => {
568
+ if (!String(via ?? '').trim() || !String(at ?? '').trim()) {
569
+ throw new CallError(
570
+ 'keep',
571
+ 'each place names a keeper (via) and where (at)',
572
+ )
573
+ }
574
+ return { via: String(via).trim(), at: String(at).trim() }
575
+ })
576
+
577
+ let asked = async (
578
+ read: Read,
579
+ a: Need,
580
+ request: boolean,
581
+ ): Promise<Bundle[]> => {
582
+ let hosts = a.hosts ?? []
583
+ let name = a.integration
584
+ let i = await known(read, name)
585
+ let fields = (!i || !request) && a.fields?.length ? fielded(a.fields) : []
586
+ let catalog = i?.built && request
587
+ let about = catalog ? {} : told(a)
588
+ if (fields.length && i && !i.fields?.length) {
589
+ throw new CallError(
590
+ 'fields',
591
+ `${name} is connected with ${
592
+ keyed(i) ? 'one key' : 'a sign-in'
593
+ }, and its fields never change`,
594
+ )
595
+ }
596
+ if (
597
+ fields.length && i?.fields &&
598
+ JSON.stringify(fielded(i.fields)) != JSON.stringify(fields)
599
+ ) {
600
+ throw new CallError(
601
+ 'fields',
602
+ `${name} already asks for ${i.fields.map((f) => f.name).join(', ')}`,
603
+ )
604
+ }
605
+ if (hosts.length && i?.built && !catalog) {
606
+ throw new CallError(
607
+ 'hosts',
608
+ `${name} is built, and sends its credential to its own hosts`,
609
+ )
610
+ }
611
+ let naming = i && !catalog && a.hosts != null && !same(i.hosts, hosts)
612
+ ? i
613
+ : undefined
614
+ if (naming && naming.owner != a.owner) {
615
+ throw new CallError(
616
+ 'hosts',
617
+ `only the space or person that made ${name} names its hosts`,
618
+ )
619
+ }
620
+ if (
621
+ naming && naming.hosts.length && (
622
+ naming.credentialed || (await read(
623
+ line`.${CONNECTION}.integration=${name}&.secret.value&.limit=1&.fields=entity.eid`,
624
+ )).length
625
+ )
626
+ ) {
627
+ throw new CallError(
628
+ 'hosts',
629
+ `${name} already sends its key to ${naming.hosts.join(', ')}`,
630
+ )
631
+ }
632
+ let binding = a.binding ?? bindingOf(name)
633
+ if (a.separate && (!a.app || a.binding == null || a.each)) {
634
+ throw new CallError(
635
+ 'separate',
636
+ 'A separate connection needs an app and a binding shared by its callers',
637
+ )
638
+ }
639
+ if (!NAME.test(binding)) {
640
+ throw new CallError(
641
+ 'binding',
642
+ `${binding} is not a name code can read: letters, digits and ` +
643
+ `underscores, not starting with a digit`,
644
+ )
645
+ }
646
+ if (a.direct && i && !keyed(i)) {
647
+ throw new CallError(
648
+ 'direct',
649
+ `${name} is connected by signing in, and only a pasted key is handed ` +
650
+ `to an app directly`,
651
+ )
652
+ }
653
+ if (a.direct && a.each) {
654
+ throw new CallError(
655
+ 'direct',
656
+ `a key each person connects is theirs, and is never handed to the app`,
657
+ )
658
+ }
659
+ let u = { binding, direct: !!a.direct, each: a.each, separate: a.separate }
660
+ if (a.app && i?.broker?.scoped) {
661
+ throw new CallError(
662
+ 'connection',
663
+ `${name} is reserved for its space service`,
664
+ )
665
+ }
666
+ // Said again of one that stands, it is its owner's change to make.
667
+ let retold = [
668
+ ...i && Object.keys(about).length ? await set(read, a) : [],
669
+ ...naming
670
+ ? [{
671
+ entity: { eid: integrationEid(name) },
672
+ [INTEGRATION]: { hosts },
673
+ // Refused, rather than written over, where they were named meanwhile.
674
+ $was: {
675
+ [INTEGRATION]: {
676
+ hosts: token(naming.hosts),
677
+ credentialed: token(naming.credentialed ?? null),
678
+ },
679
+ },
680
+ }]
681
+ : [],
682
+ ]
683
+ let uses = a.app ? await appUses(read, { ...a, app: a.app }) : []
684
+ let used = (a.binding != null ? boundAs(uses, binding) : undefined) ??
685
+ (a.separate ? undefined : shared(uses) ?? boundAs(uses, binding))
686
+ if (used) {
687
+ if (a.direct) {
688
+ let loan = comp(used.link, USES)
689
+ if (loan.lender != null || loan.lends != null) {
690
+ throw new CallError(
691
+ 'direct',
692
+ loan.lender != null
693
+ ? 'A borrowed connection only supplies a sentinel; connect your own key first'
694
+ : 'Stop lending this connection before handing its key to the app',
695
+ )
696
+ }
697
+ }
698
+ let said = a.binding != null || a.direct != null
699
+ let patch = {
700
+ ...a.binding != null ? { binding: a.binding } : {},
701
+ ...a.direct != null ? { direct: a.direct || null } : {},
702
+ }
703
+ return [
704
+ // Answered with the integration it goes through, as it already does.
705
+ {
706
+ entity: { eid: used.connection.entity.eid },
707
+ [CONNECTION]: { integration: name },
708
+ },
709
+ ...said
710
+ ? [{
711
+ ...link(a.app!, USES, used.connection.entity.eid),
712
+ [USES]: patch,
713
+ }]
714
+ : [],
715
+ ...retold,
716
+ ]
717
+ }
718
+ // An owner-only request can reuse a saved credential without granting it
719
+ // to a new app. Otherwise reuse the open ask for the same scopes and group.
720
+ let saved = !request || a.app || a.each || a.task || a.keep?.length
721
+ ? undefined
722
+ : (await inGroup(
723
+ read,
724
+ await withScopes(read, a.owner, name, a.scopes ?? [], 'connected'),
725
+ ))[0]
726
+ let standing = saved ?? (a.each ? undefined : (await asksOf(
727
+ read,
728
+ a.owner,
729
+ name,
730
+ a.scopes ?? [],
731
+ a.separate ? binding : undefined,
732
+ ))[0])
733
+ if (standing) {
734
+ return [
735
+ {
736
+ entity: { eid: standing.entity.eid },
737
+ [CONNECTION]: { integration: name },
738
+ },
739
+ ...retold,
740
+ ...a.app ? [linked(a.app, standing.entity.eid, u)] : [],
741
+ ]
742
+ }
743
+ let made = fresh(a.owner, name, a.scopes ?? [])
744
+ let written = Object.fromEntries(
745
+ Object.entries(about).filter(([, v]) => v != null),
746
+ )
747
+ return [
748
+ made,
749
+ ...i ? retold : [{
750
+ entity: { eid: integrationEid(name) },
751
+ [INTEGRATION]: {
752
+ name,
753
+ hosts,
754
+ ...fields.length ? { fields } : {},
755
+ owner: a.owner,
756
+ ...written,
757
+ },
758
+ // Refused, rather than written over, where one was made meanwhile.
759
+ $was: { [INTEGRATION]: { name: null } },
760
+ }],
761
+ ...a.app ? [linked(a.app, made.entity.eid, u)] : [],
762
+ ]
763
+ }
764
+
765
+ // Whether a link may lend its connection: a sentinel every caller shares, on
766
+ // a connection the app's own space keeps rather than borrows.
767
+ let lendable = (u: Comp) => !u.each && !u.direct && u.lender == null
768
+
769
+ // The copy's link to the connection its source app lends, capped as lent.
770
+ let borrowing = (app: Eid, lent: Bundle, lender: Eid): Bundle => {
771
+ let u = comp(lent, USES)
772
+ return {
773
+ ...link(app, USES, far(lent, 'from')),
774
+ [USES]: {
775
+ binding: u.binding,
776
+ cap: u.lends,
777
+ lender,
778
+ ...u.separate ? { separate: true } : {},
779
+ },
780
+ }
781
+ }
782
+
783
+ /** What a copy of an app asks for, read off the app it was copied from: for
784
+ * each connection the source uses and the copy does not yet, a connection
785
+ * needing a credential, owned by `owner`, the copy's space, and linked from the
786
+ * copy as `need` makes one. It goes through the same integration, is read by
787
+ * the same binding, as directly, for each person where the source asks each,
788
+ * and asks for the same scopes. A credential never travels, and neither does a
789
+ * link opened to anyone, which is the person's act. Where the source lends a
790
+ * connected connection (`lend`), the copy borrows it instead: a link to that
791
+ * same connection, capped at what the source lends and naming it the
792
+ * `lender`, which the host writes as itself since only it sets a cap. An
793
+ * install and an update both ask it, so an update adds what its version gained
794
+ * and leaves what the copy already uses as its person made it. */
795
+ export let carry = async (
796
+ read: Read,
797
+ a: { source: Eid; app: Eid; owner: Eid },
798
+ ): Promise<Bundle[]> => {
799
+ let out = await links(read, 'from', [a.source, a.app])
800
+ if (!out.length) return []
801
+ let to = await read(
802
+ line`.entity.eid=${out.map((l) => far(l, 'from'))}&.${CONNECTION}`,
803
+ )
804
+ // One ask for each integration and mode, with a binding for separate asks.
805
+ let had = new Set<string>()
806
+ let asks = new Map<string, Need | Bundle>()
807
+ for (let l of out) {
808
+ let c = comp(to.find((b) => b.entity.eid == far(l, 'from')), CONNECTION)
809
+ let u = comp(l, USES)
810
+ // A link naming no binding is a person's grant of their own source
811
+ // (./sources.ts), not something the app's code asks for.
812
+ if (u.binding == null && u.lender == null) continue
813
+ let each = u.each == true
814
+ let key = JSON.stringify([
815
+ each,
816
+ c.integration,
817
+ u.separate ? u.binding : null,
818
+ ])
819
+ if (comp(l, EDGE).from == a.app) {
820
+ if (!each || c.owner == a.owner) had.add(key)
821
+ } else if (
822
+ lendable(u) && typeof u.lends == 'number' && c.status == 'connected'
823
+ ) {
824
+ asks.set(key, borrowing(a.app, l, a.source))
825
+ } else if (typeof c.integration == 'string') {
826
+ asks.set(key, {
827
+ owner: a.owner,
828
+ app: a.app,
829
+ integration: c.integration,
830
+ scopes: strs(c.scopes),
831
+ each,
832
+ binding: typeof u.binding == 'string' ? u.binding : undefined,
833
+ direct: u.direct == true,
834
+ separate: u.separate == true,
835
+ })
836
+ }
837
+ }
838
+ let made = await Promise.all(
839
+ [...asks].filter(([key]) => !had.has(key)).map(([, ask]) =>
840
+ 'entity' in ask ? [ask] : need(read, ask)
841
+ ),
842
+ )
843
+ return made.flat()
844
+ }
845
+
846
+ /** Lend the connection an app uses through an integration to every copy
847
+ * installed from it, from then on: each copy borrows it at install (`carry`)
848
+ * under a cap of `cap` calls per month, and a new cap moves every copy already
849
+ * borrowing it. `null` stops lending it, and every copy borrowing it through
850
+ * this app asks for its own (`recall`). The cap a copy borrows under is the
851
+ * host's to write, so the host applies this as itself, once it has checked
852
+ * that the actor owns the app's space and the connection. Refused for a key
853
+ * handed to the app's code, a link where each person connects their own, and
854
+ * a connection the app itself borrows. */
855
+ export let lend = async (
856
+ read: Read,
857
+ a: { app: Eid; integration: string; binding?: string; cap: number | null },
858
+ owners: Owners,
859
+ ): Promise<Bundle[]> => {
860
+ if (a.cap != null && !(Number.isInteger(a.cap) && a.cap > 0)) {
861
+ throw new CallError(
862
+ 'cap',
863
+ 'a cap is a whole number of calls per month, at least one',
864
+ )
865
+ }
866
+ let used = await usingLink(read, a)
867
+ if (!used) {
868
+ throw new CallError(
869
+ 'integration',
870
+ `Choose a shared ${a.integration} connection by binding to lend it`,
871
+ )
872
+ }
873
+ let eid = used.link.entity.eid
874
+ let u = comp(used.link, USES)
875
+ if (u.direct) {
876
+ throw new CallError(
877
+ 'integration',
878
+ `the app's code is handed the ${a.integration} key itself, and only a ` +
879
+ 'sentinel is lent',
880
+ )
881
+ }
882
+ if (u.lender != null) {
883
+ throw new CallError(
884
+ 'integration',
885
+ `the app borrows its ${a.integration} connection, which is not its to lend`,
886
+ )
887
+ }
888
+ let lends = { entity: { eid }, [USES]: { lends: a.cap } }
889
+ let loans = (await read(line`.${USES}.lender=${a.app}${sub(ALL)}`))
890
+ .filter((l) => {
891
+ let loan = comp(l, USES)
892
+ return !!loan.separate == !!u.separate &&
893
+ (!u.separate || loan.binding == u.binding)
894
+ })
895
+ let connections = loans.length
896
+ ? await read(
897
+ line`.entity.eid=${loans.map((l) => far(l, 'from'))}&.${CONNECTION}`,
898
+ )
899
+ : []
900
+ let targets = new Set(
901
+ connections.filter((b) => comp(b, CONNECTION).integration == a.integration)
902
+ .map((b) => b.entity.eid),
903
+ )
904
+ let lent = loans.filter((l) => targets.has(far(l, 'from')))
905
+ if (a.cap == null) {
906
+ return [
907
+ lends,
908
+ ...(await Promise.all(
909
+ [...targets].map((connection) =>
910
+ recall(read, { connection, lender: a.app }, owners)
911
+ ),
912
+ )).flat(),
913
+ ]
914
+ }
915
+ return [
916
+ lends,
917
+ ...lent.map((l) => ({
918
+ entity: { eid: l.entity.eid },
919
+ [USES]: { cap: a.cap },
920
+ })),
921
+ ]
922
+ }
923
+
924
+ /** Stop lending a connection: to the one copy `app`, to every copy borrowing
925
+ * it through the `lender` app's lend, or with neither to every copy borrowing
926
+ * it. Each copy's link gives way to a connection needing a credential of its
927
+ * own, in the copy's own space (`owners`), linked by the same name, as
928
+ * `disconnect` leaves the apps that shared one. The connection lent stays as
929
+ * it was. */
930
+ export let recall = async (
931
+ read: Read,
932
+ a: { connection: Eid; app?: Eid; lender?: Eid },
933
+ owners: Owners,
934
+ ): Promise<Bundle[]> => {
935
+ let b = await held(read, a.connection)
936
+ let loans = (await links(read, 'to', a.connection)).filter((l) => {
937
+ let u = comp(l, USES)
938
+ return u.lender != null && (a.app == null || far(l, 'to') == a.app) &&
939
+ (a.lender == null || u.lender == a.lender)
940
+ })
941
+ return [
942
+ ...loans.map((l) => ({ entity: { eid: l.entity.eid }, tombstone: {} })),
943
+ ...await reasked(b, loans, owners),
944
+ ]
945
+ }
946
+
947
+ /** The connections some apps borrow rather than hold, from the `uses` links
948
+ * out of them, each with the link borrowing it and the integration it goes
949
+ * through: what the apps' own space reads beside the connections it keeps.
950
+ * The host reads the links however it names its apps, so they can be asked
951
+ * beside everything else it shows. A borrowed connection is read without its
952
+ * secret, which is the lender's. */
953
+ export let borrowed = async (
954
+ read: Read,
955
+ out: Bundle[],
956
+ ): Promise<Bundle[]> => {
957
+ let loans = out.filter((l) => l[USES] && comp(l, USES).lender != null)
958
+ if (!loans.length) return []
959
+ let lent = await read(
960
+ line`.entity.eid=${loans.map((l) => far(l, 'from'))}&.${CONNECTION}`,
961
+ )
962
+ return [...lent, ...loans, ...await through(read, lent)]
963
+ }
964
+
965
+ /** Link an app to a connection its space already owns and has connected.
966
+ * The host verifies that the actor owns both. A previous unmet ask is
967
+ * replaced, with its binding kept, and an unused ask is removed. `anyone`
968
+ * opens the link to visitors or keeps it to the app's members within the
969
+ * integration's visitor policy. When omitted, the link keeps any explicit
970
+ * choice and otherwise follows the integration's default. The app gets a
971
+ * sentinel. */
972
+ export let attach = async (
973
+ read: Read,
974
+ a: {
975
+ owner: Eid
976
+ app: Eid
977
+ connection: Eid
978
+ binding?: string
979
+ anyone?: boolean
980
+ },
981
+ ): Promise<Bundle[]> => {
982
+ let target = await held(read, a.connection)
983
+ let grant = comp(target, CONNECTION)
984
+ if (grant.owner != a.owner || grant.status != 'connected') {
985
+ throw new Error('Choose a connected connection owned by this space')
986
+ }
987
+ let integration = String(grant.integration)
988
+ let i = await known(read, integration)
989
+ if (i?.broker?.scoped) {
990
+ throw new CallError(
991
+ 'connection',
992
+ `${integration} is reserved for its space service`,
993
+ )
994
+ }
995
+ let uses = await appUses(read, { app: a.app, integration })
996
+ let current = uses.find((m) => m.connection.entity.eid == a.connection)?.link
997
+ let selected = a.binding == null ? undefined : boundAs(uses, a.binding)
998
+ if (current) {
999
+ // Attached again, it is renamed when given a new name and opened or
1000
+ // closed when told to, and otherwise already is what was asked.
1001
+ let had = comp(current, USES)
1002
+ let renamed = a.binding != null && a.binding != had.binding
1003
+ let opened = a.anyone != null && a.anyone !== had.anyone
1004
+ if (!renamed && !opened) return []
1005
+ if (renamed && !NAME.test(a.binding!)) {
1006
+ throw new Error('The binding must be a name code can read')
1007
+ }
1008
+ if (
1009
+ renamed && selected && selected.link.entity.eid != current.entity.eid
1010
+ ) {
1011
+ throw new Error(
1012
+ 'This app already uses another connection under that binding',
1013
+ )
1014
+ }
1015
+ return [{
1016
+ entity: current.entity,
1017
+ [USES]: {
1018
+ ...renamed ? { binding: a.binding } : {},
1019
+ ...opened ? { anyone: a.anyone } : {},
1020
+ },
1021
+ ...renamed
1022
+ ? {
1023
+ $was: {
1024
+ [USES]: {
1025
+ binding: had.binding == null ? null : token(had.binding),
1026
+ },
1027
+ },
1028
+ }
1029
+ : {},
1030
+ }]
1031
+ }
1032
+ let old = selected ??
1033
+ (a.binding == null
1034
+ ? byIntegration(uses) ?? boundAs(uses, bindingOf(integration))
1035
+ : shared(uses))
1036
+ let previous = old?.connection.entity.eid
1037
+ let u = comp(old?.link, USES)
1038
+ if (u.direct) {
1039
+ throw new Error(
1040
+ 'This app asks for the key itself; attach requires a sentinel',
1041
+ )
1042
+ }
1043
+ let binding = a.binding ?? u.binding ?? bindingOf(integration)
1044
+ if (typeof binding != 'string' || !NAME.test(binding)) {
1045
+ throw new Error('The binding must be a name code can read')
1046
+ }
1047
+ if (old && comp(old.connection, CONNECTION).status == 'needed') {
1048
+ if (i?.token) {
1049
+ let wanted = strs(comp(old.connection, CONNECTION).scopes)
1050
+ let granted = strs(grant.scopes)
1051
+ wanted = wanted.length ? wanted : i.scopes ?? []
1052
+ granted = granted.length ? granted : i.scopes ?? []
1053
+ if (wanted.some((s) => !granted.includes(s))) {
1054
+ throw new Error(
1055
+ 'This connection does not grant the scopes the app asked for',
1056
+ )
1057
+ }
1058
+ }
1059
+ }
1060
+ let alone = previous && (await links(read, 'to', previous)).length == 1
1061
+ return [
1062
+ {
1063
+ entity: { eid: a.connection },
1064
+ $was: {
1065
+ [CONNECTION]: {
1066
+ status: token(grant.status),
1067
+ owner: token(grant.owner),
1068
+ integration: token(grant.integration),
1069
+ },
1070
+ },
1071
+ },
1072
+ ...previous
1073
+ ? [{ entity: { eid: edgeEid(a.app, USES, previous) }, tombstone: {} }]
1074
+ : [],
1075
+ ...previous && alone && comp(old?.connection, CONNECTION).status == 'needed'
1076
+ ? [{
1077
+ entity: { eid: previous },
1078
+ tombstone: {},
1079
+ $was: { [CONNECTION]: { status: token('needed') } },
1080
+ }]
1081
+ : [],
1082
+ linked(a.app, a.connection, {
1083
+ binding,
1084
+ direct: false,
1085
+ separate: u.separate == true,
1086
+ anyone: a.anyone ?? (typeof u.anyone == 'boolean' ? u.anyone : undefined),
1087
+ }),
1088
+ ]
1089
+ }
1090
+
1091
+ /** An owner named before its eid is known: the walk from a reference to it
1092
+ * to what names it, as `.space.slug=ada` names a space by its address, and
1093
+ * its eid as whatever learns it answers. The host spells the walk, and one
1094
+ * may reach more than one owner: only the eid's are kept. */
1095
+ export type Path = { path: Built; eid: Promise<Eid> }
1096
+
1097
+ /** An owner's connected chat integrations and their connection rows. A
1098
+ * {@link Path} lets both reads start while the owner is still being read. */
1099
+ export let chatConnections = async (
1100
+ read: Read,
1101
+ owner: Eid | Path,
1102
+ ): Promise<{ row: Bundle; integration: Integration }[]> => {
1103
+ let at = typeof owner == 'string' ? line`=${owner}` : owner.path
1104
+ let [rows, integrations, eid] = await Promise.all([
1105
+ read(
1106
+ line`.${CONNECTION}.owner${sub(at)}&.${CONNECTION}.status=connected${
1107
+ sub(ALL)
1108
+ }`,
1109
+ ),
1110
+ installed(read),
1111
+ typeof owner == 'string' ? owner : owner.eid,
1112
+ ])
1113
+ let byName = new Map(
1114
+ integrations.filter((i) => i.chat).map((i) => [i.name, i]),
1115
+ )
1116
+ return rows.flatMap((row) => {
1117
+ let connection = comp(row, CONNECTION)
1118
+ let integration = byName.get(String(connection.integration))
1119
+ return connection.owner == eid && integration ? [{ row, integration }] : []
1120
+ })
1121
+ }
1122
+
1123
+ /** A space's or a person's connections, the `uses` links from the apps that
1124
+ * use them, and the integrations they go through. Each is asked by the owner,
1125
+ * so all three are asked at once, and a host whose reads asked together
1126
+ * travel together answers them in one trip: the integrations among the built
1127
+ * ones (the line `installed` asks) and the owner's own. Only one another owner
1128
+ * listed is asked after. An owner named by a {@link Path} is asked before its
1129
+ * eid is known, beside whatever learns it. */
1130
+ export let list = async (read: Read, owner: Eid | Path): Promise<Bundle[]> => {
1131
+ let at = typeof owner == 'string' ? line`=${owner}` : owner.path
1132
+ let [reached, links, built, theirs, eid] = await Promise.all([
1133
+ read(line`.${CONNECTION}.owner${sub(at)}${sub(ALL)}`),
1134
+ read(line`.${EDGE}.to.${CONNECTION}.owner${sub(at)}&.${USES}${sub(ALL)}`),
1135
+ read(line`.${INTEGRATION}.built`),
1136
+ read(line`.${INTEGRATION}.owner${sub(at)}`),
1137
+ typeof owner == 'string' ? owner : owner.eid,
1138
+ ])
1139
+ let owned = reached.filter((b) => comp(b, CONNECTION).owner == eid)
1140
+ if (!owned.length) return []
1141
+ let ids = new Set(owned.map((b) => b.entity.eid))
1142
+ let names = new Set(
1143
+ owned.map((b) => integrationEid(String(comp(b, CONNECTION).integration))),
1144
+ )
1145
+ let kept = [
1146
+ ...new Map([...built, ...theirs].map((b) => [b.entity.eid, b])).values(),
1147
+ ].filter((b) => names.has(b.entity.eid))
1148
+ return [
1149
+ ...owned,
1150
+ ...links.filter((l) => ids.has(String(comp(l, EDGE).to))),
1151
+ ...kept,
1152
+ ...await through(read, [...owned, ...kept]),
1153
+ ]
1154
+ }
1155
+
1156
+ /** Every connected connection an app calls out through for a person, or for
1157
+ * nobody in particular: those it shares with every caller, and that person's
1158
+ * own where each person connects their own. Each comes with its `uses` link
1159
+ * and the sentinel for its credential: what the egress finds a request's
1160
+ * sentinels among. */
1161
+ export let used = async (
1162
+ c: Ctx,
1163
+ app: Eid,
1164
+ person: Eid | null = null,
1165
+ ): Promise<Resolved[]> => {
1166
+ let links = await connectedUses(c.graph.read, app, person)
1167
+ let all = await Promise.all(links.map(async ({ connection, link }) => ({
1168
+ connection,
1169
+ link,
1170
+ sentinels: await sentinelsOf(c, connection),
1171
+ })))
1172
+ return all.filter((r) => Object.keys(r.sentinels).length)
1173
+ }
1174
+
1175
+ let connectedUses = async (read: Read, app: Eid, person: Eid | null) => {
1176
+ let out = await links(read, 'from', app)
1177
+ if (!out.length) return []
1178
+ let found = await read(
1179
+ line`.entity.eid=${
1180
+ out.map((l) => far(l, 'from'))
1181
+ }&.${CONNECTION}.status=${'connected' satisfies Status}${sub(ALL)}`,
1182
+ )
1183
+ return found.map((connection) => ({
1184
+ connection,
1185
+ link: out.find((l) => far(l, 'from') == connection.entity.eid)!,
1186
+ })).filter((r) =>
1187
+ !comp(r.link, USES).each ||
1188
+ comp(r.connection, CONNECTION).owner == person
1189
+ )
1190
+ }
1191
+
1192
+ // The fields a connection's credential is kept as: its integration's, or one
1193
+ // key, which a sign-in's token is too.
1194
+ let fieldsFor = async (read: Read, b: Bundle): Promise<Field[]> => {
1195
+ let i = await known(read, String(comp(b, CONNECTION).integration))
1196
+ return i && keyed(i) ? fieldsOf(i) : fieldsOf()
1197
+ }
1198
+
1199
+ // The sentinel for each field of a connection's credential: the secret's own
1200
+ // for one, and one for each field of several; none while nothing is kept.
1201
+ let sentinelsOf = async (
1202
+ c: Ctx,
1203
+ b: Bundle,
1204
+ ): Promise<Record<string, string>> => {
1205
+ let fields = await fieldsFor(c.graph.read, b)
1206
+ let out: Record<string, string> = {}
1207
+ for (let f of fields) {
1208
+ let s = await sentinelOf(
1209
+ c.vault,
1210
+ nameOf(b),
1211
+ fields.length == 1 ? undefined : f.name,
1212
+ )
1213
+ if (s) out[f.name] = s
1214
+ }
1215
+ return out
1216
+ }
1217
+
1218
+ /** What an app's code is handed for each connected connection it uses, for a
1219
+ * person or for nobody in particular, by the name it reads it by: the sentinel
1220
+ * for its credential, or the credential itself where the link is direct. */
1221
+ export let envOf = (
1222
+ c: Ctx,
1223
+ app: Eid,
1224
+ person: Eid | null = null,
1225
+ ): Promise<Record<string, string>> =>
1226
+ bound(c, app, person, (u) => !!u.direct && u.lender == null)
1227
+
1228
+ /** What the host's own code reads for each connected connection an app of the
1229
+ * host's uses, by the name it reads it by: the credential itself, whatever the
1230
+ * link says, since that code is the host's and the key goes nowhere else.
1231
+ * yaks.app's own provider keys are its `platform` app's. When `unread` is
1232
+ * supplied, it hears a failed credential lookup and the other bindings still
1233
+ * answer. */
1234
+ export let keysOf = async (
1235
+ c: Ctx,
1236
+ app: Eid,
1237
+ unread?: (binding: string, error: unknown) => void,
1238
+ ): Promise<Record<string, string>> => {
1239
+ let uses = (await connectedUses(c.graph.read, app, null)).flatMap((r) => {
1240
+ let binding = comp(r.link, USES).binding
1241
+ return typeof binding == 'string' ? [{ ...r, binding }] : []
1242
+ })
1243
+ let integrations = await knownAll(c.graph.read, [
1244
+ ...new Set(uses.map(({ connection }) => integrated(connection))),
1245
+ ])
1246
+ let linked = uses.map((use) => ({
1247
+ ...use,
1248
+ integration: knownIn(integrations, integrated(use.connection)),
1249
+ }))
1250
+ let raw = await reveals(
1251
+ c.vault,
1252
+ linked.flatMap(({ connection, integration }) =>
1253
+ integration && keyed(integration) ? [nameOf(connection)] : []
1254
+ ),
1255
+ )
1256
+ let entries = await Promise.all(
1257
+ linked.map(({ connection, binding, integration }) =>
1258
+ keyEntries(
1259
+ c,
1260
+ connection,
1261
+ binding,
1262
+ integration,
1263
+ raw.get(nameOf(connection)),
1264
+ ).catch(
1265
+ (error) => {
1266
+ if (!unread) throw error
1267
+ unread(binding, error)
1268
+ return []
1269
+ },
1270
+ )
1271
+ ),
1272
+ )
1273
+ return Object.fromEntries(entries.flat())
1274
+ }
1275
+
1276
+ let keyEntries = async (
1277
+ c: Ctx,
1278
+ connection: Bundle,
1279
+ binding: string,
1280
+ i: Integration | undefined,
1281
+ raw: PromiseSettledResult<string | undefined> | undefined,
1282
+ ) => {
1283
+ let name = nameOf(connection)
1284
+ if (!i || !keyed(i)) {
1285
+ // A sign-in can refresh its grant. Only connections still holding one
1286
+ // in the vault can be used, as at the egress.
1287
+ if (!await sentinelOf(c.vault, name)) return []
1288
+ let value = await granted(c, connection)
1289
+ return value ? [[binding, value] as const] : []
1290
+ }
1291
+ if (raw?.status == 'rejected') throw raw.reason
1292
+ let fields = fieldsOf(i)
1293
+ let named = namesOf(binding, fields.map((f) => f.name))
1294
+ let values = await keyValues(c, connection, fields, raw?.value)
1295
+ return Object.entries(named).flatMap(([field, name]) =>
1296
+ values?.[field] ? [[name, values[field]] as const] : []
1297
+ )
1298
+ }
1299
+
1300
+ // Each connected connection `app` uses, by the name it reads it by: the
1301
+ // credential where `direct` says so, else its sentinel.
1302
+ let bound = async (
1303
+ c: Ctx,
1304
+ app: Eid,
1305
+ person: Eid | null,
1306
+ direct: (u: Comp) => boolean,
1307
+ ): Promise<Record<string, string>> => {
1308
+ let out: Record<string, string> = {}
1309
+ for (let r of await used(c, app, person)) {
1310
+ let u = comp(r.link, USES)
1311
+ if (typeof u.binding != 'string') continue
1312
+ let names = namesOf(u.binding, Object.keys(r.sentinels))
1313
+ for (let [f, name] of Object.entries(names)) {
1314
+ let value = direct(u)
1315
+ ? await credential(c, r.connection.entity.eid, f)
1316
+ : r.sentinels[f]
1317
+ if (value) out[name] = value
1318
+ }
1319
+ }
1320
+ return out
1321
+ }
1322
+
1323
+ /** The connection an app calls out through for an integration, for a person
1324
+ * or for nobody in particular, optionally by binding. It includes the
1325
+ * credential's sentinel. Whether the caller may use it is the egress's
1326
+ * question. */
1327
+ export let resolve = async (
1328
+ c: Ctx,
1329
+ app: Eid,
1330
+ integration: string,
1331
+ person: Eid | null = null,
1332
+ binding?: string,
1333
+ ): Promise<Resolved | undefined> => {
1334
+ let uses = (await used(c, app, person)).filter((r) =>
1335
+ comp(r.connection, CONNECTION).integration == integration
1336
+ )
1337
+ return binding == null ? byIntegration(uses) : boundAs(uses, binding)
1338
+ }
1339
+
1340
+ /** Choose an owner's account. Without a name, the person's own address wins,
1341
+ * otherwise the oldest connection. No remembered selection can let a newer
1342
+ * throwaway change what unattended commands use. */
1343
+ export let pick = async (
1344
+ read: Read,
1345
+ owner: Eid,
1346
+ integration: string,
1347
+ as?: string,
1348
+ ): Promise<Bundle | undefined> => {
1349
+ let found = (await read(
1350
+ line`.${CONNECTION}.owner=${owner}${sub(ALL)}&.order=created.at`,
1351
+ ))
1352
+ .filter((b) => comp(b, CONNECTION).integration == integration)
1353
+ let address = (b: Bundle) =>
1354
+ String(comp(b, CONNECTION).account ?? '').toLowerCase()
1355
+ if (as) {
1356
+ let name = as.toLowerCase()
1357
+ let exact = found.filter((b) => address(b) == name)
1358
+ let matches = exact.length
1359
+ ? exact
1360
+ : name.includes('@')
1361
+ ? []
1362
+ : found.filter((b) => address(b).split('@')[0] == name)
1363
+ let accounts = [...new Set(found.map((b) => comp(b, CONNECTION).account))]
1364
+ .filter((a): a is string => typeof a == 'string' && a != '')
1365
+ .sort()
1366
+ let available = `; available accounts: ${accounts.join(', ') || '(none)'}`
1367
+ if (matches.length > 1) {
1368
+ throw new AccountError(
1369
+ `${as} names several ${integration} accounts; use the whole address${available}`,
1370
+ )
1371
+ }
1372
+ if (!matches.length) {
1373
+ throw new AccountError(
1374
+ `no ${integration} account is named ${as}${available}`,
1375
+ )
1376
+ }
1377
+ return matches[0]
1378
+ }
1379
+ let [person] = await read(line`.entity.eid=${owner}&*`)
1380
+ let own = String(comp(person, 'email').address ?? '').toLowerCase()
1381
+ return found.find((b) => own && address(b) == own) ?? found[0]
1382
+ }
1383
+
1384
+ /** Every connection to one account of an integration, by its whole address,
1385
+ * whoever owns it: what goes when the account does. */
1386
+ export let toAccount = async (
1387
+ read: Read,
1388
+ integration: string,
1389
+ address: string,
1390
+ ): Promise<Bundle[]> =>
1391
+ (await read(line`.${CONNECTION}.integration=${integration}`)).filter((b) =>
1392
+ String(comp(b, CONNECTION).account ?? '').toLowerCase() ==
1393
+ address.toLowerCase()
1394
+ )
1395
+
1396
+ /** The address the provider returned. An id_token is used only to name an
1397
+ * account after the authenticated code exchange, never as authorization. */
1398
+ export let accountOf = async (
1399
+ integration: Integration,
1400
+ tokens: Tokens,
1401
+ fetcher: typeof fetch = fetch,
1402
+ ): Promise<string | undefined> =>
1403
+ (await signedIn(integration, tokens, fetcher)).account
1404
+
1405
+ // The account the provider returned, and what people call it where the
1406
+ // account is an id (`account_title`).
1407
+ let signedIn = async (
1408
+ integration: Integration,
1409
+ tokens: Tokens,
1410
+ fetcher: typeof fetch,
1411
+ ): Promise<{ account?: string; title?: string }> => {
1412
+ if (integration.account && tokens.account) {
1413
+ return { account: tokens.account, title: tokens.account_title }
1414
+ }
1415
+ let body: Record<string, unknown> = {}
1416
+ // An account the integration names is a path of its userinfo answer, so
1417
+ // an id_token is read only where it names none.
1418
+ let userinfo =
1419
+ tokens.access_token && (integration.account || !tokens.id_token)
1420
+ ? integration.userinfo
1421
+ : undefined
1422
+ if (userinfo) {
1423
+ let res = await fetcher(userinfo, {
1424
+ headers: {
1425
+ authorization: `Bearer ${tokens.access_token}`,
1426
+ accept: 'application/json',
1427
+ },
1428
+ redirect: 'manual',
1429
+ signal: AbortSignal.timeout(30_000),
1430
+ })
1431
+ if (!res.ok) {
1432
+ throw new Error(`the userinfo endpoint refused: ${res.status}`)
1433
+ }
1434
+ body = await res.json()
1435
+ } else if (tokens.id_token) {
1436
+ body = claims(tokens.id_token)
1437
+ if (!Object.keys(body).length) {
1438
+ throw new Error('the provider returned an invalid id_token')
1439
+ }
1440
+ }
1441
+ let at = (path?: string) => {
1442
+ let v = path?.split('.').reduce<unknown>(
1443
+ (at, k) => at && typeof at == 'object' ? (at as Comp)[k] : undefined,
1444
+ body,
1445
+ )
1446
+ return typeof v == 'string' || typeof v == 'number' ? String(v) : undefined
1447
+ }
1448
+ if (integration.account) {
1449
+ return {
1450
+ account: at(integration.account),
1451
+ title: at(integration.account_title),
1452
+ }
1453
+ }
1454
+ return {
1455
+ account: typeof body.email == 'string' && body.email.includes('@')
1456
+ ? body.email.toLowerCase()
1457
+ : undefined,
1458
+ }
1459
+ }
1460
+
1461
+ // The OAuth client for a connection: its integration's endpoints, the scopes
1462
+ // it was asked for, and its tokens kept as its own secret.
1463
+ let signIn = async (
1464
+ c: Ctx,
1465
+ b: Bundle,
1466
+ staged?: Tokens,
1467
+ again = false,
1468
+ ): Promise<Client> => {
1469
+ let name = String(comp(b, CONNECTION).integration)
1470
+ let i = await known(c.graph.read, name)
1471
+ return oauth(c, name, i, b, staged, again)
1472
+ }
1473
+
1474
+ let oauth = async (
1475
+ c: Ctx,
1476
+ name: string,
1477
+ i: Integration | undefined,
1478
+ b?: Bundle,
1479
+ staged?: Tokens,
1480
+ again = false,
1481
+ ): Promise<Client> => {
1482
+ if (!i?.authorize || !i.token) {
1483
+ throw new Error(
1484
+ `${name} is connected with a pasted key, not by signing in`,
1485
+ )
1486
+ }
1487
+ let registered = await clientOf(c.vault, c.graph.read, i)
1488
+ if (!connectable(i, registered)) {
1489
+ throw new Error(`no OAuth client is registered for ${name}`)
1490
+ }
1491
+ let scopes = strs(comp(b, CONNECTION).scopes)
1492
+ return client({
1493
+ authorize: i.authorize,
1494
+ token: i.token,
1495
+ scopes: scopes.length
1496
+ ? [
1497
+ ...new Set([
1498
+ ...scopes,
1499
+ ...(i.scopes ?? []).filter((s) => again || IDENTITY.has(s)),
1500
+ ]),
1501
+ ]
1502
+ : i.scopes,
1503
+ params: i.params,
1504
+ client: registered ?? (i.client_id ? { id: i.client_id } : undefined),
1505
+ auth: i.auth,
1506
+ scopeSeparator: i.scope_separator,
1507
+ pkce: i.pkce,
1508
+ refreshEncoding: i.refresh_encoding,
1509
+ answers: i.answers,
1510
+ resource: i.resource,
1511
+ issuer: i.issuer,
1512
+ account: i.account,
1513
+ account_title: i.account_title,
1514
+ }, {
1515
+ store: staged || !b
1516
+ ? {
1517
+ read: () => Promise.resolve(staged ?? {}),
1518
+ update: (_, fn) => fn(staged ?? {}),
1519
+ }
1520
+ : keeping(c, b),
1521
+ key: b ? nameOf(b) : '',
1522
+ redirect: c.redirect ?? '',
1523
+ fetch: c.fetch,
1524
+ now: c.now,
1525
+ })
1526
+ }
1527
+
1528
+ // The scopes that only say who signed in, which a provider may name its own
1529
+ // way in what it grants.
1530
+ let IDENTITY = new Set(['openid', 'email', 'profile'])
1531
+
1532
+ /** The scopes `i` now asks for that a connection holding `scopes` lacks, so
1533
+ * signing in again would give it more; none when what it holds is unknown. */
1534
+ export let lacking = (i: Integration, scopes: string[]): string[] => {
1535
+ let held = new Set(scopes)
1536
+ return scopes.length
1537
+ ? (i.scopes ?? []).filter((s) => !IDENTITY.has(s) && !held.has(s))
1538
+ : []
1539
+ }
1540
+
1541
+ // Restricted space services use a broker configuration dedicated to their
1542
+ // owner, so each can use its Workspace's internal OAuth app and scopes.
1543
+ let brokerConfig = (
1544
+ broker: NonNullable<Integration['broker']>,
1545
+ owner: unknown,
1546
+ ) =>
1547
+ broker.scoped ? `${broker.integration}-${String(owner)}` : broker.integration
1548
+
1549
+ /** The link to send a person to, to connect by signing in, and the attempt to
1550
+ * hold until they return. `again` signs a connection in again in place,
1551
+ * asking for every scope its integration now asks for: the same row, the
1552
+ * apps using it and its account, with a new grant. A brokered one is marked
1553
+ * `reconnecting` until `settle` finds the new grant at the broker. `began` is
1554
+ * the verified address of the person beginning it, which a brokered sign-in
1555
+ * must come back from to attach at once (`settle`). */
1556
+ export let begin = async (
1557
+ c: Ctx,
1558
+ connection: Eid | NewSignIn,
1559
+ again = false,
1560
+ began?: string,
1561
+ ): Promise<{ url: string; attempt?: Attempt & { verifier: string } }> => {
1562
+ let b = await signing(c.graph.read, connection)
1563
+ if (!again && typeof connection == 'string') await admitting(c, b)
1564
+ let i = await known(c.graph.read, String(comp(b, CONNECTION).integration))
1565
+ let alternative = mcpAlternative(i?.resource)
1566
+ if (alternative) throw new CallError('rejected', useIntegration(alternative))
1567
+ if (i?.broker) {
1568
+ if (typeof connection != 'string') {
1569
+ throw new Error('A broker needs a connection')
1570
+ }
1571
+ // A broker's sign-in returns to the broker, not to us: `settle` finds
1572
+ // it there afterwards by the connection's eid.
1573
+ let broker = await brokering(c, i.broker.name)
1574
+ if (
1575
+ i.broker.managed || !i.built && !i.owner && Array.isArray(i.categories)
1576
+ ) {
1577
+ await broker.enable(i.broker.integration, i.connects ?? 'signin')
1578
+ }
1579
+ let url = await broker.begin(
1580
+ brokerConfig(i.broker, comp(b, CONNECTION).owner),
1581
+ connection,
1582
+ began?.toLowerCase(),
1583
+ i.broker.scoped ? i.scopes : i.broker.managed
1584
+ ? [
1585
+ ...new Set([
1586
+ ...(i.scopes ?? []),
1587
+ ...strs(comp(b, CONNECTION).scopes),
1588
+ ]),
1589
+ ]
1590
+ : undefined,
1591
+ )
1592
+ if (again) {
1593
+ await c.graph.apply([{ entity: { eid: connection }, [RECONNECTING]: {} }])
1594
+ }
1595
+ return { url }
1596
+ }
1597
+ if (!c.redirect) throw new Error('signing in needs a redirect')
1598
+ return (await signIn(c, b, undefined, again)).begin()
1599
+ }
1600
+
1601
+ // The last two labels of a host: canva.com for mcp.canva.com.
1602
+ let domainOf = (url?: string) => {
1603
+ try {
1604
+ return new URL(url ?? '').host.split('.').slice(-2).join('.')
1605
+ } catch {
1606
+ return ''
1607
+ }
1608
+ }
1609
+
1610
+ /** An MCP server's sign-in page `url`, which `begin` gave for `connection`,
1611
+ * opened once before a person's browser is sent there. A server that takes
1612
+ * only the OAuth clients it lists can fail its page for any other:
1613
+ * mcp.canva.com answers 500 to a client from Canva's Developer Portal. That
1614
+ * refuses here in words, naming a built integration for the same service that
1615
+ * signs in another way, instead of sending them to the server's error page. A
1616
+ * page that can't be reached from here is left for the browser to try. */
1617
+ export let opens = async (c: Ctx, connection: Eid | NewSignIn, url: string) => {
1618
+ let b = await signing(c.graph.read, connection)
1619
+ let i = await known(c.graph.read, integrated(b))
1620
+ if (!i?.resource) return
1621
+ let res = await (c.fetch ?? fetch)(url, {
1622
+ redirect: 'manual',
1623
+ signal: AbortSignal.timeout(10_000),
1624
+ }).catch(() => undefined)
1625
+ await res?.body?.cancel()
1626
+ if (!res || res.status < 500) return
1627
+ let at = domainOf(i.resource)
1628
+ let other = (await installed(c.graph.read)).find((o) =>
1629
+ o.name != i.name && !o.resource && domainOf(o.site) == at
1630
+ )
1631
+ throw new CallError(
1632
+ 'rejected',
1633
+ `Sign-in to ${i.title ?? i.name} could not start.` +
1634
+ (other
1635
+ ? ` Connect ${
1636
+ other.title ?? other.name
1637
+ } from the list of services instead.`
1638
+ : ' Try connecting again later.'),
1639
+ )
1640
+ }
1641
+
1642
+ /** What an integration signs in with, where it is kept: its broker, when it
1643
+ * names one, else the OAuth client it names. `connectable` says whether
1644
+ * either is enough. */
1645
+ export let signsInWith = (
1646
+ vault: Vault,
1647
+ read: Read,
1648
+ i: Integration,
1649
+ ): Promise<unknown> =>
1650
+ i.broker ? brokerOf(vault, i.broker.name) : clientOf(vault, read, i)
1651
+
1652
+ // The broker named `name`, or a failure saying its key is not kept.
1653
+ let brokering = async (c: Ctx, name: string): Promise<Broker> => {
1654
+ let broker = await brokerOf(c.vault, name, c.fetch)
1655
+ if (!broker) throw new Error(`no key is kept for the ${name} broker`)
1656
+ return broker
1657
+ }
1658
+
1659
+ /** Connect a connection whose sign-in finished at its integration's broker,
1660
+ * once it has; nothing while it has not, or for one that is not needed or
1661
+ * not brokered. A broker's sign-in never returns to us, so whoever reads a
1662
+ * needed connection settles it: nothing waits on the broker telling us.
1663
+ *
1664
+ * A broker's link opens in any browser, so the account that approved there
1665
+ * may not be the beginner's. A grant attaches at once only when the account
1666
+ * it names is the address `begin` was given. Any other is held, attaching
1667
+ * nothing, and the connection is marked `approving` with the account that
1668
+ * approved, for that account to confirm (`approve`) or decline (`decline`).
1669
+ * The answer is the bundles written: the mark, when one is new, is the
1670
+ * caller's cue to ask the account. A hold unanswered for a day (`HOLD`) is
1671
+ * forgotten at the broker: by the run its write owes (`lapse`,
1672
+ * `connection_hold_lapse`), or by a read here or a press of `approve`,
1673
+ * whichever comes first. */
1674
+ export let settle = async (
1675
+ c: Ctx,
1676
+ connection: Eid,
1677
+ ): Promise<Bundle[]> => {
1678
+ let b = await held(c.graph.read, connection)
1679
+ let again = b[RECONNECTING] as Comp | undefined
1680
+ let waiting = b[APPROVING] as Comp | undefined
1681
+ let connected = comp(b, CONNECTION).status == 'connected' && !again
1682
+ if (connected && !waiting) return []
1683
+ let i = await known(c.graph.read, String(comp(b, CONNECTION).integration))
1684
+ if (!i?.broker) return []
1685
+ let broker = await brokerOf(c.vault, i.broker.name, c.fetch)
1686
+ if (!broker) return []
1687
+ let integration = brokerConfig(i.broker, comp(b, CONNECTION).owner)
1688
+ let now = (c.now ?? Date.now)()
1689
+ if (waiting && lapsedHold(waiting, now)) return forgetting(c, b, i)
1690
+ if (connected) return []
1691
+ let found = await broker.found(integration, connection)
1692
+ let kept = again
1693
+ ? await records<Kept>(c.graph, c.vault, '').read(nameOf(b))
1694
+ : undefined
1695
+ // A hold naming no account was never asked of anyone, so its grant is
1696
+ // read again rather than waited on.
1697
+ let asked = waiting?.account ? waiting.id : undefined
1698
+ if (!found || found.id == kept?.id || found.id == asked) {
1699
+ // Signing in again that found nothing new within the hour is let go.
1700
+ let stale = again && now - Date.parse(String(again.at)) > HOUR
1701
+ return stale
1702
+ ? c.graph.apply([{ entity: { eid: connection }, [RECONNECTING]: null }])
1703
+ : []
1704
+ }
1705
+ let grant = await broker.grant(integration, found.id)
1706
+ if (i.broker.scoped) {
1707
+ let required = new Set(i.scopes)
1708
+ let granted = new Set(grant.scopes)
1709
+ if (
1710
+ !required.size || granted.size != required.size ||
1711
+ [...required].some((scope) => !granted.has(scope))
1712
+ ) {
1713
+ await broker.forget(integration, found.id)
1714
+ throw new CallError(
1715
+ 'scope',
1716
+ `${i.title} requires exactly its listed scopes`,
1717
+ )
1718
+ }
1719
+ let account = await accountOf(
1720
+ i,
1721
+ { access_token: grant.access_token },
1722
+ c.fetch ?? fetch,
1723
+ )
1724
+ if (!account || account.toLowerCase() != found.began) {
1725
+ await broker.forget(integration, found.id)
1726
+ return []
1727
+ }
1728
+ return adopt(c, b, found.id, { ...grant, account: account.toLowerCase() })
1729
+ }
1730
+ let account = await grantAccount(c, i, grant)
1731
+ if (!account || account != found.began) {
1732
+ if (found.id == waiting?.id && !account) return []
1733
+ if (waiting && found.id != waiting.id) {
1734
+ await broker.forget(integration, String(waiting.id))
1735
+ .catch(c.report ?? (() => {}))
1736
+ }
1737
+ return c.graph.apply([{
1738
+ entity: { eid: connection },
1739
+ [APPROVING]: {
1740
+ id: found.id,
1741
+ account: account ?? '',
1742
+ at: new Date(now).toISOString(),
1743
+ ...found.began ? { began: found.began } : {},
1744
+ },
1745
+ }])
1746
+ }
1747
+ return adopt(c, b, found.id, grant)
1748
+ }
1749
+
1750
+ /** Connect the grant held for its approver (`settle`), once the account that
1751
+ * approved confirms it: `id` is the broker's id the hold names. Nothing for a
1752
+ * hold that is gone or names another grant. A hold past its day connects
1753
+ * nothing, and is forgotten: the answer is empty then too. */
1754
+ export let approve = async (
1755
+ c: Ctx,
1756
+ connection: Eid,
1757
+ id: string,
1758
+ ): Promise<Bundle[]> => {
1759
+ let b = await held(c.graph.read, connection)
1760
+ let waiting = comp(b, APPROVING)
1761
+ if (waiting.id != id) return []
1762
+ if (!lapsedHold(waiting, (c.now ?? Date.now)())) return adopt(c, b, id)
1763
+ await forgetting(c, b)
1764
+ return []
1765
+ }
1766
+
1767
+ /** Forget the grant held for its approver at the broker, when the account
1768
+ * that approved declines it. Nothing for a hold that is gone or names
1769
+ * another grant. */
1770
+ export let decline = async (
1771
+ c: Ctx,
1772
+ connection: Eid,
1773
+ id: string,
1774
+ ): Promise<Bundle[]> => {
1775
+ let b = await held(c.graph.read, connection)
1776
+ return comp(b, APPROVING).id == id ? forgetting(c, b) : []
1777
+ }
1778
+
1779
+ /** Forget the grant held for its approver at the broker, and its mark, once
1780
+ * the hold is a day old (`HOLD`): the run a hold's write owes
1781
+ * (`connection_hold_lapse`, ./effects.ts). The answer is how long the hold
1782
+ * has left, for one written since, or 0 once nothing is held: for a
1783
+ * connection gone, or a hold already answered or forgotten. */
1784
+ export let lapse = async (c: Ctx, connection: Eid): Promise<number> => {
1785
+ let [b] = await c.graph.read(
1786
+ line`.entity.eid=${connection}&.${CONNECTION}&.${APPROVING}`,
1787
+ )
1788
+ let waiting = b && comp(b, APPROVING)
1789
+ if (!waiting) return 0
1790
+ let rest = left(waiting, (c.now ?? Date.now)())
1791
+ if (rest <= 0) await forgetting(c, b)
1792
+ return Math.max(rest, 0)
1793
+ }
1794
+
1795
+ /** Forget at the broker what a connection that died held there: the run its
1796
+ * death owes (`connection_gone`, ./effects.ts), whether a disconnect or the
1797
+ * space or person that owned it took it. `was` is its `connection` as it
1798
+ * died. Every grant the broker holds for it goes, the one held for an
1799
+ * approver among them, but the grant it kept while it can still be restored:
1800
+ * while its owner stands and the vault retains its credential. Nothing for a
1801
+ * connection brought back since, and nothing is asked of a broker whose key
1802
+ * is not kept. */
1803
+ export let ended = async (
1804
+ c: Ctx,
1805
+ connection: Eid,
1806
+ was: Comp,
1807
+ ): Promise<void> => {
1808
+ let { read } = c.graph
1809
+ if ((await read(line`.entity.eid=${connection}&.${CONNECTION}`)).length) {
1810
+ return
1811
+ }
1812
+ let at = (await known(read, String(was.integration)))?.broker
1813
+ let kept = was.broker ? await retainedGrants(c.vault, connection) : []
1814
+ let owned = (await read(line`.entity.eid=${String(was.owner)}`)).length > 0
1815
+ // Without the broker's key, nothing can be asked of it: a grant the vault
1816
+ // kept says one is there, and asks with the key it lacks, which is reported.
1817
+ let broker = at && await brokerOf(c.vault, at.name, c.fetch)
1818
+ let integration = at && brokerConfig(at, was.owner)
1819
+ let found = at && broker && integration
1820
+ ? (await broker.grants(integration, connection))
1821
+ .map(({ id }) => ({ broker: at.name, integration, id }))
1822
+ : []
1823
+ let seen = new Set(owned ? kept.map(grantKey) : [])
1824
+ for (let g of [...found, ...kept]) {
1825
+ let key = grantKey(g)
1826
+ if (seen.has(key)) continue
1827
+ seen.add(key)
1828
+ await forgetGrant(c, g)
1829
+ }
1830
+ }
1831
+
1832
+ type BrokerGrant = Required<Kept>
1833
+
1834
+ /** The locator in a vaulted broker credential. Only these fields can leave
1835
+ * the vault as part of cleanup work. */
1836
+ export let grantOf = (value: string | undefined): BrokerGrant | undefined => {
1837
+ if (!value?.trimStart().startsWith('{')) return
1838
+ let kept: Kept | undefined
1839
+ try {
1840
+ kept = JSON.parse(value)
1841
+ } catch {
1842
+ return
1843
+ }
1844
+ let { broker, integration, id } = kept ?? {}
1845
+ if (
1846
+ typeof broker == 'string' && broker &&
1847
+ typeof integration == 'string' && integration &&
1848
+ typeof id == 'string' && id
1849
+ ) return { broker, integration, id }
1850
+ }
1851
+
1852
+ let grantKey = ({ broker, integration, id }: BrokerGrant) =>
1853
+ JSON.stringify([broker, integration, id])
1854
+
1855
+ let forgetGrant = async (c: Ctx, g: BrokerGrant): Promise<void> =>
1856
+ (await brokering(c, g.broker)).forget(g.integration, g.id)
1857
+
1858
+ let retainedGrants = async (vault: Vault, eid: Eid): Promise<BrokerGrant[]> => {
1859
+ let grants: BrokerGrant[] = []
1860
+ for (let t of await vault.trash()) {
1861
+ if (t.eid != eid) continue
1862
+ let grant = grantOf((await vault.past(t.id))?.value)
1863
+ if (grant) grants.push(grant)
1864
+ }
1865
+ return grants
1866
+ }
1867
+
1868
+ /** Forget a purged version's grant after checking the current restore paths. */
1869
+ export let forgetPurged = async (
1870
+ c: Ctx,
1871
+ eid: Eid,
1872
+ grant: BrokerGrant,
1873
+ ): Promise<void> => {
1874
+ if ((await c.graph.read(line`.entity.eid=${eid}&.${CONNECTION}`)).length) {
1875
+ return
1876
+ }
1877
+ let key = grantKey(grant)
1878
+ let active = grantOf((await c.vault.read(eid))?.value)
1879
+ if (active && grantKey(active) == key) return
1880
+ if ((await retainedGrants(c.vault, eid)).some((g) => grantKey(g) == key)) {
1881
+ return
1882
+ }
1883
+ await forgetGrant(c, grant)
1884
+ }
1885
+
1886
+ // How long the hold `waiting` has left at `now`, in ms.
1887
+ let left = (waiting: Comp, now: number) =>
1888
+ Date.parse(String(waiting.at)) + HOLD - now
1889
+
1890
+ /** Whether the hold `waiting` (a connection's `approving` mark) is a day old
1891
+ * at `now`: one `approve` connects nothing by. */
1892
+ export let lapsedHold = (waiting: Comp, now: number): boolean =>
1893
+ left(waiting, now) <= 0
1894
+
1895
+ // Forget the grant `b` holds for its approver at its integration's broker
1896
+ // (`i`, read when not given), then its mark. A broker that does not answer
1897
+ // throws, and the mark stays for the next try.
1898
+ let forgetting = async (c: Ctx, b: Bundle, i?: Integration) => {
1899
+ i ??= await known(c.graph.read, String(comp(b, CONNECTION).integration))
1900
+ let id = String(comp(b, APPROVING).id)
1901
+ if (i?.broker) {
1902
+ let integration = brokerConfig(i.broker, comp(b, CONNECTION).owner)
1903
+ await (await brokering(c, i.broker.name)).forget(integration, id)
1904
+ }
1905
+ return c.graph.apply([{
1906
+ entity: { eid: b.entity.eid },
1907
+ [APPROVING]: null,
1908
+ $was: { [APPROVING]: { id: token(id) } },
1909
+ }])
1910
+ }
1911
+
1912
+ // Connect the broker's grant `id` into `b`. Signing in again leaves the new
1913
+ // grant at the broker beside the one kept, which goes once the connection
1914
+ // holds the new one.
1915
+ let adopt = async (c: Ctx, b: Bundle, id: string, grant?: Grant) => {
1916
+ let keeps = records<Kept>(c.graph, c.vault, '')
1917
+ let kept = b[RECONNECTING] ? await keeps.read(nameOf(b)) : undefined
1918
+ let out = await connect(c, b.entity.eid, { brokered: id, grant })
1919
+ let now = kept && await keeps.read(nameOf(b))
1920
+ if (
1921
+ now?.id == id && kept?.id && kept.id != id && kept.broker &&
1922
+ kept.integration
1923
+ ) {
1924
+ await (await brokering(c, kept.broker)).forget(kept.integration, kept.id)
1925
+ .catch(c.report ?? (() => {}))
1926
+ }
1927
+ return out
1928
+ }
1929
+
1930
+ // The account a broker's grant names, lower-cased: the broker's word, else
1931
+ // what the service says of the token. A service that refuses to say fails.
1932
+ let grantAccount = async (c: Ctx, i: Integration, g: Grant) =>
1933
+ (g.account ?? await accountOf(i, g, c.fetch ?? fetch))?.toLowerCase()
1934
+
1935
+ let HOUR = 3_600_000
1936
+
1937
+ /** How long a grant held for the account that approved it waits for that
1938
+ * account's answer before it is forgotten at the broker: one day, in ms. */
1939
+ export let HOLD = 86_400_000
1940
+
1941
+ // A needed connection given its key or grant is one more its owner holds,
1942
+ // which the host may refuse (`admit`).
1943
+ let admitting = async (c: Ctx, b: Bundle) => {
1944
+ let { owner, status } = comp(b, CONNECTION)
1945
+ if (status == 'needed') await c.admit?.(String(owner))
1946
+ }
1947
+
1948
+ /** Exchange an installation begun at a provider. The grant is still unowned. */
1949
+ export let redeemInstallation = async (
1950
+ c: Ctx,
1951
+ i: Integration,
1952
+ code: string,
1953
+ ): Promise<Tokens> => {
1954
+ let grant = await (await oauth(c, i.name, i)).redeem(code)
1955
+ if (!grant.account) {
1956
+ throw new CallError('connection', 'Install the app in a workspace.')
1957
+ }
1958
+ return grant
1959
+ }
1960
+
1961
+ /** Bind a redeemed installation to the workspace's chosen space. */
1962
+ export let attachInstallation = async (
1963
+ c: Ctx,
1964
+ owner: Eid,
1965
+ integration: string,
1966
+ grant: Tokens,
1967
+ ): Promise<Bundle[]> => {
1968
+ let [b] = await c.graph.apply(
1969
+ await need(c.graph.read, { owner, integration }),
1970
+ )
1971
+ return keepGrant(
1972
+ c,
1973
+ b,
1974
+ grant,
1975
+ grant.account,
1976
+ grantWords(grant, grant.account_title),
1977
+ )
1978
+ }
1979
+
1980
+ let grantWords = (tokens: Tokens, title?: string): Comp => ({
1981
+ ...tokens.scope ? { scopes: tokens.scope.split(/\s+/) } : {},
1982
+ ...title ? { title } : {},
1983
+ })
1984
+
1985
+ /** Keep a connection's credential — a pasted key, or the grant a finished
1986
+ * sign-in returns — and mark it connected. */
1987
+ export let connect = async (
1988
+ c: Ctx,
1989
+ connection: Eid | NewSignIn,
1990
+ given: Given,
1991
+ account?: string,
1992
+ ): Promise<Bundle[]> => {
1993
+ let b = await signing(c.graph.read, connection)
1994
+ let now = {
1995
+ status: 'connected' satisfies Status,
1996
+ ...account ? { account } : {},
1997
+ }
1998
+ if ('key' in given || 'fields' in given) {
1999
+ if (typeof connection != 'string') {
2000
+ throw new Error('A key needs a connection')
2001
+ }
2002
+ let name = String(comp(b, CONNECTION).integration)
2003
+ let i = await known(c.graph.read, name)
2004
+ if (!i || (!keyed(i) && name != 'yaks.app')) {
2005
+ throw new Error(`${name} is connected by signing in, not with a key`)
2006
+ }
2007
+ let [reply] = await Promise.all([
2008
+ answered(c.graph.read, b, connection),
2009
+ admitting(c, b),
2010
+ ])
2011
+ let held = stillHeld(b)
2012
+ let expect = 'key' in given ? given.expect : undefined
2013
+ if (expect) held.$was![CONNECTION] = { status: token(expect) }
2014
+ return c.graph.apply([
2015
+ {
2016
+ ...pasted(b, name, fieldsOf(i), given),
2017
+ ...held,
2018
+ [CONNECTION]: now,
2019
+ },
2020
+ ...i.owner && !i.credentialed
2021
+ ? [{
2022
+ entity: { eid: integrationEid(name) },
2023
+ [INTEGRATION]: { credentialed: true },
2024
+ $was: { [INTEGRATION]: { hosts: token(i.hosts) } },
2025
+ }]
2026
+ : [],
2027
+ ...reply,
2028
+ ])
2029
+ }
2030
+ let i = await known(c.graph.read, String(comp(b, CONNECTION).integration))
2031
+ let tokens: Tokens & Kept = {}
2032
+ let made: Comp = {}
2033
+ let linked: Bundle[] = []
2034
+ if ('brokered' in given) {
2035
+ if (!i?.broker) throw new Error(`${i?.name} is not brokered`)
2036
+ let { name } = i.broker
2037
+ let integration = brokerConfig(i.broker, comp(b, CONNECTION).owner)
2038
+ let g = given.grant ??
2039
+ await (await brokering(c, name)).grant(integration, given.brokered)
2040
+ Object.assign(tokens, keptGrant(name, integration, given.brokered, g))
2041
+ account = await grantAccount(c, i, g)
2042
+ .catch((e) => (c.report?.(e), undefined)) ?? account
2043
+ made = { broker: name, ...g.scopes ? { scopes: g.scopes } : {} }
2044
+ } else {
2045
+ await (await signIn(c, b, tokens)).complete(given.attempt, given.callback)
2046
+ if (given.session) {
2047
+ Object.assign(tokens, { website_session: given.session })
2048
+ }
2049
+ let who = i ? await signedIn(i, tokens, c.fetch ?? fetch) : {}
2050
+ if (i?.chat_grant && !who.account) {
2051
+ throw new CallError('connection', 'Install the app in a workspace.')
2052
+ }
2053
+ if (typeof connection != 'string' && i?.account && !who.account) {
2054
+ throw new CallError(
2055
+ 'connection',
2056
+ 'The service did not identify the account.',
2057
+ )
2058
+ }
2059
+ account = who.account ?? account
2060
+ made = grantWords(tokens, who.title)
2061
+ if (i?.links && given.person) {
2062
+ linked = await linking(c, i.links, given.person, tokens)
2063
+ .catch((e) => (c.report?.(e), []))
2064
+ }
2065
+ }
2066
+ let saved = typeof connection == 'string'
2067
+ let write = () => keepGrant(c, b, tokens, account, made, linked, saved)
2068
+ try {
2069
+ return await write()
2070
+ } catch (e) {
2071
+ if (
2072
+ saved || !(e instanceof Stale) ||
2073
+ e.comp != 'tombstone' && !(e.comp == CONNECTION && e.prop == 'status')
2074
+ ) throw e
2075
+ return await write()
2076
+ }
2077
+ }
2078
+
2079
+ let forAccount = async (
2080
+ read: Read,
2081
+ grant: Comp,
2082
+ account: string,
2083
+ except?: Eid,
2084
+ ) => {
2085
+ let rows = (await read(
2086
+ line`.${CONNECTION}.owner=${
2087
+ String(grant.owner)
2088
+ }&.${CONNECTION}.integration=${String(grant.integration)}${sub(ALL)}`,
2089
+ )).filter((b) =>
2090
+ b.entity.eid != except &&
2091
+ String(comp(b, CONNECTION).account ?? '').toLowerCase() ==
2092
+ account.toLowerCase()
2093
+ )
2094
+ if (!rows.length) return
2095
+ let reserved = new Set(
2096
+ (await links(read, 'to', rows.map((b) => b.entity.eid)))
2097
+ .filter((l) => comp(l, USES).separate).map((l) => far(l, 'from')),
2098
+ )
2099
+ let shared = rows.filter((b) => !reserved.has(b.entity.eid))
2100
+ return shared.find((b) => comp(b, CONNECTION).status == 'connected') ??
2101
+ shared[0]
2102
+ }
2103
+
2104
+ let keepGrant = async (
2105
+ c: Ctx,
2106
+ b: Bundle,
2107
+ tokens: Tokens,
2108
+ account: string | undefined,
2109
+ made: Comp,
2110
+ linked: Bundle[] = [],
2111
+ saved = true,
2112
+ ): Promise<Bundle[]> => {
2113
+ let connection = b.entity.eid
2114
+ let grant = comp(b, CONNECTION)
2115
+ let binding = saved ? await separately(c.graph.read, connection) : undefined
2116
+ let kept = account && binding == null
2117
+ ? await forAccount(c.graph.read, grant, account, connection)
2118
+ : undefined
2119
+ let ask = !saved && !kept
2120
+ ? await firstAsk(
2121
+ c.graph.read,
2122
+ String(grant.owner),
2123
+ String(grant.integration),
2124
+ strs(grant.scopes),
2125
+ )
2126
+ : undefined
2127
+ let pending = comp(ask, CONNECTION).status == 'needed' ? ask : undefined
2128
+ // A different account never overwrites what the person already holds.
2129
+ let different = grant.status == 'connected' && grant.account && account &&
2130
+ String(grant.account).toLowerCase() != account.toLowerCase()
2131
+ let target = kept ?? pending ??
2132
+ (different || !saved
2133
+ ? fresh(
2134
+ String(grant.owner),
2135
+ String(grant.integration),
2136
+ strs(grant.scopes),
2137
+ binding == null ? account : undefined,
2138
+ )
2139
+ : b)
2140
+ if (!kept) await admitting(c, target)
2141
+ let transient = saved && kept && grant.status != 'connected'
2142
+ let out = transient
2143
+ ? await movedUses(c.graph.read, [connection], target.entity.eid)
2144
+ : []
2145
+ return c.graph.apply([
2146
+ ...saved ? [stillHeld(b)] : [],
2147
+ ...kept ? [stillHeld(kept)] : [],
2148
+ ...pending ? [stillNeeded(pending)] : [],
2149
+ {
2150
+ entity: { eid: target.entity.eid },
2151
+ ...target.$was ? { $was: target.$was } : {},
2152
+ [SECRET]: { name: nameOf(target), value: JSON.stringify(tokens) },
2153
+ [CONNECTION]: {
2154
+ ...comp(target, CONNECTION),
2155
+ ...made,
2156
+ status: 'connected',
2157
+ ...account ? { account } : {},
2158
+ },
2159
+ ...target[RECONNECTING] ? { [RECONNECTING]: null } : {},
2160
+ ...target[APPROVING] ? { [APPROVING]: null } : {},
2161
+ },
2162
+ ...out,
2163
+ ...transient
2164
+ ? [{ entity: { eid: connection }, tombstone: {} }]
2165
+ : b[RECONNECTING] && target.entity.eid != connection
2166
+ ? [{ entity: { eid: connection }, [RECONNECTING]: null }]
2167
+ : [],
2168
+ ...await answered(c.graph.read, b, target.entity.eid),
2169
+ ...linked,
2170
+ ])
2171
+ }
2172
+
2173
+ // The person's own connection through `name` that a sign-in through another
2174
+ // integration also names (`links`): Discord's bot added with `identify`
2175
+ // granted reads who added it at `/users/@me`, with the same token. It keeps
2176
+ // that token without its refresh token, so the two never race to rotate one
2177
+ // grant. A separately authorized refresh token stays with the person's own
2178
+ // connection. A failure to read who they are leaves the server sign-in standing.
2179
+ let linking = async (
2180
+ c: Ctx,
2181
+ name: string,
2182
+ person: Eid,
2183
+ tokens: Tokens,
2184
+ ): Promise<Bundle[]> => {
2185
+ let i = await known(c.graph.read, name)
2186
+ if (!i) throw new Error(`no integration ${name} to link`)
2187
+ let { refresh_token: _, account: _a, account_title: _t, ...own } = tokens
2188
+ let who = await signedIn(i, own, c.fetch ?? fetch)
2189
+ if (!who.account) throw new Error(`${name} named no account`)
2190
+ let existing = await forAccount(c.graph.read, {
2191
+ owner: person,
2192
+ integration: name,
2193
+ }, who.account)
2194
+ let ask = existing
2195
+ ? undefined
2196
+ : await firstAsk(c.graph.read, person, name, [])
2197
+ let pending = comp(ask, CONNECTION).status == 'needed' ? ask : undefined
2198
+ let target = existing ?? pending ??
2199
+ fresh(person, name, i.scopes ?? [], who.account)
2200
+ let previous = existing && comp(existing, CONNECTION).status == 'connected'
2201
+ ? await reveal(c.vault, nameOf(existing))
2202
+ : undefined
2203
+ let renewable = previous && (JSON.parse(previous) as Tokens).refresh_token
2204
+ return [
2205
+ {
2206
+ ...existing || pending ? stillHeld(target) : {},
2207
+ entity: { eid: target.entity.eid },
2208
+ ...renewable
2209
+ ? {}
2210
+ : { [SECRET]: { name: nameOf(target), value: JSON.stringify(own) } },
2211
+ [CONNECTION]: {
2212
+ ...comp(target, CONNECTION),
2213
+ status: 'connected',
2214
+ account: who.account,
2215
+ ...who.title ? { title: who.title } : {},
2216
+ },
2217
+ },
2218
+ ...await answered(c.graph.read, fresh(person, name, []), target.entity.eid),
2219
+ ]
2220
+ }
2221
+
2222
+ // What takes the place of `was`, links to a connection going away or no
2223
+ // longer lent: a connection needing a credential for each owner, and for
2224
+ // each separate binding. The app keeps its binding and access settings.
2225
+ // Borrowers keep their binding and ask in their own space.
2226
+ let reasked = async (b: Bundle, was: Bundle[], owners?: Owners) => {
2227
+ let { integration, owner, scopes } = comp(b, CONNECTION)
2228
+ let loans = was.filter((l) => comp(l, USES).lender != null)
2229
+ let whose = loans.length && owners
2230
+ ? await owners(loans.map((l) => far(l, 'to')))
2231
+ : {}
2232
+ let asks = new Map<string, Bundle>()
2233
+ let out: Bundle[] = []
2234
+ for (let l of was) {
2235
+ let app = far(l, 'to')
2236
+ let u = comp(l, USES)
2237
+ let at = u.lender == null ? String(owner) : whose[app]
2238
+ if (!at) {
2239
+ throw new Error(
2240
+ `no space is known for ${app}, which borrows ${b.entity.eid}`,
2241
+ )
2242
+ }
2243
+ let key = JSON.stringify([at, u.separate ? u.binding : null])
2244
+ let again = asks.get(key)
2245
+ if (!again) {
2246
+ asks.set(key, again = fresh(at, String(integration), strs(scopes)))
2247
+ out.push(again)
2248
+ }
2249
+ out.push({
2250
+ ...link(app, USES, again.entity.eid),
2251
+ [USES]: u.lender == null ? u : {
2252
+ binding: u.binding,
2253
+ ...u.separate ? { separate: true } : {},
2254
+ },
2255
+ })
2256
+ }
2257
+ return out
2258
+ }
2259
+
2260
+ /** Forget any grant held for its approver, then trash the connection. A
2261
+ * broker that does not answer stops neither: the run the connection's death
2262
+ * owes (`ended`) forgets what is left. Its attached credential and kept broker
2263
+ * grant stay available for restoration. The
2264
+ * apps that shared it are linked to a new connection. A copy that borrowed
2265
+ * it is linked to one in its own space, which `owners` says. An app that asks
2266
+ * each person for their own connection continues to ask them. */
2267
+ export let disconnect = async (
2268
+ c: Ctx,
2269
+ connection: Eid,
2270
+ owners?: Owners,
2271
+ ): Promise<Bundle[]> => {
2272
+ let b = await held(c.graph.read, connection)
2273
+ let was = (await links(c.graph.read, 'to', connection))
2274
+ .filter((l) => !comp(l, USES).each)
2275
+ let asks = await reasked(b, was, owners)
2276
+ if (b[APPROVING]) await forgetting(c, b).catch(c.report ?? (() => {}))
2277
+ return c.graph.apply([
2278
+ { entity: { eid: connection }, tombstone: {} },
2279
+ ...asks,
2280
+ ])
2281
+ }
2282
+
2283
+ // A step against the service's token endpoint. A grant the service refuses
2284
+ // marks the connection broken; a failure on the wire leaves it be.
2285
+ let marking = async (
2286
+ c: Ctx,
2287
+ connection: Bundle,
2288
+ step: () => Promise<string | undefined>,
2289
+ ): Promise<string | undefined> => {
2290
+ try {
2291
+ return await step()
2292
+ } catch (e) {
2293
+ if (
2294
+ e instanceof OAuthError && !e.code.startsWith('http_') ||
2295
+ e instanceof BrokerError && e.refused
2296
+ ) {
2297
+ await c.graph.apply([{
2298
+ ...stillHeld(connection),
2299
+ [CONNECTION]: { status: 'broken' satisfies Status },
2300
+ }])
2301
+ }
2302
+ throw e
2303
+ }
2304
+ }
2305
+
2306
+ // A connection's fields, as the vault keeps them. A voip.ms key pasted before
2307
+ // its integration named fields was its fields joined by colons; it is read so
2308
+ // and kept as the object it is now, behind the same handle, so its sentinels
2309
+ // hold. TODO: delete the colon reading once no such record is left.
2310
+ let fieldsKept = async (
2311
+ c: Ctx,
2312
+ b: Bundle,
2313
+ fields: Field[],
2314
+ raw: string,
2315
+ ): Promise<Record<string, string>> => {
2316
+ if (raw.trimStart().startsWith('{')) return JSON.parse(raw)
2317
+ let parts = raw.split(':')
2318
+ let said = Object.fromEntries(fields.map((f, n) => [
2319
+ f.name,
2320
+ (n < fields.length - 1 ? parts[n] : parts.slice(n).join(':'))?.trim() ??
2321
+ '',
2322
+ ]))
2323
+ await c.graph.apply([{
2324
+ entity: { eid: b.entity.eid },
2325
+ [SECRET]: { name: nameOf(b), value: JSON.stringify(said) },
2326
+ }])
2327
+ return said
2328
+ }
2329
+
2330
+ /** What a call out sends in a sentinel's place: the pasted key, one `field` of
2331
+ * several by name, or an access token, refreshed first when it is about to
2332
+ * expire. A credential kept as several fields is only ever read one at a
2333
+ * time. */
2334
+ /**
2335
+ * The bot token that speaks for a chat connection (`integration.chat`): the
2336
+ * pasted key of a bot the space brought, or, for one that added the
2337
+ * platform's own bot to a server, the bot of the OAuth client its
2338
+ * integration signs in as. None for a connection that does not chat, is not
2339
+ * connected (or not there at all), or whose bot is not kept yet.
2340
+ */
2341
+ export let botOf = async (
2342
+ c: Ctx,
2343
+ connection: Eid,
2344
+ ): Promise<string | undefined> => {
2345
+ let [b] = await c.graph.read(
2346
+ line`.entity.eid=${connection}&.${CONNECTION}${sub(ALL)}`,
2347
+ )
2348
+ if (comp(b, CONNECTION).status != 'connected') return undefined
2349
+ let i = await known(c.graph.read, String(comp(b, CONNECTION).integration))
2350
+ return botFrom(c, b, i)
2351
+ }
2352
+
2353
+ /** The bot token for a connection and integration already read together. */
2354
+ export let botFrom = async (
2355
+ c: Ctx,
2356
+ b: Bundle,
2357
+ i: Integration | undefined,
2358
+ ): Promise<string | undefined> => {
2359
+ if (comp(b, CONNECTION).status != 'connected' || !i?.chat) return undefined
2360
+ if (keyed(i)) return keyOf(c, b, i)
2361
+ if (i.chat_grant) {
2362
+ return marking(c, b, (await signIn(c, b)).token)
2363
+ }
2364
+ return (await clientOf(c.vault, c.graph.read, i))?.bot
2365
+ }
2366
+
2367
+ let keyOf = async (c: Ctx, b: Bundle, i: Integration, field?: string) => {
2368
+ let fields = fieldsOf(i)
2369
+ if (fields.length > 1 && field == null) {
2370
+ throw new Error(`${i.name} is kept as several fields; read one by name`)
2371
+ }
2372
+ let name = field ?? fields[0].name
2373
+ if (!fields.some((f) => f.name == name)) return undefined
2374
+ return (await keyFields(c, b, fields))?.[name]
2375
+ }
2376
+
2377
+ let keyFields = async (c: Ctx, b: Bundle, fields: Field[]) =>
2378
+ keyValues(c, b, fields, await reveal(c.vault, nameOf(b)))
2379
+
2380
+ let keyValues = (
2381
+ c: Ctx,
2382
+ b: Bundle,
2383
+ fields: Field[],
2384
+ raw: string | undefined,
2385
+ ) => {
2386
+ if (!raw) return undefined
2387
+ return fields.length == 1
2388
+ ? { [fields[0].name]: raw }
2389
+ : fieldsKept(c, b, fields, raw)
2390
+ }
2391
+
2392
+ export let credential = async (
2393
+ c: Ctx,
2394
+ connection: Eid,
2395
+ field?: string,
2396
+ ): Promise<string | undefined> => {
2397
+ let b = await held(c.graph.read, connection)
2398
+ let i = await known(c.graph.read, integrated(b))
2399
+ if (i && keyed(i)) return keyOf(c, b, i, field)
2400
+ if (field != null && field != fieldsOf()[0].name) return undefined
2401
+ return granted(c, b)
2402
+ }
2403
+
2404
+ /** Read both site sign-in fields from one version of the vaulted credential. */
2405
+ export let loginCredential = async (
2406
+ c: Ctx,
2407
+ connection: Bundle,
2408
+ ): Promise<{ username: string; password: string } | undefined> => {
2409
+ let i = await known(c.graph.read, integrated(connection))
2410
+ if (!i || !keyed(i) || !loginFields(fieldsOf(i))) return
2411
+ let fields = await keyFields(c, connection, fieldsOf(i))
2412
+ let { username, password } = fields ?? {}
2413
+ if (
2414
+ typeof username == 'string' && username && typeof password == 'string' &&
2415
+ password
2416
+ ) {
2417
+ return { username, password }
2418
+ }
2419
+ }
2420
+
2421
+ let granted = async (c: Ctx, b: Bundle): Promise<string | undefined> => {
2422
+ let raw = await reveal(c.vault, nameOf(b), { env: () => undefined })
2423
+ if (comp(b, CONNECTION).broker) {
2424
+ return marking(c, b, () => brokered(c, b))
2425
+ }
2426
+ if (raw && !raw.trimStart().startsWith('{')) return raw
2427
+ let oauth = await signIn(c, b)
2428
+ return marking(c, b, oauth.token)
2429
+ }
2430
+
2431
+ /** What the vault keeps for a brokered connection, beside its access token:
2432
+ * the broker it was made through, the broker's id for it, and what the broker
2433
+ * calls its integration. */
2434
+ type Kept = { broker?: string; id?: string; integration?: string }
2435
+
2436
+ let keptGrant = (
2437
+ broker: string,
2438
+ integration: string,
2439
+ id: string,
2440
+ g: Grant,
2441
+ ): Tokens & Kept => ({
2442
+ broker,
2443
+ integration,
2444
+ id,
2445
+ access_token: g.access_token,
2446
+ ...g.expires_at ? { expires_at: g.expires_at } : {},
2447
+ })
2448
+
2449
+ // A brokered connection's access token: the one kept while it is good for a
2450
+ // minute more, else the broker's, which the broker refreshes when it is due;
2451
+ // with `stale`, a new one unless another caller already replaced it. The
2452
+ // connection is asked of the broker it was made through, by what that broker
2453
+ // called its integration then, whatever its integration names now.
2454
+ let brokered = (c: Ctx, b: Bundle, stale?: string) => {
2455
+ let now = (c.now ?? Date.now)()
2456
+ return keeping(c, b).update(
2457
+ nameOf(b),
2458
+ async (r) => {
2459
+ let good = r.access_token &&
2460
+ (stale
2461
+ ? r.access_token != stale
2462
+ : r.expires_at && r.expires_at - now > 60_000)
2463
+ if (good) return r.access_token
2464
+ let { broker, integration, id } = r
2465
+ if (!broker || !integration || !id) {
2466
+ throw new Error(`${nameOf(b)} names no connection at its broker`)
2467
+ }
2468
+ let g = await (await brokering(c, broker)).grant(
2469
+ integration,
2470
+ id,
2471
+ !!stale,
2472
+ )
2473
+ if (!g.expires_at) delete r.expires_at
2474
+ Object.assign(r, keptGrant(broker, integration, id, g))
2475
+ return g.access_token
2476
+ },
2477
+ )
2478
+ }
2479
+
2480
+ /** A new access token behind the same handle, after the service refused
2481
+ * `stale`, unless another caller already replaced it. A grant the service
2482
+ * refuses marks the connection broken; a failure on the wire leaves it be. */
2483
+ export let refresh = async (
2484
+ c: Ctx,
2485
+ connection: Eid,
2486
+ stale: string,
2487
+ ): Promise<string | undefined> => {
2488
+ let b = await held(c.graph.read, connection)
2489
+ if (comp(b, CONNECTION).broker) {
2490
+ return marking(c, b, () => brokered(c, b, stale))
2491
+ }
2492
+ let oauth = await signIn(c, b)
2493
+ return marking(c, b, () => oauth.refresh(stale))
2494
+ }
2495
+
2496
+ /** Send a request through a connection for the one who holds it, its
2497
+ * credential as the bearer: over https to a host its integration names, and
2498
+ * to no other, following no redirect. A service that refuses the access token
2499
+ * (401) is asked once more with a refreshed one. */
2500
+ export let call = async (
2501
+ c: Ctx,
2502
+ connection: Eid,
2503
+ req: Request,
2504
+ ): Promise<Response> => {
2505
+ let b = await held(c.graph.read, connection)
2506
+ let name = String(comp(b, CONNECTION).integration)
2507
+ let i = await known(c.graph.read, name)
2508
+ let url = new URL(req.url)
2509
+ if (url.protocol != 'https:' || !i?.hosts.includes(url.host)) {
2510
+ throw new CallError(
2511
+ 'access',
2512
+ `${name} sends its credential to no ${url.host}`,
2513
+ )
2514
+ }
2515
+ let bearer = await credential(c, connection)
2516
+ if (!bearer) throw new CallError('missing', `${name} holds no credential yet`)
2517
+ let body = req.body ? await req.arrayBuffer() : undefined
2518
+ let send = (token: string) => {
2519
+ let headers = new Headers(req.headers)
2520
+ headers.set('authorization', `Bearer ${token}`)
2521
+ return (c.fetch ?? fetch)(url, {
2522
+ method: req.method,
2523
+ headers,
2524
+ body,
2525
+ redirect: 'manual',
2526
+ })
2527
+ }
2528
+ let res = await send(bearer)
2529
+ if (res.status != 401 || keyed(i)) return res
2530
+ let fresh = await refresh(c, connection, bearer)
2531
+ if (!fresh || fresh == bearer) return res
2532
+ await res.body?.cancel()
2533
+ return send(fresh)
2534
+ }
2535
+
2536
+ /** A selected account's bearer and optional website session, read privately
2537
+ * from its vault. The session is not handed to browser-only API doors. */
2538
+ export let accountCredential = async (
2539
+ ctx: Ctx,
2540
+ owner: Eid,
2541
+ integration: string,
2542
+ as?: string,
2543
+ ): Promise<
2544
+ { connection: Bundle; bearer: string; session?: string } | undefined
2545
+ > => {
2546
+ let connection = await pick(ctx.graph.read, owner, integration, as)
2547
+ if (!connection) return undefined
2548
+ let bearer = await credential(ctx, connection.entity.eid)
2549
+ if (!bearer) return undefined
2550
+ let raw = await reveal(ctx.vault, nameOf(connection), {
2551
+ env: () => undefined,
2552
+ })
2553
+ let session: string | undefined
2554
+ try {
2555
+ let record = JSON.parse(raw ?? '{}')
2556
+ session = typeof record.website_session == 'string'
2557
+ ? record.website_session
2558
+ : undefined
2559
+ } catch { /* A pasted key is not an OAuth record. */ }
2560
+ return { connection, bearer, ...session ? { session } : {} }
2561
+ }