@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.js ADDED
@@ -0,0 +1,1961 @@
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
+ import { line, sub } from "@yaks/query";
63
+ import { CallError } from "@yaks/tools/errors";
64
+ import { Stale } from "@yaks/graph/errors";
65
+ import { identityEid } from "@yaks/graph/identity";
66
+ import { token } from "@yaks/graph/sha256";
67
+ import { edgeEid, link } from "@yaks/edge";
68
+ import { claims, client, OAuthError } from "@yaks/oauth";
69
+ import { records, reveal, reveals, secretEid, sentinelOf } from "@yaks/secrets";
70
+ import { connectable, fieldsOf, installed, keyed, known, knownAll, knownIn, set, told } from "./integrations.js";
71
+ import { APPROVING, ASKS, CONNECTION, INTEGRATION, integrationEid, USES } from "./identity.js";
72
+ import { through } from "./graph.js";
73
+ import { pasted } from "./paste.js";
74
+ import { loginFields } from "./field.js";
75
+ import { clientOf } from "./clients.js";
76
+ import { BrokerError, brokerOf } from "./brokers.js";
77
+ import { mcpAlternative, useIntegration } from "./mcp-signin.js";
78
+ let SECRET = 'secret';
79
+ let RECONNECTING = 'reconnecting';
80
+ let EDGE = 'edge';
81
+ /** An explicit account name did not select one connection: a refusal of the
82
+ * caller's own input, not a fault. */ export class AccountError extends CallError {
83
+ constructor(message){
84
+ super('arguments', message);
85
+ this.name = 'AccountError';
86
+ }
87
+ }
88
+ let comp = (b, name)=>b?.[name] ?? {};
89
+ let strs = (v)=>Array.isArray(v) ? v.map(String) : [];
90
+ // Reads are filter lines, the form every door to a graph takes, so these verbs
91
+ // run over a graph in this process or one behind HTTP alike (yaks.app's
92
+ // directory). What a line here spells is an eid or a word of this package's,
93
+ // never a name somebody chose, which a line would have to quote: a connection's
94
+ // integration is compared here, after the read. A line answers the components
95
+ // it names, so one that needs the rest of an entity asks for them (`*`).
96
+ let ALL = line`&*`;
97
+ let nameOf = (b)=>String(comp(b, SECRET).name);
98
+ let integrated = (b)=>String(comp(b, CONNECTION).integration);
99
+ // A new connection, needing a credential, under a name of its own.
100
+ let fresh = (owner, integration, scopes, account)=>{
101
+ let id = account ? identityEid('connection-account', [
102
+ owner,
103
+ integration,
104
+ account.toLowerCase()
105
+ ]) : crypto.randomUUID();
106
+ let name = `${CONNECTION}:${id}`;
107
+ return {
108
+ entity: {
109
+ eid: secretEid(name)
110
+ },
111
+ [CONNECTION]: {
112
+ integration,
113
+ owner,
114
+ ...scopes.length ? {
115
+ scopes
116
+ } : {},
117
+ status: 'needed'
118
+ },
119
+ [SECRET]: {
120
+ name
121
+ }
122
+ };
123
+ };
124
+ // The connection as the graph holds it, or a refusal naming it.
125
+ let held = async (read, eid)=>{
126
+ let [b] = await read(line`.entity.eid=${eid}&.${CONNECTION}${sub(ALL)}`);
127
+ if (!b) throw new Error(`no connection ${eid}`);
128
+ return b;
129
+ };
130
+ let signing = (read, connection)=>typeof connection == 'string' ? held(read, connection) : fresh(connection.owner, connection.integration, []);
131
+ // An exchange may outlast the connection it started on.
132
+ let stillHeld = (row)=>({
133
+ entity: row.entity,
134
+ $was: {
135
+ entity: {
136
+ eid: token(row.entity.eid)
137
+ },
138
+ tombstone: {
139
+ '': null
140
+ }
141
+ }
142
+ });
143
+ let keeping = (c, b)=>records({
144
+ apply: (rows)=>c.graph.apply([
145
+ stillHeld(b),
146
+ ...rows
147
+ ])
148
+ }, c.vault, '');
149
+ // The `uses` links at one end, and the far end of one.
150
+ let links = (read, at, eid)=>read(line`.${EDGE}.${at}=${eid}&.${USES}${sub(ALL)}`);
151
+ let far = (l, at)=>String(comp(l, EDGE)[at == 'from' ? 'to' : 'from']);
152
+ let appUses = async (read, a)=>{
153
+ let out = (await links(read, 'from', a.app)).filter((l)=>!comp(l, USES).each == !a.each);
154
+ if (!out.length) return [];
155
+ let found = await read(line`.entity.eid=${out.map((l)=>far(l, 'from'))}&.${CONNECTION}`);
156
+ return found.flatMap((b)=>{
157
+ let c = comp(b, CONNECTION);
158
+ if (c.integration != a.integration || a.each && c.owner != a.owner) {
159
+ return [];
160
+ }
161
+ return [
162
+ {
163
+ connection: b,
164
+ link: out.find((l)=>far(l, 'from') == b.entity.eid)
165
+ }
166
+ ];
167
+ });
168
+ };
169
+ let boundAs = (uses, binding)=>uses.find((m)=>comp(m.link, USES).binding == binding);
170
+ let shared = (uses)=>uses.find((m)=>!comp(m.link, USES).separate);
171
+ let byIntegration = (uses)=>shared(uses) ?? (uses.length == 1 ? uses[0] : undefined);
172
+ let usingLink = async (read, a)=>{
173
+ let uses = await appUses(read, a);
174
+ return a.binding == null ? byIntegration(uses) : boundAs(uses, a.binding);
175
+ };
176
+ /** The connection an app uses through an integration, optionally by binding.
177
+ * With `each`, it is the one `owner` holds. */ export let using = async (read, a)=>(await usingLink(read, a))?.connection;
178
+ let same = (a, b)=>[
179
+ ...a
180
+ ].sort().join('\n') == [
181
+ ...b
182
+ ].sort().join('\n');
183
+ // What a custom integration's fields say, checked: each a name an app can
184
+ // read, said once, with a label a person reads.
185
+ let FIELD = /^[a-z][a-z0-9_]{0,31}$/;
186
+ let fielded = (fields)=>{
187
+ let out = fields.map((f)=>({
188
+ name: String(f.name ?? ''),
189
+ label: String(f.label ?? '').trim(),
190
+ ...f.shown ? {
191
+ shown: true
192
+ } : {},
193
+ ...f.example ? {
194
+ example: f.example
195
+ } : {}
196
+ }));
197
+ for (let f of out){
198
+ if (!FIELD.test(f.name)) {
199
+ throw new CallError('fields', `${f.name} is not a field name: lowercase letters, digits and ` + `underscores, starting with a letter`);
200
+ }
201
+ if (!f.label) throw new CallError('fields', `${f.name} needs a label`);
202
+ }
203
+ if (new Set(out.map((f)=>f.name)).size < out.length) {
204
+ throw new CallError('fields', 'each field is named once');
205
+ }
206
+ return out;
207
+ };
208
+ // A binding is a name in the app's own code, so it must be one.
209
+ let NAME = /^[A-Za-z_][A-Za-z0-9_]{0,63}$/;
210
+ /** The names an app's code reads a connection by, by field name: its
211
+ * binding, for one key or a sign-in, or for several fields the binding and
212
+ * each field's name in capitals, `S3_ACCESS_KEY_ID`. */ export let namesOf = (binding, fields)=>fields.length == 1 ? {
213
+ [fields[0]]: binding
214
+ } : Object.fromEntries(fields.map((f)=>[
215
+ f,
216
+ `${binding}_${f.toUpperCase()}`
217
+ ]));
218
+ /** The name an app reads an integration's connection by when it names none:
219
+ * `google-calendar` is `GOOGLE_CALENDAR`. */ export let bindingOf = (integration)=>integration.toUpperCase().replace(/[^A-Z0-9]+/g, '_').replace(/^(?=\d)/, '_').slice(0, 64);
220
+ // The link from an app, saying what its code reads the connection by,
221
+ // whether each person connects their own, and whether visitors call out
222
+ // through it where that was said.
223
+ let linked = (app, to, u)=>({
224
+ ...link(app, USES, to),
225
+ [USES]: {
226
+ binding: u.binding,
227
+ ...u.direct ? {
228
+ direct: true
229
+ } : {},
230
+ ...u.each ? {
231
+ each: true
232
+ } : {},
233
+ ...u.separate ? {
234
+ separate: true
235
+ } : {},
236
+ ...u.anyone == null ? {} : {
237
+ anyone: u.anyone
238
+ }
239
+ }
240
+ });
241
+ // The asks `owner` has standing through an integration for these scopes:
242
+ // shared connections needing a credential, grouped by binding for separate asks.
243
+ let withScopes = async (read, owner, integration, scopes, status)=>(await read(line`.${CONNECTION}.owner=${owner}&.${CONNECTION}.integration=${integration}&.${CONNECTION}.status=${status}`)).filter((b)=>same(strs(comp(b, CONNECTION).scopes), scopes));
244
+ let inGroup = async (read, needed, binding)=>{
245
+ if (!needed.length) return [];
246
+ let used = await links(read, 'to', needed.map((b)=>b.entity.eid));
247
+ return needed.filter((b)=>{
248
+ let uses = used.filter((l)=>far(l, 'from') == b.entity.eid).map((l)=>comp(l, USES));
249
+ return binding == null ? uses.every((u)=>!u.each && !u.separate) : uses.length > 0 && uses.every((u)=>u.separate && u.binding == binding);
250
+ });
251
+ };
252
+ let asksOf = async (read, owner, integration, scopes, binding)=>inGroup(read, await withScopes(read, owner, integration, scopes, 'needed'), binding);
253
+ let firstAsk = async (read, owner, integration, scopes)=>{
254
+ let [ask] = await asksOf(read, owner, integration, scopes);
255
+ return ask && (await read(line`.entity.eid=${ask.entity.eid}&.${CONNECTION}${sub(ALL)}`))[0];
256
+ };
257
+ let stillNeeded = (b)=>{
258
+ let held = stillHeld(b);
259
+ held.$was[CONNECTION] = {
260
+ status: token('needed')
261
+ };
262
+ return held;
263
+ };
264
+ // A separate credential only answers other asks for its binding.
265
+ let separately = async (read, eid)=>(await links(read, 'to', eid)).map((l)=>comp(l, USES)).find((u)=>u.separate)?.binding;
266
+ let movedUses = async (read, from, to)=>{
267
+ let uses = await links(read, 'to', [
268
+ ...from,
269
+ to
270
+ ]);
271
+ let kept = new Set(uses.filter((l)=>far(l, 'from') == to).map((l)=>far(l, 'to')));
272
+ let moved = [];
273
+ for (let l of uses){
274
+ if (far(l, 'from') == to) continue;
275
+ let app = far(l, 'to');
276
+ if (kept.has(app)) continue;
277
+ kept.add(app);
278
+ moved.push({
279
+ ...link(app, USES, to),
280
+ [USES]: comp(l, USES)
281
+ });
282
+ }
283
+ return moved;
284
+ };
285
+ // What connecting `b` answers: every other ask its owner has standing through
286
+ // the same integration and scopes closes, and each app it served is linked to
287
+ // `to`, the connection now connected, as it was to the ask.
288
+ let answered = async (read, b, to)=>{
289
+ let c = comp(b, CONNECTION);
290
+ let needed = (await withScopes(read, String(c.owner), String(c.integration), strs(c.scopes), 'needed')).filter((o)=>o.entity.eid != b.entity.eid && o.entity.eid != to);
291
+ if (!needed.length) return [];
292
+ let asks = await inGroup(read, needed, await separately(read, b.entity.eid));
293
+ if (!asks.length) return [];
294
+ return [
295
+ ...asks.map((o)=>({
296
+ ...stillNeeded(o),
297
+ tombstone: {}
298
+ })),
299
+ ...await movedUses(read, asks.map((o)=>o.entity.eid), to)
300
+ ];
301
+ };
302
+ /** Make a connection needing a credential, linked from the app that needs it,
303
+ * with the custom integration a key for an unbuilt service needs — made only
304
+ * where no integration holds the name, so it never writes over one, and owned
305
+ * by whoever made it. Its hosts may wait: a key kept before anyone uses it is
306
+ * sent nowhere, and its owner may name them once. On a new integration the
307
+ * owner can correct hosts until its first credential. What is said about it (`About`) is written with it, or
308
+ * changed by its owner asking again. An ask the owner already has standing
309
+ * through that integration for the same scopes is reused. With `separate`,
310
+ * the binding also identifies the ask. With `each`, each owner asks for
311
+ * their own. The connection comes first. */ export let need = async (read, a, request = false)=>{
312
+ let keep = placesOf(a.keep);
313
+ if (keep.length) {
314
+ let i = await known(read, a.integration);
315
+ if (i && !keyed(i)) {
316
+ throw new CallError('keep', `${a.integration} is connected by signing in, and only a pasted key ` + `is kept anywhere but the vault`);
317
+ }
318
+ }
319
+ let [made, ...rest] = await asked(read, a, request);
320
+ let eid = made.entity.eid;
321
+ return [
322
+ keep.length ? {
323
+ ...made,
324
+ [CONNECTION]: {
325
+ ...comp(made, CONNECTION),
326
+ keep
327
+ }
328
+ } : made,
329
+ ...rest,
330
+ ...a.task ? [
331
+ {
332
+ ...link(a.task, ASKS, eid),
333
+ [ASKS]: {}
334
+ }
335
+ ] : []
336
+ ];
337
+ };
338
+ // The places a key is kept, each a keeper's name and its address there.
339
+ let placesOf = (keep = [])=>keep.map(({ via, at })=>{
340
+ if (!String(via ?? '').trim() || !String(at ?? '').trim()) {
341
+ throw new CallError('keep', 'each place names a keeper (via) and where (at)');
342
+ }
343
+ return {
344
+ via: String(via).trim(),
345
+ at: String(at).trim()
346
+ };
347
+ });
348
+ let asked = async (read, a, request)=>{
349
+ let hosts = a.hosts ?? [];
350
+ let name = a.integration;
351
+ let i = await known(read, name);
352
+ let fields = (!i || !request) && a.fields?.length ? fielded(a.fields) : [];
353
+ let catalog = i?.built && request;
354
+ let about = catalog ? {} : told(a);
355
+ if (fields.length && i && !i.fields?.length) {
356
+ throw new CallError('fields', `${name} is connected with ${keyed(i) ? 'one key' : 'a sign-in'}, and its fields never change`);
357
+ }
358
+ if (fields.length && i?.fields && JSON.stringify(fielded(i.fields)) != JSON.stringify(fields)) {
359
+ throw new CallError('fields', `${name} already asks for ${i.fields.map((f)=>f.name).join(', ')}`);
360
+ }
361
+ if (hosts.length && i?.built && !catalog) {
362
+ throw new CallError('hosts', `${name} is built, and sends its credential to its own hosts`);
363
+ }
364
+ let naming = i && !catalog && a.hosts != null && !same(i.hosts, hosts) ? i : undefined;
365
+ if (naming && naming.owner != a.owner) {
366
+ throw new CallError('hosts', `only the space or person that made ${name} names its hosts`);
367
+ }
368
+ if (naming && naming.hosts.length && (naming.credentialed || (await read(line`.${CONNECTION}.integration=${name}&.secret.value&.limit=1&.fields=entity.eid`)).length)) {
369
+ throw new CallError('hosts', `${name} already sends its key to ${naming.hosts.join(', ')}`);
370
+ }
371
+ let binding = a.binding ?? bindingOf(name);
372
+ if (a.separate && (!a.app || a.binding == null || a.each)) {
373
+ throw new CallError('separate', 'A separate connection needs an app and a binding shared by its callers');
374
+ }
375
+ if (!NAME.test(binding)) {
376
+ throw new CallError('binding', `${binding} is not a name code can read: letters, digits and ` + `underscores, not starting with a digit`);
377
+ }
378
+ if (a.direct && i && !keyed(i)) {
379
+ throw new CallError('direct', `${name} is connected by signing in, and only a pasted key is handed ` + `to an app directly`);
380
+ }
381
+ if (a.direct && a.each) {
382
+ throw new CallError('direct', `a key each person connects is theirs, and is never handed to the app`);
383
+ }
384
+ let u = {
385
+ binding,
386
+ direct: !!a.direct,
387
+ each: a.each,
388
+ separate: a.separate
389
+ };
390
+ if (a.app && i?.broker?.scoped) {
391
+ throw new CallError('connection', `${name} is reserved for its space service`);
392
+ }
393
+ // Said again of one that stands, it is its owner's change to make.
394
+ let retold = [
395
+ ...i && Object.keys(about).length ? await set(read, a) : [],
396
+ ...naming ? [
397
+ {
398
+ entity: {
399
+ eid: integrationEid(name)
400
+ },
401
+ [INTEGRATION]: {
402
+ hosts
403
+ },
404
+ // Refused, rather than written over, where they were named meanwhile.
405
+ $was: {
406
+ [INTEGRATION]: {
407
+ hosts: token(naming.hosts),
408
+ credentialed: token(naming.credentialed ?? null)
409
+ }
410
+ }
411
+ }
412
+ ] : []
413
+ ];
414
+ let uses = a.app ? await appUses(read, {
415
+ ...a,
416
+ app: a.app
417
+ }) : [];
418
+ let used = (a.binding != null ? boundAs(uses, binding) : undefined) ?? (a.separate ? undefined : shared(uses) ?? boundAs(uses, binding));
419
+ if (used) {
420
+ if (a.direct) {
421
+ let loan = comp(used.link, USES);
422
+ if (loan.lender != null || loan.lends != null) {
423
+ throw new CallError('direct', loan.lender != null ? 'A borrowed connection only supplies a sentinel; connect your own key first' : 'Stop lending this connection before handing its key to the app');
424
+ }
425
+ }
426
+ let said = a.binding != null || a.direct != null;
427
+ let patch = {
428
+ ...a.binding != null ? {
429
+ binding: a.binding
430
+ } : {},
431
+ ...a.direct != null ? {
432
+ direct: a.direct || null
433
+ } : {}
434
+ };
435
+ return [
436
+ // Answered with the integration it goes through, as it already does.
437
+ {
438
+ entity: {
439
+ eid: used.connection.entity.eid
440
+ },
441
+ [CONNECTION]: {
442
+ integration: name
443
+ }
444
+ },
445
+ ...said ? [
446
+ {
447
+ ...link(a.app, USES, used.connection.entity.eid),
448
+ [USES]: patch
449
+ }
450
+ ] : [],
451
+ ...retold
452
+ ];
453
+ }
454
+ // An owner-only request can reuse a saved credential without granting it
455
+ // to a new app. Otherwise reuse the open ask for the same scopes and group.
456
+ let saved = !request || a.app || a.each || a.task || a.keep?.length ? undefined : (await inGroup(read, await withScopes(read, a.owner, name, a.scopes ?? [], 'connected')))[0];
457
+ let standing = saved ?? (a.each ? undefined : (await asksOf(read, a.owner, name, a.scopes ?? [], a.separate ? binding : undefined))[0]);
458
+ if (standing) {
459
+ return [
460
+ {
461
+ entity: {
462
+ eid: standing.entity.eid
463
+ },
464
+ [CONNECTION]: {
465
+ integration: name
466
+ }
467
+ },
468
+ ...retold,
469
+ ...a.app ? [
470
+ linked(a.app, standing.entity.eid, u)
471
+ ] : []
472
+ ];
473
+ }
474
+ let made = fresh(a.owner, name, a.scopes ?? []);
475
+ let written = Object.fromEntries(Object.entries(about).filter(([, v])=>v != null));
476
+ return [
477
+ made,
478
+ ...i ? retold : [
479
+ {
480
+ entity: {
481
+ eid: integrationEid(name)
482
+ },
483
+ [INTEGRATION]: {
484
+ name,
485
+ hosts,
486
+ ...fields.length ? {
487
+ fields
488
+ } : {},
489
+ owner: a.owner,
490
+ ...written
491
+ },
492
+ // Refused, rather than written over, where one was made meanwhile.
493
+ $was: {
494
+ [INTEGRATION]: {
495
+ name: null
496
+ }
497
+ }
498
+ }
499
+ ],
500
+ ...a.app ? [
501
+ linked(a.app, made.entity.eid, u)
502
+ ] : []
503
+ ];
504
+ };
505
+ // Whether a link may lend its connection: a sentinel every caller shares, on
506
+ // a connection the app's own space keeps rather than borrows.
507
+ let lendable = (u)=>!u.each && !u.direct && u.lender == null;
508
+ // The copy's link to the connection its source app lends, capped as lent.
509
+ let borrowing = (app, lent, lender)=>{
510
+ let u = comp(lent, USES);
511
+ return {
512
+ ...link(app, USES, far(lent, 'from')),
513
+ [USES]: {
514
+ binding: u.binding,
515
+ cap: u.lends,
516
+ lender,
517
+ ...u.separate ? {
518
+ separate: true
519
+ } : {}
520
+ }
521
+ };
522
+ };
523
+ /** What a copy of an app asks for, read off the app it was copied from: for
524
+ * each connection the source uses and the copy does not yet, a connection
525
+ * needing a credential, owned by `owner`, the copy's space, and linked from the
526
+ * copy as `need` makes one. It goes through the same integration, is read by
527
+ * the same binding, as directly, for each person where the source asks each,
528
+ * and asks for the same scopes. A credential never travels, and neither does a
529
+ * link opened to anyone, which is the person's act. Where the source lends a
530
+ * connected connection (`lend`), the copy borrows it instead: a link to that
531
+ * same connection, capped at what the source lends and naming it the
532
+ * `lender`, which the host writes as itself since only it sets a cap. An
533
+ * install and an update both ask it, so an update adds what its version gained
534
+ * and leaves what the copy already uses as its person made it. */ export let carry = async (read, a)=>{
535
+ let out = await links(read, 'from', [
536
+ a.source,
537
+ a.app
538
+ ]);
539
+ if (!out.length) return [];
540
+ let to = await read(line`.entity.eid=${out.map((l)=>far(l, 'from'))}&.${CONNECTION}`);
541
+ // One ask for each integration and mode, with a binding for separate asks.
542
+ let had = new Set();
543
+ let asks = new Map();
544
+ for (let l of out){
545
+ let c = comp(to.find((b)=>b.entity.eid == far(l, 'from')), CONNECTION);
546
+ let u = comp(l, USES);
547
+ // A link naming no binding is a person's grant of their own source
548
+ // (./sources.ts), not something the app's code asks for.
549
+ if (u.binding == null && u.lender == null) continue;
550
+ let each = u.each == true;
551
+ let key = JSON.stringify([
552
+ each,
553
+ c.integration,
554
+ u.separate ? u.binding : null
555
+ ]);
556
+ if (comp(l, EDGE).from == a.app) {
557
+ if (!each || c.owner == a.owner) had.add(key);
558
+ } else if (lendable(u) && typeof u.lends == 'number' && c.status == 'connected') {
559
+ asks.set(key, borrowing(a.app, l, a.source));
560
+ } else if (typeof c.integration == 'string') {
561
+ asks.set(key, {
562
+ owner: a.owner,
563
+ app: a.app,
564
+ integration: c.integration,
565
+ scopes: strs(c.scopes),
566
+ each,
567
+ binding: typeof u.binding == 'string' ? u.binding : undefined,
568
+ direct: u.direct == true,
569
+ separate: u.separate == true
570
+ });
571
+ }
572
+ }
573
+ let made = await Promise.all([
574
+ ...asks
575
+ ].filter(([key])=>!had.has(key)).map(([, ask])=>'entity' in ask ? [
576
+ ask
577
+ ] : need(read, ask)));
578
+ return made.flat();
579
+ };
580
+ /** Lend the connection an app uses through an integration to every copy
581
+ * installed from it, from then on: each copy borrows it at install (`carry`)
582
+ * under a cap of `cap` calls per month, and a new cap moves every copy already
583
+ * borrowing it. `null` stops lending it, and every copy borrowing it through
584
+ * this app asks for its own (`recall`). The cap a copy borrows under is the
585
+ * host's to write, so the host applies this as itself, once it has checked
586
+ * that the actor owns the app's space and the connection. Refused for a key
587
+ * handed to the app's code, a link where each person connects their own, and
588
+ * a connection the app itself borrows. */ export let lend = async (read, a, owners)=>{
589
+ if (a.cap != null && !(Number.isInteger(a.cap) && a.cap > 0)) {
590
+ throw new CallError('cap', 'a cap is a whole number of calls per month, at least one');
591
+ }
592
+ let used = await usingLink(read, a);
593
+ if (!used) {
594
+ throw new CallError('integration', `Choose a shared ${a.integration} connection by binding to lend it`);
595
+ }
596
+ let eid = used.link.entity.eid;
597
+ let u = comp(used.link, USES);
598
+ if (u.direct) {
599
+ throw new CallError('integration', `the app's code is handed the ${a.integration} key itself, and only a ` + 'sentinel is lent');
600
+ }
601
+ if (u.lender != null) {
602
+ throw new CallError('integration', `the app borrows its ${a.integration} connection, which is not its to lend`);
603
+ }
604
+ let lends = {
605
+ entity: {
606
+ eid
607
+ },
608
+ [USES]: {
609
+ lends: a.cap
610
+ }
611
+ };
612
+ let loans = (await read(line`.${USES}.lender=${a.app}${sub(ALL)}`)).filter((l)=>{
613
+ let loan = comp(l, USES);
614
+ return !!loan.separate == !!u.separate && (!u.separate || loan.binding == u.binding);
615
+ });
616
+ let connections = loans.length ? await read(line`.entity.eid=${loans.map((l)=>far(l, 'from'))}&.${CONNECTION}`) : [];
617
+ let targets = new Set(connections.filter((b)=>comp(b, CONNECTION).integration == a.integration).map((b)=>b.entity.eid));
618
+ let lent = loans.filter((l)=>targets.has(far(l, 'from')));
619
+ if (a.cap == null) {
620
+ return [
621
+ lends,
622
+ ...(await Promise.all([
623
+ ...targets
624
+ ].map((connection)=>recall(read, {
625
+ connection,
626
+ lender: a.app
627
+ }, owners)))).flat()
628
+ ];
629
+ }
630
+ return [
631
+ lends,
632
+ ...lent.map((l)=>({
633
+ entity: {
634
+ eid: l.entity.eid
635
+ },
636
+ [USES]: {
637
+ cap: a.cap
638
+ }
639
+ }))
640
+ ];
641
+ };
642
+ /** Stop lending a connection: to the one copy `app`, to every copy borrowing
643
+ * it through the `lender` app's lend, or with neither to every copy borrowing
644
+ * it. Each copy's link gives way to a connection needing a credential of its
645
+ * own, in the copy's own space (`owners`), linked by the same name, as
646
+ * `disconnect` leaves the apps that shared one. The connection lent stays as
647
+ * it was. */ export let recall = async (read, a, owners)=>{
648
+ let b = await held(read, a.connection);
649
+ let loans = (await links(read, 'to', a.connection)).filter((l)=>{
650
+ let u = comp(l, USES);
651
+ return u.lender != null && (a.app == null || far(l, 'to') == a.app) && (a.lender == null || u.lender == a.lender);
652
+ });
653
+ return [
654
+ ...loans.map((l)=>({
655
+ entity: {
656
+ eid: l.entity.eid
657
+ },
658
+ tombstone: {}
659
+ })),
660
+ ...await reasked(b, loans, owners)
661
+ ];
662
+ };
663
+ /** The connections some apps borrow rather than hold, from the `uses` links
664
+ * out of them, each with the link borrowing it and the integration it goes
665
+ * through: what the apps' own space reads beside the connections it keeps.
666
+ * The host reads the links however it names its apps, so they can be asked
667
+ * beside everything else it shows. A borrowed connection is read without its
668
+ * secret, which is the lender's. */ export let borrowed = async (read, out)=>{
669
+ let loans = out.filter((l)=>l[USES] && comp(l, USES).lender != null);
670
+ if (!loans.length) return [];
671
+ let lent = await read(line`.entity.eid=${loans.map((l)=>far(l, 'from'))}&.${CONNECTION}`);
672
+ return [
673
+ ...lent,
674
+ ...loans,
675
+ ...await through(read, lent)
676
+ ];
677
+ };
678
+ /** Link an app to a connection its space already owns and has connected.
679
+ * The host verifies that the actor owns both. A previous unmet ask is
680
+ * replaced, with its binding kept, and an unused ask is removed. `anyone`
681
+ * opens the link to visitors or keeps it to the app's members within the
682
+ * integration's visitor policy. When omitted, the link keeps any explicit
683
+ * choice and otherwise follows the integration's default. The app gets a
684
+ * sentinel. */ export let attach = async (read, a)=>{
685
+ let target = await held(read, a.connection);
686
+ let grant = comp(target, CONNECTION);
687
+ if (grant.owner != a.owner || grant.status != 'connected') {
688
+ throw new Error('Choose a connected connection owned by this space');
689
+ }
690
+ let integration = String(grant.integration);
691
+ let i = await known(read, integration);
692
+ if (i?.broker?.scoped) {
693
+ throw new CallError('connection', `${integration} is reserved for its space service`);
694
+ }
695
+ let uses = await appUses(read, {
696
+ app: a.app,
697
+ integration
698
+ });
699
+ let current = uses.find((m)=>m.connection.entity.eid == a.connection)?.link;
700
+ let selected = a.binding == null ? undefined : boundAs(uses, a.binding);
701
+ if (current) {
702
+ // Attached again, it is renamed when given a new name and opened or
703
+ // closed when told to, and otherwise already is what was asked.
704
+ let had = comp(current, USES);
705
+ let renamed = a.binding != null && a.binding != had.binding;
706
+ let opened = a.anyone != null && a.anyone !== had.anyone;
707
+ if (!renamed && !opened) return [];
708
+ if (renamed && !NAME.test(a.binding)) {
709
+ throw new Error('The binding must be a name code can read');
710
+ }
711
+ if (renamed && selected && selected.link.entity.eid != current.entity.eid) {
712
+ throw new Error('This app already uses another connection under that binding');
713
+ }
714
+ return [
715
+ {
716
+ entity: current.entity,
717
+ [USES]: {
718
+ ...renamed ? {
719
+ binding: a.binding
720
+ } : {},
721
+ ...opened ? {
722
+ anyone: a.anyone
723
+ } : {}
724
+ },
725
+ ...renamed ? {
726
+ $was: {
727
+ [USES]: {
728
+ binding: had.binding == null ? null : token(had.binding)
729
+ }
730
+ }
731
+ } : {}
732
+ }
733
+ ];
734
+ }
735
+ let old = selected ?? (a.binding == null ? byIntegration(uses) ?? boundAs(uses, bindingOf(integration)) : shared(uses));
736
+ let previous = old?.connection.entity.eid;
737
+ let u = comp(old?.link, USES);
738
+ if (u.direct) {
739
+ throw new Error('This app asks for the key itself; attach requires a sentinel');
740
+ }
741
+ let binding = a.binding ?? u.binding ?? bindingOf(integration);
742
+ if (typeof binding != 'string' || !NAME.test(binding)) {
743
+ throw new Error('The binding must be a name code can read');
744
+ }
745
+ if (old && comp(old.connection, CONNECTION).status == 'needed') {
746
+ if (i?.token) {
747
+ let wanted = strs(comp(old.connection, CONNECTION).scopes);
748
+ let granted = strs(grant.scopes);
749
+ wanted = wanted.length ? wanted : i.scopes ?? [];
750
+ granted = granted.length ? granted : i.scopes ?? [];
751
+ if (wanted.some((s)=>!granted.includes(s))) {
752
+ throw new Error('This connection does not grant the scopes the app asked for');
753
+ }
754
+ }
755
+ }
756
+ let alone = previous && (await links(read, 'to', previous)).length == 1;
757
+ return [
758
+ {
759
+ entity: {
760
+ eid: a.connection
761
+ },
762
+ $was: {
763
+ [CONNECTION]: {
764
+ status: token(grant.status),
765
+ owner: token(grant.owner),
766
+ integration: token(grant.integration)
767
+ }
768
+ }
769
+ },
770
+ ...previous ? [
771
+ {
772
+ entity: {
773
+ eid: edgeEid(a.app, USES, previous)
774
+ },
775
+ tombstone: {}
776
+ }
777
+ ] : [],
778
+ ...previous && alone && comp(old?.connection, CONNECTION).status == 'needed' ? [
779
+ {
780
+ entity: {
781
+ eid: previous
782
+ },
783
+ tombstone: {},
784
+ $was: {
785
+ [CONNECTION]: {
786
+ status: token('needed')
787
+ }
788
+ }
789
+ }
790
+ ] : [],
791
+ linked(a.app, a.connection, {
792
+ binding,
793
+ direct: false,
794
+ separate: u.separate == true,
795
+ anyone: a.anyone ?? (typeof u.anyone == 'boolean' ? u.anyone : undefined)
796
+ })
797
+ ];
798
+ };
799
+ /** An owner's connected chat integrations and their connection rows. A
800
+ * {@link Path} lets both reads start while the owner is still being read. */ export let chatConnections = async (read, owner)=>{
801
+ let at = typeof owner == 'string' ? line`=${owner}` : owner.path;
802
+ let [rows, integrations, eid] = await Promise.all([
803
+ read(line`.${CONNECTION}.owner${sub(at)}&.${CONNECTION}.status=connected${sub(ALL)}`),
804
+ installed(read),
805
+ typeof owner == 'string' ? owner : owner.eid
806
+ ]);
807
+ let byName = new Map(integrations.filter((i)=>i.chat).map((i)=>[
808
+ i.name,
809
+ i
810
+ ]));
811
+ return rows.flatMap((row)=>{
812
+ let connection = comp(row, CONNECTION);
813
+ let integration = byName.get(String(connection.integration));
814
+ return connection.owner == eid && integration ? [
815
+ {
816
+ row,
817
+ integration
818
+ }
819
+ ] : [];
820
+ });
821
+ };
822
+ /** A space's or a person's connections, the `uses` links from the apps that
823
+ * use them, and the integrations they go through. Each is asked by the owner,
824
+ * so all three are asked at once, and a host whose reads asked together
825
+ * travel together answers them in one trip: the integrations among the built
826
+ * ones (the line `installed` asks) and the owner's own. Only one another owner
827
+ * listed is asked after. An owner named by a {@link Path} is asked before its
828
+ * eid is known, beside whatever learns it. */ export let list = async (read, owner)=>{
829
+ let at = typeof owner == 'string' ? line`=${owner}` : owner.path;
830
+ let [reached, links, built, theirs, eid] = await Promise.all([
831
+ read(line`.${CONNECTION}.owner${sub(at)}${sub(ALL)}`),
832
+ read(line`.${EDGE}.to.${CONNECTION}.owner${sub(at)}&.${USES}${sub(ALL)}`),
833
+ read(line`.${INTEGRATION}.built`),
834
+ read(line`.${INTEGRATION}.owner${sub(at)}`),
835
+ typeof owner == 'string' ? owner : owner.eid
836
+ ]);
837
+ let owned = reached.filter((b)=>comp(b, CONNECTION).owner == eid);
838
+ if (!owned.length) return [];
839
+ let ids = new Set(owned.map((b)=>b.entity.eid));
840
+ let names = new Set(owned.map((b)=>integrationEid(String(comp(b, CONNECTION).integration))));
841
+ let kept = [
842
+ ...new Map([
843
+ ...built,
844
+ ...theirs
845
+ ].map((b)=>[
846
+ b.entity.eid,
847
+ b
848
+ ])).values()
849
+ ].filter((b)=>names.has(b.entity.eid));
850
+ return [
851
+ ...owned,
852
+ ...links.filter((l)=>ids.has(String(comp(l, EDGE).to))),
853
+ ...kept,
854
+ ...await through(read, [
855
+ ...owned,
856
+ ...kept
857
+ ])
858
+ ];
859
+ };
860
+ /** Every connected connection an app calls out through for a person, or for
861
+ * nobody in particular: those it shares with every caller, and that person's
862
+ * own where each person connects their own. Each comes with its `uses` link
863
+ * and the sentinel for its credential: what the egress finds a request's
864
+ * sentinels among. */ export let used = async (c, app, person = null)=>{
865
+ let links = await connectedUses(c.graph.read, app, person);
866
+ let all = await Promise.all(links.map(async ({ connection, link })=>({
867
+ connection,
868
+ link,
869
+ sentinels: await sentinelsOf(c, connection)
870
+ })));
871
+ return all.filter((r)=>Object.keys(r.sentinels).length);
872
+ };
873
+ let connectedUses = async (read, app, person)=>{
874
+ let out = await links(read, 'from', app);
875
+ if (!out.length) return [];
876
+ let found = await read(line`.entity.eid=${out.map((l)=>far(l, 'from'))}&.${CONNECTION}.status=${'connected'}${sub(ALL)}`);
877
+ return found.map((connection)=>({
878
+ connection,
879
+ link: out.find((l)=>far(l, 'from') == connection.entity.eid)
880
+ })).filter((r)=>!comp(r.link, USES).each || comp(r.connection, CONNECTION).owner == person);
881
+ };
882
+ // The fields a connection's credential is kept as: its integration's, or one
883
+ // key, which a sign-in's token is too.
884
+ let fieldsFor = async (read, b)=>{
885
+ let i = await known(read, String(comp(b, CONNECTION).integration));
886
+ return i && keyed(i) ? fieldsOf(i) : fieldsOf();
887
+ };
888
+ // The sentinel for each field of a connection's credential: the secret's own
889
+ // for one, and one for each field of several; none while nothing is kept.
890
+ let sentinelsOf = async (c, b)=>{
891
+ let fields = await fieldsFor(c.graph.read, b);
892
+ let out = {};
893
+ for (let f of fields){
894
+ let s = await sentinelOf(c.vault, nameOf(b), fields.length == 1 ? undefined : f.name);
895
+ if (s) out[f.name] = s;
896
+ }
897
+ return out;
898
+ };
899
+ /** What an app's code is handed for each connected connection it uses, for a
900
+ * person or for nobody in particular, by the name it reads it by: the sentinel
901
+ * for its credential, or the credential itself where the link is direct. */ export let envOf = (c, app, person = null)=>bound(c, app, person, (u)=>!!u.direct && u.lender == null);
902
+ /** What the host's own code reads for each connected connection an app of the
903
+ * host's uses, by the name it reads it by: the credential itself, whatever the
904
+ * link says, since that code is the host's and the key goes nowhere else.
905
+ * yaks.app's own provider keys are its `platform` app's. When `unread` is
906
+ * supplied, it hears a failed credential lookup and the other bindings still
907
+ * answer. */ export let keysOf = async (c, app, unread)=>{
908
+ let uses = (await connectedUses(c.graph.read, app, null)).flatMap((r)=>{
909
+ let binding = comp(r.link, USES).binding;
910
+ return typeof binding == 'string' ? [
911
+ {
912
+ ...r,
913
+ binding
914
+ }
915
+ ] : [];
916
+ });
917
+ let integrations = await knownAll(c.graph.read, [
918
+ ...new Set(uses.map(({ connection })=>integrated(connection)))
919
+ ]);
920
+ let linked = uses.map((use)=>({
921
+ ...use,
922
+ integration: knownIn(integrations, integrated(use.connection))
923
+ }));
924
+ let raw = await reveals(c.vault, linked.flatMap(({ connection, integration })=>integration && keyed(integration) ? [
925
+ nameOf(connection)
926
+ ] : []));
927
+ let entries = await Promise.all(linked.map(({ connection, binding, integration })=>keyEntries(c, connection, binding, integration, raw.get(nameOf(connection))).catch((error)=>{
928
+ if (!unread) throw error;
929
+ unread(binding, error);
930
+ return [];
931
+ })));
932
+ return Object.fromEntries(entries.flat());
933
+ };
934
+ let keyEntries = async (c, connection, binding, i, raw)=>{
935
+ let name = nameOf(connection);
936
+ if (!i || !keyed(i)) {
937
+ // A sign-in can refresh its grant. Only connections still holding one
938
+ // in the vault can be used, as at the egress.
939
+ if (!await sentinelOf(c.vault, name)) return [];
940
+ let value = await granted(c, connection);
941
+ return value ? [
942
+ [
943
+ binding,
944
+ value
945
+ ]
946
+ ] : [];
947
+ }
948
+ if (raw?.status == 'rejected') throw raw.reason;
949
+ let fields = fieldsOf(i);
950
+ let named = namesOf(binding, fields.map((f)=>f.name));
951
+ let values = await keyValues(c, connection, fields, raw?.value);
952
+ return Object.entries(named).flatMap(([field, name])=>values?.[field] ? [
953
+ [
954
+ name,
955
+ values[field]
956
+ ]
957
+ ] : []);
958
+ };
959
+ // Each connected connection `app` uses, by the name it reads it by: the
960
+ // credential where `direct` says so, else its sentinel.
961
+ let bound = async (c, app, person, direct)=>{
962
+ let out = {};
963
+ for (let r of (await used(c, app, person))){
964
+ let u = comp(r.link, USES);
965
+ if (typeof u.binding != 'string') continue;
966
+ let names = namesOf(u.binding, Object.keys(r.sentinels));
967
+ for (let [f, name] of Object.entries(names)){
968
+ let value = direct(u) ? await credential(c, r.connection.entity.eid, f) : r.sentinels[f];
969
+ if (value) out[name] = value;
970
+ }
971
+ }
972
+ return out;
973
+ };
974
+ /** The connection an app calls out through for an integration, for a person
975
+ * or for nobody in particular, optionally by binding. It includes the
976
+ * credential's sentinel. Whether the caller may use it is the egress's
977
+ * question. */ export let resolve = async (c, app, integration, person = null, binding)=>{
978
+ let uses = (await used(c, app, person)).filter((r)=>comp(r.connection, CONNECTION).integration == integration);
979
+ return binding == null ? byIntegration(uses) : boundAs(uses, binding);
980
+ };
981
+ /** Choose an owner's account. Without a name, the person's own address wins,
982
+ * otherwise the oldest connection. No remembered selection can let a newer
983
+ * throwaway change what unattended commands use. */ export let pick = async (read, owner, integration, as)=>{
984
+ let found = (await read(line`.${CONNECTION}.owner=${owner}${sub(ALL)}&.order=created.at`)).filter((b)=>comp(b, CONNECTION).integration == integration);
985
+ let address = (b)=>String(comp(b, CONNECTION).account ?? '').toLowerCase();
986
+ if (as) {
987
+ let name = as.toLowerCase();
988
+ let exact = found.filter((b)=>address(b) == name);
989
+ let matches = exact.length ? exact : name.includes('@') ? [] : found.filter((b)=>address(b).split('@')[0] == name);
990
+ let accounts = [
991
+ ...new Set(found.map((b)=>comp(b, CONNECTION).account))
992
+ ].filter((a)=>typeof a == 'string' && a != '').sort();
993
+ let available = `; available accounts: ${accounts.join(', ') || '(none)'}`;
994
+ if (matches.length > 1) {
995
+ throw new AccountError(`${as} names several ${integration} accounts; use the whole address${available}`);
996
+ }
997
+ if (!matches.length) {
998
+ throw new AccountError(`no ${integration} account is named ${as}${available}`);
999
+ }
1000
+ return matches[0];
1001
+ }
1002
+ let [person] = await read(line`.entity.eid=${owner}&*`);
1003
+ let own = String(comp(person, 'email').address ?? '').toLowerCase();
1004
+ return found.find((b)=>own && address(b) == own) ?? found[0];
1005
+ };
1006
+ /** Every connection to one account of an integration, by its whole address,
1007
+ * whoever owns it: what goes when the account does. */ export let toAccount = async (read, integration, address)=>(await read(line`.${CONNECTION}.integration=${integration}`)).filter((b)=>String(comp(b, CONNECTION).account ?? '').toLowerCase() == address.toLowerCase());
1008
+ /** The address the provider returned. An id_token is used only to name an
1009
+ * account after the authenticated code exchange, never as authorization. */ export let accountOf = async (integration, tokens, fetcher = fetch)=>(await signedIn(integration, tokens, fetcher)).account;
1010
+ // The account the provider returned, and what people call it where the
1011
+ // account is an id (`account_title`).
1012
+ let signedIn = async (integration, tokens, fetcher)=>{
1013
+ if (integration.account && tokens.account) {
1014
+ return {
1015
+ account: tokens.account,
1016
+ title: tokens.account_title
1017
+ };
1018
+ }
1019
+ let body = {};
1020
+ // An account the integration names is a path of its userinfo answer, so
1021
+ // an id_token is read only where it names none.
1022
+ let userinfo = tokens.access_token && (integration.account || !tokens.id_token) ? integration.userinfo : undefined;
1023
+ if (userinfo) {
1024
+ let res = await fetcher(userinfo, {
1025
+ headers: {
1026
+ authorization: `Bearer ${tokens.access_token}`,
1027
+ accept: 'application/json'
1028
+ },
1029
+ redirect: 'manual',
1030
+ signal: AbortSignal.timeout(30_000)
1031
+ });
1032
+ if (!res.ok) {
1033
+ throw new Error(`the userinfo endpoint refused: ${res.status}`);
1034
+ }
1035
+ body = await res.json();
1036
+ } else if (tokens.id_token) {
1037
+ body = claims(tokens.id_token);
1038
+ if (!Object.keys(body).length) {
1039
+ throw new Error('the provider returned an invalid id_token');
1040
+ }
1041
+ }
1042
+ let at = (path)=>{
1043
+ let v = path?.split('.').reduce((at, k)=>at && typeof at == 'object' ? at[k] : undefined, body);
1044
+ return typeof v == 'string' || typeof v == 'number' ? String(v) : undefined;
1045
+ };
1046
+ if (integration.account) {
1047
+ return {
1048
+ account: at(integration.account),
1049
+ title: at(integration.account_title)
1050
+ };
1051
+ }
1052
+ return {
1053
+ account: typeof body.email == 'string' && body.email.includes('@') ? body.email.toLowerCase() : undefined
1054
+ };
1055
+ };
1056
+ // The OAuth client for a connection: its integration's endpoints, the scopes
1057
+ // it was asked for, and its tokens kept as its own secret.
1058
+ let signIn = async (c, b, staged, again = false)=>{
1059
+ let name = String(comp(b, CONNECTION).integration);
1060
+ let i = await known(c.graph.read, name);
1061
+ return oauth(c, name, i, b, staged, again);
1062
+ };
1063
+ let oauth = async (c, name, i, b, staged, again = false)=>{
1064
+ if (!i?.authorize || !i.token) {
1065
+ throw new Error(`${name} is connected with a pasted key, not by signing in`);
1066
+ }
1067
+ let registered = await clientOf(c.vault, c.graph.read, i);
1068
+ if (!connectable(i, registered)) {
1069
+ throw new Error(`no OAuth client is registered for ${name}`);
1070
+ }
1071
+ let scopes = strs(comp(b, CONNECTION).scopes);
1072
+ return client({
1073
+ authorize: i.authorize,
1074
+ token: i.token,
1075
+ scopes: scopes.length ? [
1076
+ ...new Set([
1077
+ ...scopes,
1078
+ ...(i.scopes ?? []).filter((s)=>again || IDENTITY.has(s))
1079
+ ])
1080
+ ] : i.scopes,
1081
+ params: i.params,
1082
+ client: registered ?? (i.client_id ? {
1083
+ id: i.client_id
1084
+ } : undefined),
1085
+ auth: i.auth,
1086
+ scopeSeparator: i.scope_separator,
1087
+ pkce: i.pkce,
1088
+ refreshEncoding: i.refresh_encoding,
1089
+ answers: i.answers,
1090
+ resource: i.resource,
1091
+ issuer: i.issuer,
1092
+ account: i.account,
1093
+ account_title: i.account_title
1094
+ }, {
1095
+ store: staged || !b ? {
1096
+ read: ()=>Promise.resolve(staged ?? {}),
1097
+ update: (_, fn)=>fn(staged ?? {})
1098
+ } : keeping(c, b),
1099
+ key: b ? nameOf(b) : '',
1100
+ redirect: c.redirect ?? '',
1101
+ fetch: c.fetch,
1102
+ now: c.now
1103
+ });
1104
+ };
1105
+ // The scopes that only say who signed in, which a provider may name its own
1106
+ // way in what it grants.
1107
+ let IDENTITY = new Set([
1108
+ 'openid',
1109
+ 'email',
1110
+ 'profile'
1111
+ ]);
1112
+ /** The scopes `i` now asks for that a connection holding `scopes` lacks, so
1113
+ * signing in again would give it more; none when what it holds is unknown. */ export let lacking = (i, scopes)=>{
1114
+ let held = new Set(scopes);
1115
+ return scopes.length ? (i.scopes ?? []).filter((s)=>!IDENTITY.has(s) && !held.has(s)) : [];
1116
+ };
1117
+ // Restricted space services use a broker configuration dedicated to their
1118
+ // owner, so each can use its Workspace's internal OAuth app and scopes.
1119
+ let brokerConfig = (broker, owner)=>broker.scoped ? `${broker.integration}-${String(owner)}` : broker.integration;
1120
+ /** The link to send a person to, to connect by signing in, and the attempt to
1121
+ * hold until they return. `again` signs a connection in again in place,
1122
+ * asking for every scope its integration now asks for: the same row, the
1123
+ * apps using it and its account, with a new grant. A brokered one is marked
1124
+ * `reconnecting` until `settle` finds the new grant at the broker. `began` is
1125
+ * the verified address of the person beginning it, which a brokered sign-in
1126
+ * must come back from to attach at once (`settle`). */ export let begin = async (c, connection, again = false, began)=>{
1127
+ let b = await signing(c.graph.read, connection);
1128
+ if (!again && typeof connection == 'string') await admitting(c, b);
1129
+ let i = await known(c.graph.read, String(comp(b, CONNECTION).integration));
1130
+ let alternative = mcpAlternative(i?.resource);
1131
+ if (alternative) throw new CallError('rejected', useIntegration(alternative));
1132
+ if (i?.broker) {
1133
+ if (typeof connection != 'string') {
1134
+ throw new Error('A broker needs a connection');
1135
+ }
1136
+ // A broker's sign-in returns to the broker, not to us: `settle` finds
1137
+ // it there afterwards by the connection's eid.
1138
+ let broker = await brokering(c, i.broker.name);
1139
+ if (i.broker.managed || !i.built && !i.owner && Array.isArray(i.categories)) {
1140
+ await broker.enable(i.broker.integration, i.connects ?? 'signin');
1141
+ }
1142
+ let url = await broker.begin(brokerConfig(i.broker, comp(b, CONNECTION).owner), connection, began?.toLowerCase(), i.broker.scoped ? i.scopes : i.broker.managed ? [
1143
+ ...new Set([
1144
+ ...i.scopes ?? [],
1145
+ ...strs(comp(b, CONNECTION).scopes)
1146
+ ])
1147
+ ] : undefined);
1148
+ if (again) {
1149
+ await c.graph.apply([
1150
+ {
1151
+ entity: {
1152
+ eid: connection
1153
+ },
1154
+ [RECONNECTING]: {}
1155
+ }
1156
+ ]);
1157
+ }
1158
+ return {
1159
+ url
1160
+ };
1161
+ }
1162
+ if (!c.redirect) throw new Error('signing in needs a redirect');
1163
+ return (await signIn(c, b, undefined, again)).begin();
1164
+ };
1165
+ // The last two labels of a host: canva.com for mcp.canva.com.
1166
+ let domainOf = (url)=>{
1167
+ try {
1168
+ return new URL(url ?? '').host.split('.').slice(-2).join('.');
1169
+ } catch {
1170
+ return '';
1171
+ }
1172
+ };
1173
+ /** An MCP server's sign-in page `url`, which `begin` gave for `connection`,
1174
+ * opened once before a person's browser is sent there. A server that takes
1175
+ * only the OAuth clients it lists can fail its page for any other:
1176
+ * mcp.canva.com answers 500 to a client from Canva's Developer Portal. That
1177
+ * refuses here in words, naming a built integration for the same service that
1178
+ * signs in another way, instead of sending them to the server's error page. A
1179
+ * page that can't be reached from here is left for the browser to try. */ export let opens = async (c, connection, url)=>{
1180
+ let b = await signing(c.graph.read, connection);
1181
+ let i = await known(c.graph.read, integrated(b));
1182
+ if (!i?.resource) return;
1183
+ let res = await (c.fetch ?? fetch)(url, {
1184
+ redirect: 'manual',
1185
+ signal: AbortSignal.timeout(10_000)
1186
+ }).catch(()=>undefined);
1187
+ await res?.body?.cancel();
1188
+ if (!res || res.status < 500) return;
1189
+ let at = domainOf(i.resource);
1190
+ let other = (await installed(c.graph.read)).find((o)=>o.name != i.name && !o.resource && domainOf(o.site) == at);
1191
+ throw new CallError('rejected', `Sign-in to ${i.title ?? i.name} could not start.` + (other ? ` Connect ${other.title ?? other.name} from the list of services instead.` : ' Try connecting again later.'));
1192
+ };
1193
+ /** What an integration signs in with, where it is kept: its broker, when it
1194
+ * names one, else the OAuth client it names. `connectable` says whether
1195
+ * either is enough. */ export let signsInWith = (vault, read, i)=>i.broker ? brokerOf(vault, i.broker.name) : clientOf(vault, read, i);
1196
+ // The broker named `name`, or a failure saying its key is not kept.
1197
+ let brokering = async (c, name)=>{
1198
+ let broker = await brokerOf(c.vault, name, c.fetch);
1199
+ if (!broker) throw new Error(`no key is kept for the ${name} broker`);
1200
+ return broker;
1201
+ };
1202
+ /** Connect a connection whose sign-in finished at its integration's broker,
1203
+ * once it has; nothing while it has not, or for one that is not needed or
1204
+ * not brokered. A broker's sign-in never returns to us, so whoever reads a
1205
+ * needed connection settles it: nothing waits on the broker telling us.
1206
+ *
1207
+ * A broker's link opens in any browser, so the account that approved there
1208
+ * may not be the beginner's. A grant attaches at once only when the account
1209
+ * it names is the address `begin` was given. Any other is held, attaching
1210
+ * nothing, and the connection is marked `approving` with the account that
1211
+ * approved, for that account to confirm (`approve`) or decline (`decline`).
1212
+ * The answer is the bundles written: the mark, when one is new, is the
1213
+ * caller's cue to ask the account. A hold unanswered for a day (`HOLD`) is
1214
+ * forgotten at the broker: by the run its write owes (`lapse`,
1215
+ * `connection_hold_lapse`), or by a read here or a press of `approve`,
1216
+ * whichever comes first. */ export let settle = async (c, connection)=>{
1217
+ let b = await held(c.graph.read, connection);
1218
+ let again = b[RECONNECTING];
1219
+ let waiting = b[APPROVING];
1220
+ let connected = comp(b, CONNECTION).status == 'connected' && !again;
1221
+ if (connected && !waiting) return [];
1222
+ let i = await known(c.graph.read, String(comp(b, CONNECTION).integration));
1223
+ if (!i?.broker) return [];
1224
+ let broker = await brokerOf(c.vault, i.broker.name, c.fetch);
1225
+ if (!broker) return [];
1226
+ let integration = brokerConfig(i.broker, comp(b, CONNECTION).owner);
1227
+ let now = (c.now ?? Date.now)();
1228
+ if (waiting && lapsedHold(waiting, now)) return forgetting(c, b, i);
1229
+ if (connected) return [];
1230
+ let found = await broker.found(integration, connection);
1231
+ let kept = again ? await records(c.graph, c.vault, '').read(nameOf(b)) : undefined;
1232
+ // A hold naming no account was never asked of anyone, so its grant is
1233
+ // read again rather than waited on.
1234
+ let asked = waiting?.account ? waiting.id : undefined;
1235
+ if (!found || found.id == kept?.id || found.id == asked) {
1236
+ // Signing in again that found nothing new within the hour is let go.
1237
+ let stale = again && now - Date.parse(String(again.at)) > HOUR;
1238
+ return stale ? c.graph.apply([
1239
+ {
1240
+ entity: {
1241
+ eid: connection
1242
+ },
1243
+ [RECONNECTING]: null
1244
+ }
1245
+ ]) : [];
1246
+ }
1247
+ let grant = await broker.grant(integration, found.id);
1248
+ if (i.broker.scoped) {
1249
+ let required = new Set(i.scopes);
1250
+ let granted = new Set(grant.scopes);
1251
+ if (!required.size || granted.size != required.size || [
1252
+ ...required
1253
+ ].some((scope)=>!granted.has(scope))) {
1254
+ await broker.forget(integration, found.id);
1255
+ throw new CallError('scope', `${i.title} requires exactly its listed scopes`);
1256
+ }
1257
+ let account = await accountOf(i, {
1258
+ access_token: grant.access_token
1259
+ }, c.fetch ?? fetch);
1260
+ if (!account || account.toLowerCase() != found.began) {
1261
+ await broker.forget(integration, found.id);
1262
+ return [];
1263
+ }
1264
+ return adopt(c, b, found.id, {
1265
+ ...grant,
1266
+ account: account.toLowerCase()
1267
+ });
1268
+ }
1269
+ let account = await grantAccount(c, i, grant);
1270
+ if (!account || account != found.began) {
1271
+ if (found.id == waiting?.id && !account) return [];
1272
+ if (waiting && found.id != waiting.id) {
1273
+ await broker.forget(integration, String(waiting.id)).catch(c.report ?? (()=>{}));
1274
+ }
1275
+ return c.graph.apply([
1276
+ {
1277
+ entity: {
1278
+ eid: connection
1279
+ },
1280
+ [APPROVING]: {
1281
+ id: found.id,
1282
+ account: account ?? '',
1283
+ at: new Date(now).toISOString(),
1284
+ ...found.began ? {
1285
+ began: found.began
1286
+ } : {}
1287
+ }
1288
+ }
1289
+ ]);
1290
+ }
1291
+ return adopt(c, b, found.id, grant);
1292
+ };
1293
+ /** Connect the grant held for its approver (`settle`), once the account that
1294
+ * approved confirms it: `id` is the broker's id the hold names. Nothing for a
1295
+ * hold that is gone or names another grant. A hold past its day connects
1296
+ * nothing, and is forgotten: the answer is empty then too. */ export let approve = async (c, connection, id)=>{
1297
+ let b = await held(c.graph.read, connection);
1298
+ let waiting = comp(b, APPROVING);
1299
+ if (waiting.id != id) return [];
1300
+ if (!lapsedHold(waiting, (c.now ?? Date.now)())) return adopt(c, b, id);
1301
+ await forgetting(c, b);
1302
+ return [];
1303
+ };
1304
+ /** Forget the grant held for its approver at the broker, when the account
1305
+ * that approved declines it. Nothing for a hold that is gone or names
1306
+ * another grant. */ export let decline = async (c, connection, id)=>{
1307
+ let b = await held(c.graph.read, connection);
1308
+ return comp(b, APPROVING).id == id ? forgetting(c, b) : [];
1309
+ };
1310
+ /** Forget the grant held for its approver at the broker, and its mark, once
1311
+ * the hold is a day old (`HOLD`): the run a hold's write owes
1312
+ * (`connection_hold_lapse`, ./effects.ts). The answer is how long the hold
1313
+ * has left, for one written since, or 0 once nothing is held: for a
1314
+ * connection gone, or a hold already answered or forgotten. */ export let lapse = async (c, connection)=>{
1315
+ let [b] = await c.graph.read(line`.entity.eid=${connection}&.${CONNECTION}&.${APPROVING}`);
1316
+ let waiting = b && comp(b, APPROVING);
1317
+ if (!waiting) return 0;
1318
+ let rest = left(waiting, (c.now ?? Date.now)());
1319
+ if (rest <= 0) await forgetting(c, b);
1320
+ return Math.max(rest, 0);
1321
+ };
1322
+ /** Forget at the broker what a connection that died held there: the run its
1323
+ * death owes (`connection_gone`, ./effects.ts), whether a disconnect or the
1324
+ * space or person that owned it took it. `was` is its `connection` as it
1325
+ * died. Every grant the broker holds for it goes, the one held for an
1326
+ * approver among them, but the grant it kept while it can still be restored:
1327
+ * while its owner stands and the vault retains its credential. Nothing for a
1328
+ * connection brought back since, and nothing is asked of a broker whose key
1329
+ * is not kept. */ export let ended = async (c, connection, was)=>{
1330
+ let { read } = c.graph;
1331
+ if ((await read(line`.entity.eid=${connection}&.${CONNECTION}`)).length) {
1332
+ return;
1333
+ }
1334
+ let at = (await known(read, String(was.integration)))?.broker;
1335
+ let kept = was.broker ? await retainedGrants(c.vault, connection) : [];
1336
+ let owned = (await read(line`.entity.eid=${String(was.owner)}`)).length > 0;
1337
+ // Without the broker's key, nothing can be asked of it: a grant the vault
1338
+ // kept says one is there, and asks with the key it lacks, which is reported.
1339
+ let broker = at && await brokerOf(c.vault, at.name, c.fetch);
1340
+ let integration = at && brokerConfig(at, was.owner);
1341
+ let found = at && broker && integration ? (await broker.grants(integration, connection)).map(({ id })=>({
1342
+ broker: at.name,
1343
+ integration,
1344
+ id
1345
+ })) : [];
1346
+ let seen = new Set(owned ? kept.map(grantKey) : []);
1347
+ for (let g of [
1348
+ ...found,
1349
+ ...kept
1350
+ ]){
1351
+ let key = grantKey(g);
1352
+ if (seen.has(key)) continue;
1353
+ seen.add(key);
1354
+ await forgetGrant(c, g);
1355
+ }
1356
+ };
1357
+ /** The locator in a vaulted broker credential. Only these fields can leave
1358
+ * the vault as part of cleanup work. */ export let grantOf = (value)=>{
1359
+ if (!value?.trimStart().startsWith('{')) return;
1360
+ let kept;
1361
+ try {
1362
+ kept = JSON.parse(value);
1363
+ } catch {
1364
+ return;
1365
+ }
1366
+ let { broker, integration, id } = kept ?? {};
1367
+ if (typeof broker == 'string' && broker && typeof integration == 'string' && integration && typeof id == 'string' && id) return {
1368
+ broker,
1369
+ integration,
1370
+ id
1371
+ };
1372
+ };
1373
+ let grantKey = ({ broker, integration, id })=>JSON.stringify([
1374
+ broker,
1375
+ integration,
1376
+ id
1377
+ ]);
1378
+ let forgetGrant = async (c, g)=>(await brokering(c, g.broker)).forget(g.integration, g.id);
1379
+ let retainedGrants = async (vault, eid)=>{
1380
+ let grants = [];
1381
+ for (let t of (await vault.trash())){
1382
+ if (t.eid != eid) continue;
1383
+ let grant = grantOf((await vault.past(t.id))?.value);
1384
+ if (grant) grants.push(grant);
1385
+ }
1386
+ return grants;
1387
+ };
1388
+ /** Forget a purged version's grant after checking the current restore paths. */ export let forgetPurged = async (c, eid, grant)=>{
1389
+ if ((await c.graph.read(line`.entity.eid=${eid}&.${CONNECTION}`)).length) {
1390
+ return;
1391
+ }
1392
+ let key = grantKey(grant);
1393
+ let active = grantOf((await c.vault.read(eid))?.value);
1394
+ if (active && grantKey(active) == key) return;
1395
+ if ((await retainedGrants(c.vault, eid)).some((g)=>grantKey(g) == key)) {
1396
+ return;
1397
+ }
1398
+ await forgetGrant(c, grant);
1399
+ };
1400
+ // How long the hold `waiting` has left at `now`, in ms.
1401
+ let left = (waiting, now)=>Date.parse(String(waiting.at)) + HOLD - now;
1402
+ /** Whether the hold `waiting` (a connection's `approving` mark) is a day old
1403
+ * at `now`: one `approve` connects nothing by. */ export let lapsedHold = (waiting, now)=>left(waiting, now) <= 0;
1404
+ // Forget the grant `b` holds for its approver at its integration's broker
1405
+ // (`i`, read when not given), then its mark. A broker that does not answer
1406
+ // throws, and the mark stays for the next try.
1407
+ let forgetting = async (c, b, i)=>{
1408
+ i ??= await known(c.graph.read, String(comp(b, CONNECTION).integration));
1409
+ let id = String(comp(b, APPROVING).id);
1410
+ if (i?.broker) {
1411
+ let integration = brokerConfig(i.broker, comp(b, CONNECTION).owner);
1412
+ await (await brokering(c, i.broker.name)).forget(integration, id);
1413
+ }
1414
+ return c.graph.apply([
1415
+ {
1416
+ entity: {
1417
+ eid: b.entity.eid
1418
+ },
1419
+ [APPROVING]: null,
1420
+ $was: {
1421
+ [APPROVING]: {
1422
+ id: token(id)
1423
+ }
1424
+ }
1425
+ }
1426
+ ]);
1427
+ };
1428
+ // Connect the broker's grant `id` into `b`. Signing in again leaves the new
1429
+ // grant at the broker beside the one kept, which goes once the connection
1430
+ // holds the new one.
1431
+ let adopt = async (c, b, id, grant)=>{
1432
+ let keeps = records(c.graph, c.vault, '');
1433
+ let kept = b[RECONNECTING] ? await keeps.read(nameOf(b)) : undefined;
1434
+ let out = await connect(c, b.entity.eid, {
1435
+ brokered: id,
1436
+ grant
1437
+ });
1438
+ let now = kept && await keeps.read(nameOf(b));
1439
+ if (now?.id == id && kept?.id && kept.id != id && kept.broker && kept.integration) {
1440
+ await (await brokering(c, kept.broker)).forget(kept.integration, kept.id).catch(c.report ?? (()=>{}));
1441
+ }
1442
+ return out;
1443
+ };
1444
+ // The account a broker's grant names, lower-cased: the broker's word, else
1445
+ // what the service says of the token. A service that refuses to say fails.
1446
+ let grantAccount = async (c, i, g)=>(g.account ?? await accountOf(i, g, c.fetch ?? fetch))?.toLowerCase();
1447
+ let HOUR = 3_600_000;
1448
+ /** How long a grant held for the account that approved it waits for that
1449
+ * account's answer before it is forgotten at the broker: one day, in ms. */ export let HOLD = 86_400_000;
1450
+ // A needed connection given its key or grant is one more its owner holds,
1451
+ // which the host may refuse (`admit`).
1452
+ let admitting = async (c, b)=>{
1453
+ let { owner, status } = comp(b, CONNECTION);
1454
+ if (status == 'needed') await c.admit?.(String(owner));
1455
+ };
1456
+ /** Exchange an installation begun at a provider. The grant is still unowned. */ export let redeemInstallation = async (c, i, code)=>{
1457
+ let grant = await (await oauth(c, i.name, i)).redeem(code);
1458
+ if (!grant.account) {
1459
+ throw new CallError('connection', 'Install the app in a workspace.');
1460
+ }
1461
+ return grant;
1462
+ };
1463
+ /** Bind a redeemed installation to the workspace's chosen space. */ export let attachInstallation = async (c, owner, integration, grant)=>{
1464
+ let [b] = await c.graph.apply(await need(c.graph.read, {
1465
+ owner,
1466
+ integration
1467
+ }));
1468
+ return keepGrant(c, b, grant, grant.account, grantWords(grant, grant.account_title));
1469
+ };
1470
+ let grantWords = (tokens, title)=>({
1471
+ ...tokens.scope ? {
1472
+ scopes: tokens.scope.split(/\s+/)
1473
+ } : {},
1474
+ ...title ? {
1475
+ title
1476
+ } : {}
1477
+ });
1478
+ /** Keep a connection's credential — a pasted key, or the grant a finished
1479
+ * sign-in returns — and mark it connected. */ export let connect = async (c, connection, given, account)=>{
1480
+ let b = await signing(c.graph.read, connection);
1481
+ let now = {
1482
+ status: 'connected',
1483
+ ...account ? {
1484
+ account
1485
+ } : {}
1486
+ };
1487
+ if ('key' in given || 'fields' in given) {
1488
+ if (typeof connection != 'string') {
1489
+ throw new Error('A key needs a connection');
1490
+ }
1491
+ let name = String(comp(b, CONNECTION).integration);
1492
+ let i = await known(c.graph.read, name);
1493
+ if (!i || !keyed(i) && name != 'yaks.app') {
1494
+ throw new Error(`${name} is connected by signing in, not with a key`);
1495
+ }
1496
+ let [reply] = await Promise.all([
1497
+ answered(c.graph.read, b, connection),
1498
+ admitting(c, b)
1499
+ ]);
1500
+ let held = stillHeld(b);
1501
+ let expect = 'key' in given ? given.expect : undefined;
1502
+ if (expect) held.$was[CONNECTION] = {
1503
+ status: token(expect)
1504
+ };
1505
+ return c.graph.apply([
1506
+ {
1507
+ ...pasted(b, name, fieldsOf(i), given),
1508
+ ...held,
1509
+ [CONNECTION]: now
1510
+ },
1511
+ ...i.owner && !i.credentialed ? [
1512
+ {
1513
+ entity: {
1514
+ eid: integrationEid(name)
1515
+ },
1516
+ [INTEGRATION]: {
1517
+ credentialed: true
1518
+ },
1519
+ $was: {
1520
+ [INTEGRATION]: {
1521
+ hosts: token(i.hosts)
1522
+ }
1523
+ }
1524
+ }
1525
+ ] : [],
1526
+ ...reply
1527
+ ]);
1528
+ }
1529
+ let i = await known(c.graph.read, String(comp(b, CONNECTION).integration));
1530
+ let tokens = {};
1531
+ let made = {};
1532
+ let linked = [];
1533
+ if ('brokered' in given) {
1534
+ if (!i?.broker) throw new Error(`${i?.name} is not brokered`);
1535
+ let { name } = i.broker;
1536
+ let integration = brokerConfig(i.broker, comp(b, CONNECTION).owner);
1537
+ let g = given.grant ?? await (await brokering(c, name)).grant(integration, given.brokered);
1538
+ Object.assign(tokens, keptGrant(name, integration, given.brokered, g));
1539
+ account = await grantAccount(c, i, g).catch((e)=>(c.report?.(e), undefined)) ?? account;
1540
+ made = {
1541
+ broker: name,
1542
+ ...g.scopes ? {
1543
+ scopes: g.scopes
1544
+ } : {}
1545
+ };
1546
+ } else {
1547
+ await (await signIn(c, b, tokens)).complete(given.attempt, given.callback);
1548
+ if (given.session) {
1549
+ Object.assign(tokens, {
1550
+ website_session: given.session
1551
+ });
1552
+ }
1553
+ let who = i ? await signedIn(i, tokens, c.fetch ?? fetch) : {};
1554
+ if (i?.chat_grant && !who.account) {
1555
+ throw new CallError('connection', 'Install the app in a workspace.');
1556
+ }
1557
+ if (typeof connection != 'string' && i?.account && !who.account) {
1558
+ throw new CallError('connection', 'The service did not identify the account.');
1559
+ }
1560
+ account = who.account ?? account;
1561
+ made = grantWords(tokens, who.title);
1562
+ if (i?.links && given.person) {
1563
+ linked = await linking(c, i.links, given.person, tokens).catch((e)=>(c.report?.(e), []));
1564
+ }
1565
+ }
1566
+ let saved = typeof connection == 'string';
1567
+ let write = ()=>keepGrant(c, b, tokens, account, made, linked, saved);
1568
+ try {
1569
+ return await write();
1570
+ } catch (e) {
1571
+ if (saved || !(e instanceof Stale) || e.comp != 'tombstone' && !(e.comp == CONNECTION && e.prop == 'status')) throw e;
1572
+ return await write();
1573
+ }
1574
+ };
1575
+ let forAccount = async (read, grant, account, except)=>{
1576
+ let rows = (await read(line`.${CONNECTION}.owner=${String(grant.owner)}&.${CONNECTION}.integration=${String(grant.integration)}${sub(ALL)}`)).filter((b)=>b.entity.eid != except && String(comp(b, CONNECTION).account ?? '').toLowerCase() == account.toLowerCase());
1577
+ if (!rows.length) return;
1578
+ let reserved = new Set((await links(read, 'to', rows.map((b)=>b.entity.eid))).filter((l)=>comp(l, USES).separate).map((l)=>far(l, 'from')));
1579
+ let shared = rows.filter((b)=>!reserved.has(b.entity.eid));
1580
+ return shared.find((b)=>comp(b, CONNECTION).status == 'connected') ?? shared[0];
1581
+ };
1582
+ let keepGrant = async (c, b, tokens, account, made, linked = [], saved = true)=>{
1583
+ let connection = b.entity.eid;
1584
+ let grant = comp(b, CONNECTION);
1585
+ let binding = saved ? await separately(c.graph.read, connection) : undefined;
1586
+ let kept = account && binding == null ? await forAccount(c.graph.read, grant, account, connection) : undefined;
1587
+ let ask = !saved && !kept ? await firstAsk(c.graph.read, String(grant.owner), String(grant.integration), strs(grant.scopes)) : undefined;
1588
+ let pending = comp(ask, CONNECTION).status == 'needed' ? ask : undefined;
1589
+ // A different account never overwrites what the person already holds.
1590
+ let different = grant.status == 'connected' && grant.account && account && String(grant.account).toLowerCase() != account.toLowerCase();
1591
+ let target = kept ?? pending ?? (different || !saved ? fresh(String(grant.owner), String(grant.integration), strs(grant.scopes), binding == null ? account : undefined) : b);
1592
+ if (!kept) await admitting(c, target);
1593
+ let transient = saved && kept && grant.status != 'connected';
1594
+ let out = transient ? await movedUses(c.graph.read, [
1595
+ connection
1596
+ ], target.entity.eid) : [];
1597
+ return c.graph.apply([
1598
+ ...saved ? [
1599
+ stillHeld(b)
1600
+ ] : [],
1601
+ ...kept ? [
1602
+ stillHeld(kept)
1603
+ ] : [],
1604
+ ...pending ? [
1605
+ stillNeeded(pending)
1606
+ ] : [],
1607
+ {
1608
+ entity: {
1609
+ eid: target.entity.eid
1610
+ },
1611
+ ...target.$was ? {
1612
+ $was: target.$was
1613
+ } : {},
1614
+ [SECRET]: {
1615
+ name: nameOf(target),
1616
+ value: JSON.stringify(tokens)
1617
+ },
1618
+ [CONNECTION]: {
1619
+ ...comp(target, CONNECTION),
1620
+ ...made,
1621
+ status: 'connected',
1622
+ ...account ? {
1623
+ account
1624
+ } : {}
1625
+ },
1626
+ ...target[RECONNECTING] ? {
1627
+ [RECONNECTING]: null
1628
+ } : {},
1629
+ ...target[APPROVING] ? {
1630
+ [APPROVING]: null
1631
+ } : {}
1632
+ },
1633
+ ...out,
1634
+ ...transient ? [
1635
+ {
1636
+ entity: {
1637
+ eid: connection
1638
+ },
1639
+ tombstone: {}
1640
+ }
1641
+ ] : b[RECONNECTING] && target.entity.eid != connection ? [
1642
+ {
1643
+ entity: {
1644
+ eid: connection
1645
+ },
1646
+ [RECONNECTING]: null
1647
+ }
1648
+ ] : [],
1649
+ ...await answered(c.graph.read, b, target.entity.eid),
1650
+ ...linked
1651
+ ]);
1652
+ };
1653
+ // The person's own connection through `name` that a sign-in through another
1654
+ // integration also names (`links`): Discord's bot added with `identify`
1655
+ // granted reads who added it at `/users/@me`, with the same token. It keeps
1656
+ // that token without its refresh token, so the two never race to rotate one
1657
+ // grant. A separately authorized refresh token stays with the person's own
1658
+ // connection. A failure to read who they are leaves the server sign-in standing.
1659
+ let linking = async (c, name, person, tokens)=>{
1660
+ let i = await known(c.graph.read, name);
1661
+ if (!i) throw new Error(`no integration ${name} to link`);
1662
+ let { refresh_token: _, account: _a, account_title: _t, ...own } = tokens;
1663
+ let who = await signedIn(i, own, c.fetch ?? fetch);
1664
+ if (!who.account) throw new Error(`${name} named no account`);
1665
+ let existing = await forAccount(c.graph.read, {
1666
+ owner: person,
1667
+ integration: name
1668
+ }, who.account);
1669
+ let ask = existing ? undefined : await firstAsk(c.graph.read, person, name, []);
1670
+ let pending = comp(ask, CONNECTION).status == 'needed' ? ask : undefined;
1671
+ let target = existing ?? pending ?? fresh(person, name, i.scopes ?? [], who.account);
1672
+ let previous = existing && comp(existing, CONNECTION).status == 'connected' ? await reveal(c.vault, nameOf(existing)) : undefined;
1673
+ let renewable = previous && JSON.parse(previous).refresh_token;
1674
+ return [
1675
+ {
1676
+ ...existing || pending ? stillHeld(target) : {},
1677
+ entity: {
1678
+ eid: target.entity.eid
1679
+ },
1680
+ ...renewable ? {} : {
1681
+ [SECRET]: {
1682
+ name: nameOf(target),
1683
+ value: JSON.stringify(own)
1684
+ }
1685
+ },
1686
+ [CONNECTION]: {
1687
+ ...comp(target, CONNECTION),
1688
+ status: 'connected',
1689
+ account: who.account,
1690
+ ...who.title ? {
1691
+ title: who.title
1692
+ } : {}
1693
+ }
1694
+ },
1695
+ ...await answered(c.graph.read, fresh(person, name, []), target.entity.eid)
1696
+ ];
1697
+ };
1698
+ // What takes the place of `was`, links to a connection going away or no
1699
+ // longer lent: a connection needing a credential for each owner, and for
1700
+ // each separate binding. The app keeps its binding and access settings.
1701
+ // Borrowers keep their binding and ask in their own space.
1702
+ let reasked = async (b, was, owners)=>{
1703
+ let { integration, owner, scopes } = comp(b, CONNECTION);
1704
+ let loans = was.filter((l)=>comp(l, USES).lender != null);
1705
+ let whose = loans.length && owners ? await owners(loans.map((l)=>far(l, 'to'))) : {};
1706
+ let asks = new Map();
1707
+ let out = [];
1708
+ for (let l of was){
1709
+ let app = far(l, 'to');
1710
+ let u = comp(l, USES);
1711
+ let at = u.lender == null ? String(owner) : whose[app];
1712
+ if (!at) {
1713
+ throw new Error(`no space is known for ${app}, which borrows ${b.entity.eid}`);
1714
+ }
1715
+ let key = JSON.stringify([
1716
+ at,
1717
+ u.separate ? u.binding : null
1718
+ ]);
1719
+ let again = asks.get(key);
1720
+ if (!again) {
1721
+ asks.set(key, again = fresh(at, String(integration), strs(scopes)));
1722
+ out.push(again);
1723
+ }
1724
+ out.push({
1725
+ ...link(app, USES, again.entity.eid),
1726
+ [USES]: u.lender == null ? u : {
1727
+ binding: u.binding,
1728
+ ...u.separate ? {
1729
+ separate: true
1730
+ } : {}
1731
+ }
1732
+ });
1733
+ }
1734
+ return out;
1735
+ };
1736
+ /** Forget any grant held for its approver, then trash the connection. A
1737
+ * broker that does not answer stops neither: the run the connection's death
1738
+ * owes (`ended`) forgets what is left. Its attached credential and kept broker
1739
+ * grant stay available for restoration. The
1740
+ * apps that shared it are linked to a new connection. A copy that borrowed
1741
+ * it is linked to one in its own space, which `owners` says. An app that asks
1742
+ * each person for their own connection continues to ask them. */ export let disconnect = async (c, connection, owners)=>{
1743
+ let b = await held(c.graph.read, connection);
1744
+ let was = (await links(c.graph.read, 'to', connection)).filter((l)=>!comp(l, USES).each);
1745
+ let asks = await reasked(b, was, owners);
1746
+ if (b[APPROVING]) await forgetting(c, b).catch(c.report ?? (()=>{}));
1747
+ return c.graph.apply([
1748
+ {
1749
+ entity: {
1750
+ eid: connection
1751
+ },
1752
+ tombstone: {}
1753
+ },
1754
+ ...asks
1755
+ ]);
1756
+ };
1757
+ // A step against the service's token endpoint. A grant the service refuses
1758
+ // marks the connection broken; a failure on the wire leaves it be.
1759
+ let marking = async (c, connection, step)=>{
1760
+ try {
1761
+ return await step();
1762
+ } catch (e) {
1763
+ if (e instanceof OAuthError && !e.code.startsWith('http_') || e instanceof BrokerError && e.refused) {
1764
+ await c.graph.apply([
1765
+ {
1766
+ ...stillHeld(connection),
1767
+ [CONNECTION]: {
1768
+ status: 'broken'
1769
+ }
1770
+ }
1771
+ ]);
1772
+ }
1773
+ throw e;
1774
+ }
1775
+ };
1776
+ // A connection's fields, as the vault keeps them. A voip.ms key pasted before
1777
+ // its integration named fields was its fields joined by colons; it is read so
1778
+ // and kept as the object it is now, behind the same handle, so its sentinels
1779
+ // hold. TODO: delete the colon reading once no such record is left.
1780
+ let fieldsKept = async (c, b, fields, raw)=>{
1781
+ if (raw.trimStart().startsWith('{')) return JSON.parse(raw);
1782
+ let parts = raw.split(':');
1783
+ let said = Object.fromEntries(fields.map((f, n)=>[
1784
+ f.name,
1785
+ (n < fields.length - 1 ? parts[n] : parts.slice(n).join(':'))?.trim() ?? ''
1786
+ ]));
1787
+ await c.graph.apply([
1788
+ {
1789
+ entity: {
1790
+ eid: b.entity.eid
1791
+ },
1792
+ [SECRET]: {
1793
+ name: nameOf(b),
1794
+ value: JSON.stringify(said)
1795
+ }
1796
+ }
1797
+ ]);
1798
+ return said;
1799
+ };
1800
+ /** What a call out sends in a sentinel's place: the pasted key, one `field` of
1801
+ * several by name, or an access token, refreshed first when it is about to
1802
+ * expire. A credential kept as several fields is only ever read one at a
1803
+ * time. */ /**
1804
+ * The bot token that speaks for a chat connection (`integration.chat`): the
1805
+ * pasted key of a bot the space brought, or, for one that added the
1806
+ * platform's own bot to a server, the bot of the OAuth client its
1807
+ * integration signs in as. None for a connection that does not chat, is not
1808
+ * connected (or not there at all), or whose bot is not kept yet.
1809
+ */ export let botOf = async (c, connection)=>{
1810
+ let [b] = await c.graph.read(line`.entity.eid=${connection}&.${CONNECTION}${sub(ALL)}`);
1811
+ if (comp(b, CONNECTION).status != 'connected') return undefined;
1812
+ let i = await known(c.graph.read, String(comp(b, CONNECTION).integration));
1813
+ return botFrom(c, b, i);
1814
+ };
1815
+ /** The bot token for a connection and integration already read together. */ export let botFrom = async (c, b, i)=>{
1816
+ if (comp(b, CONNECTION).status != 'connected' || !i?.chat) return undefined;
1817
+ if (keyed(i)) return keyOf(c, b, i);
1818
+ if (i.chat_grant) {
1819
+ return marking(c, b, (await signIn(c, b)).token);
1820
+ }
1821
+ return (await clientOf(c.vault, c.graph.read, i))?.bot;
1822
+ };
1823
+ let keyOf = async (c, b, i, field)=>{
1824
+ let fields = fieldsOf(i);
1825
+ if (fields.length > 1 && field == null) {
1826
+ throw new Error(`${i.name} is kept as several fields; read one by name`);
1827
+ }
1828
+ let name = field ?? fields[0].name;
1829
+ if (!fields.some((f)=>f.name == name)) return undefined;
1830
+ return (await keyFields(c, b, fields))?.[name];
1831
+ };
1832
+ let keyFields = async (c, b, fields)=>keyValues(c, b, fields, await reveal(c.vault, nameOf(b)));
1833
+ let keyValues = (c, b, fields, raw)=>{
1834
+ if (!raw) return undefined;
1835
+ return fields.length == 1 ? {
1836
+ [fields[0].name]: raw
1837
+ } : fieldsKept(c, b, fields, raw);
1838
+ };
1839
+ export let credential = async (c, connection, field)=>{
1840
+ let b = await held(c.graph.read, connection);
1841
+ let i = await known(c.graph.read, integrated(b));
1842
+ if (i && keyed(i)) return keyOf(c, b, i, field);
1843
+ if (field != null && field != fieldsOf()[0].name) return undefined;
1844
+ return granted(c, b);
1845
+ };
1846
+ /** Read both site sign-in fields from one version of the vaulted credential. */ export let loginCredential = async (c, connection)=>{
1847
+ let i = await known(c.graph.read, integrated(connection));
1848
+ if (!i || !keyed(i) || !loginFields(fieldsOf(i))) return;
1849
+ let fields = await keyFields(c, connection, fieldsOf(i));
1850
+ let { username, password } = fields ?? {};
1851
+ if (typeof username == 'string' && username && typeof password == 'string' && password) {
1852
+ return {
1853
+ username,
1854
+ password
1855
+ };
1856
+ }
1857
+ };
1858
+ let granted = async (c, b)=>{
1859
+ let raw = await reveal(c.vault, nameOf(b), {
1860
+ env: ()=>undefined
1861
+ });
1862
+ if (comp(b, CONNECTION).broker) {
1863
+ return marking(c, b, ()=>brokered(c, b));
1864
+ }
1865
+ if (raw && !raw.trimStart().startsWith('{')) return raw;
1866
+ let oauth = await signIn(c, b);
1867
+ return marking(c, b, oauth.token);
1868
+ };
1869
+ let keptGrant = (broker, integration, id, g)=>({
1870
+ broker,
1871
+ integration,
1872
+ id,
1873
+ access_token: g.access_token,
1874
+ ...g.expires_at ? {
1875
+ expires_at: g.expires_at
1876
+ } : {}
1877
+ });
1878
+ // A brokered connection's access token: the one kept while it is good for a
1879
+ // minute more, else the broker's, which the broker refreshes when it is due;
1880
+ // with `stale`, a new one unless another caller already replaced it. The
1881
+ // connection is asked of the broker it was made through, by what that broker
1882
+ // called its integration then, whatever its integration names now.
1883
+ let brokered = (c, b, stale)=>{
1884
+ let now = (c.now ?? Date.now)();
1885
+ return keeping(c, b).update(nameOf(b), async (r)=>{
1886
+ let good = r.access_token && (stale ? r.access_token != stale : r.expires_at && r.expires_at - now > 60_000);
1887
+ if (good) return r.access_token;
1888
+ let { broker, integration, id } = r;
1889
+ if (!broker || !integration || !id) {
1890
+ throw new Error(`${nameOf(b)} names no connection at its broker`);
1891
+ }
1892
+ let g = await (await brokering(c, broker)).grant(integration, id, !!stale);
1893
+ if (!g.expires_at) delete r.expires_at;
1894
+ Object.assign(r, keptGrant(broker, integration, id, g));
1895
+ return g.access_token;
1896
+ });
1897
+ };
1898
+ /** A new access token behind the same handle, after the service refused
1899
+ * `stale`, unless another caller already replaced it. A grant the service
1900
+ * refuses marks the connection broken; a failure on the wire leaves it be. */ export let refresh = async (c, connection, stale)=>{
1901
+ let b = await held(c.graph.read, connection);
1902
+ if (comp(b, CONNECTION).broker) {
1903
+ return marking(c, b, ()=>brokered(c, b, stale));
1904
+ }
1905
+ let oauth = await signIn(c, b);
1906
+ return marking(c, b, ()=>oauth.refresh(stale));
1907
+ };
1908
+ /** Send a request through a connection for the one who holds it, its
1909
+ * credential as the bearer: over https to a host its integration names, and
1910
+ * to no other, following no redirect. A service that refuses the access token
1911
+ * (401) is asked once more with a refreshed one. */ export let call = async (c, connection, req)=>{
1912
+ let b = await held(c.graph.read, connection);
1913
+ let name = String(comp(b, CONNECTION).integration);
1914
+ let i = await known(c.graph.read, name);
1915
+ let url = new URL(req.url);
1916
+ if (url.protocol != 'https:' || !i?.hosts.includes(url.host)) {
1917
+ throw new CallError('access', `${name} sends its credential to no ${url.host}`);
1918
+ }
1919
+ let bearer = await credential(c, connection);
1920
+ if (!bearer) throw new CallError('missing', `${name} holds no credential yet`);
1921
+ let body = req.body ? await req.arrayBuffer() : undefined;
1922
+ let send = (token)=>{
1923
+ let headers = new Headers(req.headers);
1924
+ headers.set('authorization', `Bearer ${token}`);
1925
+ return (c.fetch ?? fetch)(url, {
1926
+ method: req.method,
1927
+ headers,
1928
+ body,
1929
+ redirect: 'manual'
1930
+ });
1931
+ };
1932
+ let res = await send(bearer);
1933
+ if (res.status != 401 || keyed(i)) return res;
1934
+ let fresh = await refresh(c, connection, bearer);
1935
+ if (!fresh || fresh == bearer) return res;
1936
+ await res.body?.cancel();
1937
+ return send(fresh);
1938
+ };
1939
+ /** A selected account's bearer and optional website session, read privately
1940
+ * from its vault. The session is not handed to browser-only API doors. */ export let accountCredential = async (ctx, owner, integration, as)=>{
1941
+ let connection = await pick(ctx.graph.read, owner, integration, as);
1942
+ if (!connection) return undefined;
1943
+ let bearer = await credential(ctx, connection.entity.eid);
1944
+ if (!bearer) return undefined;
1945
+ let raw = await reveal(ctx.vault, nameOf(connection), {
1946
+ env: ()=>undefined
1947
+ });
1948
+ let session;
1949
+ try {
1950
+ let record = JSON.parse(raw ?? '{}');
1951
+ session = typeof record.website_session == 'string' ? record.website_session : undefined;
1952
+ } catch {}
1953
+ return {
1954
+ connection,
1955
+ bearer,
1956
+ ...session ? {
1957
+ session
1958
+ } : {}
1959
+ };
1960
+ };
1961
+ //# sourceMappingURL=connections.js.map