@yaks/phone 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 (81) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +251 -2
  3. package/_dist/call.d.ts +37 -0
  4. package/_dist/call.d.ts.map +1 -0
  5. package/_dist/effects.d.ts +5 -0
  6. package/_dist/effects.d.ts.map +1 -0
  7. package/_dist/mobile.d.ts +41 -0
  8. package/_dist/mobile.d.ts.map +1 -0
  9. package/_dist/mod.d.ts +27 -0
  10. package/_dist/mod.d.ts.map +1 -0
  11. package/_dist/numbers.d.ts +150 -0
  12. package/_dist/numbers.d.ts.map +1 -0
  13. package/_dist/options.d.ts +21 -0
  14. package/_dist/options.d.ts.map +1 -0
  15. package/_dist/plugin.d.ts +54 -0
  16. package/_dist/plugin.d.ts.map +1 -0
  17. package/_dist/provider.d.ts +72 -0
  18. package/_dist/provider.d.ts.map +1 -0
  19. package/_dist/received.d.ts +24 -0
  20. package/_dist/received.d.ts.map +1 -0
  21. package/_dist/replies.d.ts +18 -0
  22. package/_dist/replies.d.ts.map +1 -0
  23. package/_dist/send.d.ts +16 -0
  24. package/_dist/send.d.ts.map +1 -0
  25. package/_dist/stash.d.ts +19 -0
  26. package/_dist/stash.d.ts.map +1 -0
  27. package/_dist/text.d.ts +102 -0
  28. package/_dist/text.d.ts.map +1 -0
  29. package/_dist/tools.d.ts +3 -0
  30. package/_dist/tools.d.ts.map +1 -0
  31. package/_dist/vocab.d.ts +8 -0
  32. package/_dist/vocab.d.ts.map +1 -0
  33. package/call.js +5 -0
  34. package/call.js.map +1 -0
  35. package/call.ts +53 -0
  36. package/deno.json +1 -0
  37. package/effects.js +30 -0
  38. package/effects.js.map +1 -0
  39. package/effects.ts +35 -0
  40. package/mobile.js +75 -0
  41. package/mobile.js.map +1 -0
  42. package/mobile.ts +72 -0
  43. package/mod.js +28 -0
  44. package/mod.js.map +1 -0
  45. package/mod.ts +78 -0
  46. package/numbers.js +72 -0
  47. package/numbers.js.map +1 -0
  48. package/numbers.ts +259 -0
  49. package/options.js +3 -0
  50. package/options.js.map +1 -0
  51. package/options.ts +23 -0
  52. package/package.json +44 -4
  53. package/plugin.js +155 -0
  54. package/plugin.js.map +1 -0
  55. package/plugin.ts +226 -0
  56. package/provider.js +48 -0
  57. package/provider.js.map +1 -0
  58. package/provider.ts +119 -0
  59. package/received.js +72 -0
  60. package/received.js.map +1 -0
  61. package/received.ts +76 -0
  62. package/recipients.js +58 -0
  63. package/replies.js +23 -0
  64. package/replies.js.map +1 -0
  65. package/replies.ts +38 -0
  66. package/send.js +136 -0
  67. package/send.js.map +1 -0
  68. package/send.ts +131 -0
  69. package/stash.js +26 -0
  70. package/stash.js.map +1 -0
  71. package/stash.ts +41 -0
  72. package/text.js +127 -0
  73. package/text.js.map +1 -0
  74. package/text.ts +192 -0
  75. package/tools.js +62 -0
  76. package/tools.js.map +1 -0
  77. package/tools.ts +55 -0
  78. package/vocab.js +18 -0
  79. package/vocab.js.map +1 -0
  80. package/vocab.json +245 -0
  81. package/vocab.ts +19 -0
package/options.ts ADDED
@@ -0,0 +1,23 @@
1
+ /** What a config passes to @yaks/phone: which lent texter sends, by name
2
+ * (`stash` keeps texts in memory). */
3
+ export type Options = {
4
+ sender?: { via: string }
5
+ }
6
+
7
+ /** Provider selection and credentials, passed to that provider's factory. */
8
+ export type Transport = {
9
+ via: string
10
+ key?: string
11
+ profile?: string
12
+ user?: string
13
+ number?: string
14
+ tollFree?: boolean
15
+ /** the kinds of number a provider that sells them sells here */
16
+ sells?: ('local' | 'toll_free')[]
17
+ api?: string
18
+ /** the only API methods a person's own account may be asked, as the
19
+ * integration they connected it through lists them (@yaks/connections
20
+ * `Integration.methods`) */
21
+ methods?: string[]
22
+ fetch?: typeof fetch
23
+ }
package/package.json CHANGED
@@ -1,6 +1,46 @@
1
1
  {
2
2
  "name": "@yaks/phone",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.2.36",
4
+ "homepage": "https://jsr.io/@yaks/phone",
5
+ "type": "module",
6
+ "exports": {
7
+ ".": {
8
+ "types": "./_dist/mod.d.ts",
9
+ "default": "./mod.js"
10
+ },
11
+ "./mobile": {
12
+ "types": "./_dist/mobile.d.ts",
13
+ "default": "./mobile.js"
14
+ },
15
+ "./vocab": {
16
+ "types": "./_dist/vocab.d.ts",
17
+ "default": "./vocab.js"
18
+ },
19
+ "./effects": {
20
+ "types": "./_dist/effects.d.ts",
21
+ "default": "./effects.js"
22
+ },
23
+ "./plugin": {
24
+ "types": "./_dist/plugin.d.ts",
25
+ "default": "./plugin.js"
26
+ },
27
+ "./tools": {
28
+ "types": "./_dist/tools.d.ts",
29
+ "default": "./tools.js"
30
+ }
31
+ },
32
+ "license": "Apache-2.0",
33
+ "dependencies": {
34
+ "@yaks/api": "0.2.36",
35
+ "@yaks/effects": "0.2.36",
36
+ "@yaks/graph": "0.2.36",
37
+ "@yaks/hook": "0.2.36",
38
+ "@yaks/host": "0.2.36",
39
+ "@yaks/query": "0.2.36",
40
+ "@yaks/tools": "0.2.36",
41
+ "@yaks/vocab": "0.2.36",
42
+ "libphonenumber-js": "^1.13.15"
43
+ },
44
+ "description": "Phone numbers, provider selection, consent, texts and delivery outcomes in the graph, through a provider supplied at the transport boundary.",
45
+ "repository": "https://github.com/yak-sh/yak.git"
46
+ }
package/plugin.js ADDED
@@ -0,0 +1,155 @@
1
+ // What a provider package is built from to be a plugin a config names beside
2
+ // @yaks/phone: the phone it lends its host under its own name, a texter
3
+ // with the provider's webhook and calls beside it, and the webhook door its
4
+ // provider posts to. Phone implements both once; a provider gives its
5
+ // `Provider` as data, and phone never names one.
6
+ //
7
+ // ```json
8
+ // [ { "use": "@yaks/pinnacle",
9
+ // "with": { "key": { "secret": "PINNACLE_API_KEY" },
10
+ // "number": "+12695550100",
11
+ // "door": { "key": { "secret": "PINNACLE_SIGNING_SECRET" } } } },
12
+ // { "use": "@yaks/phone", "with": { "sender": { "via": "pinnacle" } } } ]
13
+ // ```
14
+ import { fault, json, refuse } from "@yaks/api/refuse";
15
+ import { Refused } from "@yaks/graph/errors";
16
+ import { line } from "@yaks/query";
17
+ import { kept, settled } from "./received.js";
18
+ import { listens, sender, verified } from "./provider.js";
19
+ let phone = (via, provider, options)=>{
20
+ let transport = ()=>({
21
+ ...options(),
22
+ via
23
+ });
24
+ let missing = ()=>provider.needs?.filter((key)=>!transport()[key]) ?? [];
25
+ let made = ()=>sender(transport(), provider);
26
+ return {
27
+ transport,
28
+ send: (text)=>made().send(text),
29
+ from: ()=>made().from?.() ?? Promise.resolve(undefined),
30
+ waiting: ()=>missing().length ? `waiting for credentials: a ${via} sender needs ${missing().join(', ')}` : undefined,
31
+ over: (more)=>phone(via, provider, ()=>({
32
+ ...options(),
33
+ ...more
34
+ })),
35
+ hear: async (request)=>{
36
+ let key = options().door?.key;
37
+ return key && listens(provider) ? await verified(provider, key, request) : undefined;
38
+ },
39
+ ...provider.caller ? {
40
+ caller: ()=>provider.caller(transport())
41
+ } : {},
42
+ ...provider.line ? {
43
+ line: provider.line
44
+ } : {},
45
+ ...provider.own ? {
46
+ own: provider.own
47
+ } : {},
48
+ ...provider.numbers ? {
49
+ numbers: ()=>provider.numbers(transport())
50
+ } : {}
51
+ };
52
+ };
53
+ /** The phone a provider lends as `via`. Until its options carry what the
54
+ * provider `needs`, it is waiting. */ export let lent = (via, provider, options = {})=>phone(via, provider, ()=>options);
55
+ /** The graph facet of the provider plugin `via`: `texters(host, options)`
56
+ * lends its phone under that name. */ export let texters = (via, provider)=>(_host, options = {})=>({
57
+ [via]: lent(via, provider, options)
58
+ });
59
+ // What a door keeps of what its provider said: a text that arrived, from
60
+ // whoever here wears its number, and a sent text's later failure.
61
+ let keep = async (graph, via, heard)=>{
62
+ let { arrival, outcome } = heard;
63
+ if (arrival) {
64
+ let people = await graph.read(line`.phone.number=${arrival.from}`);
65
+ await graph.apply(kept({
66
+ ...arrival,
67
+ via
68
+ }, people.map((p)=>p.entity.eid)));
69
+ }
70
+ if (outcome) {
71
+ let [sent] = await graph.read(line`.text.via=${via}&.text.message_id=${outcome.id}`);
72
+ if (sent) {
73
+ await graph.apply(settled(outcome, sent.entity.eid), {
74
+ trusted: true
75
+ });
76
+ }
77
+ }
78
+ };
79
+ // Two strings compared in time that says nothing of where they differ.
80
+ let same = (a, b)=>{
81
+ let x = new TextEncoder().encode(a);
82
+ let y = new TextEncoder().encode(b);
83
+ let diff = x.length ^ y.length;
84
+ for(let i = 0; i < Math.max(x.length, y.length); i++){
85
+ diff |= (x[i] ?? 0) ^ (y[i] ?? 0);
86
+ }
87
+ return diff == 0;
88
+ };
89
+ /** A provider plugin's routes facet, where the options name a door. A
90
+ * provider that signs its webhooks is posted to at `POST /<via>/webhook`: a
91
+ * missing or stale signature is refused quietly; one that is complete and
92
+ * does not match, which is what a wrong key looks like, is refused and
93
+ * reported. One whose texts arrive by a callback URL it signs nothing on
94
+ * (its `own.called`, voip.ms's) is called at `GET /<via>/<key>?<query>`, the
95
+ * door's key in the path being what says the call is the provider's; the
96
+ * host points the number's callback there, with `own.callback` as its
97
+ * query. */ export let routes = (via, provider)=>(host, options = {})=>{
98
+ let door = options.door;
99
+ if (door && listens(provider)) {
100
+ return [
101
+ {
102
+ method: 'POST',
103
+ path: door.path ?? `/${via}/webhook`,
104
+ handle: async (request)=>{
105
+ let said = await verified(provider, door.key, request);
106
+ if ('refused' in said) {
107
+ if (said.ours) {
108
+ fault(new Error(said.refused), `POST ${new URL(request.url).pathname}`);
109
+ }
110
+ return refuse(new Refused(`not signed by ${via}: ${said.refused}`), request);
111
+ }
112
+ try {
113
+ await keep(host.graph, via, said.heard);
114
+ return json({});
115
+ } catch (error) {
116
+ return refuse(error, request);
117
+ }
118
+ }
119
+ }
120
+ ];
121
+ }
122
+ let called = provider.own?.called;
123
+ if (!door || !called) return [];
124
+ let base = door.path ?? `/${via}`;
125
+ return [
126
+ {
127
+ method: 'GET',
128
+ path: `${base}/*`,
129
+ sensitive: true,
130
+ handle: async (request)=>{
131
+ let url = new URL(request.url);
132
+ let key = decodeURIComponent(url.pathname.slice(base.length + 1));
133
+ if (!door.key || !same(key, door.key)) {
134
+ return new Response('not ours', {
135
+ status: 403
136
+ });
137
+ }
138
+ try {
139
+ let arrival = called(url.searchParams);
140
+ if (arrival) await keep(host.graph, via, {
141
+ arrival
142
+ });
143
+ return new Response('ok', {
144
+ headers: {
145
+ 'content-type': 'text/plain'
146
+ }
147
+ });
148
+ } catch (error) {
149
+ return refuse(error, request);
150
+ }
151
+ }
152
+ }
153
+ ];
154
+ };
155
+ //# sourceMappingURL=plugin.js.map
package/plugin.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"plugin.js","sources":["./plugin.ts"],"names":[],"mappings":"AAAA,6EAA6E;AAC7E,wEAAwE;AACxE,4EAA4E;AAC5E,sEAAsE;AACtE,iDAAiD;AACjD,EAAE;AACF,UAAU;AACV,+BAA+B;AAC/B,yDAAyD;AACzD,0CAA0C;AAC1C,gFAAgF;AAChF,4EAA4E;AAC5E,MAAM;AAIN,SAAS,KAAK,EAAE,IAAI,EAAE,MAAM,gCAAqC;AACjE,SAAS,OAAO,kCAAuC;AACvD,SAAS,IAAI,2BAAgC;AAE7C,SAAS,IAAI,EAAE,OAAO,wBAAuB;AAC7C,SAEE,OAAO,EAGP,MAAM,EACN,QAAQ,wBACY;AAiDtB,IAAI,QAAQ,CAAC,KAAa,UAAoB;EAC5C,IAAI,YAAY,IAAiB,CAAC;MAAE,GAAG,SAAS;MAAE;IAAI,CAAC;EACvD,IAAI,UAAU,IAAM,SAAS,KAAK,EAAE,OAAO,CAAC,MAAQ,CAAC,WAAW,CAAC,IAAI,KAAK,EAAE;EAC5E,IAAI,OAAO,IAAM,OAAO,aAAa;EACrC,OAAO;IACL;IACA,MAAM,CAAC,OAAS,OAAO,IAAI,CAAC;IAC5B,MAAM,IAAM,OAAO,IAAI,QAAQ,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cAE3C;cACA,OAAO,OACL,IAAI,QAAQ,CAAC,cAAc,EAAE,IAAI,EAAE,EAAE,KAAK,OAAO,EAAE,GACnD;YAEJ;YACA,IAAI;cACF,MAAM,KAAK,KAAK,KAAK,EAAE,KAAK,KAAK,KAAK;cACtC,OAAO,KAAK,CAAC;YACf,EAAE,OAAO,OAAO;cACd,OAAO,OAAO,OAAO;YACvB;UACF;QACF;OAAE;IACJ;IACA,IAAI,SAAS,SAAS,GAAG,EAAE;IAC3B,IAAI,CAAC,QAAQ,CAAC,QAAQ,OAAO,EAAE;IAC/B,IAAI,OAAO,KAAK,IAAI,IAAI,CAAC,CAAC,EAAE,KAAK;IACjC,OAAO;MAAC;QACN,QAAQ;QACR,MAAM,GAAG,KAAK,EAAE,CAAC;QACjB,WAAW;QACX,QAAQ,OAAO;UACb,IAAI,MAAM,IAAI,IAAI,QAAQ,GAAG;UAC7B,IAAI,MAAM,mBAAmB,IAAI,QAAQ,CAAC,KAAK,CAAC,KAAK,MAAM,GAAG;UAC9D,IAAI,CAAC,KAAK,GAAG,IAAI,CAAC,KAAK,KAAK,KAAK,GAAG,GAAG;YACrC,OAAO,IAAI,SAAS,YAAY;cAAE,QAAQ;YAAI;UAChD;UACA,IAAI;YACF,IAAI,UAAU,OAAO,IAAI,YAAY;YACrC,IAAI,SAAS,MAAM,KAAK,KAAK,KAAK,EAAE,KAAK;cAAE;YAAQ;YACnD,OAAO,IAAI,SAAS,MAAM;cACxB,SAAS;gBAAE,gBAAgB;cAAa;YAC1C;UACF,EAAE,OAAO,OAAO;YACd,OAAO,OAAO,OAAO;UACvB;QACF;MACF;KAAE;EACJ,EAAC"}
package/plugin.ts ADDED
@@ -0,0 +1,226 @@
1
+ // What a provider package is built from to be a plugin a config names beside
2
+ // @yaks/phone: the phone it lends its host under its own name, a texter
3
+ // with the provider's webhook and calls beside it, and the webhook door its
4
+ // provider posts to. Phone implements both once; a provider gives its
5
+ // `Provider` as data, and phone never names one.
6
+ //
7
+ // ```json
8
+ // [ { "use": "@yaks/pinnacle",
9
+ // "with": { "key": { "secret": "PINNACLE_API_KEY" },
10
+ // "number": "+12695550100",
11
+ // "door": { "key": { "secret": "PINNACLE_SIGNING_SECRET" } } } },
12
+ // { "use": "@yaks/phone", "with": { "sender": { "via": "pinnacle" } } } ]
13
+ // ```
14
+
15
+ import type { Graph } from 'jsr:@yaks/graph@0.2.36'
16
+ import type { Route } from 'jsr:@yaks/api@0.2.36'
17
+ import { fault, json, refuse } from '@yaks/api/refuse'
18
+ import { Refused } from '@yaks/graph/errors'
19
+ import { line } from '@yaks/query'
20
+ import type { Transport } from './options.ts'
21
+ import { kept, settled } from './received.js'
22
+ import {
23
+ type Heard,
24
+ listens,
25
+ type Own,
26
+ type Provider,
27
+ sender,
28
+ verified,
29
+ } from './provider.js'
30
+ import type { Caller, Line } from './call.ts'
31
+ import type { Numbers } from './numbers.ts'
32
+ import type { Texter } from 'jsr:@yaks/host@0.2.36/senders'
33
+
34
+ /** The webhook door: where the provider posts, and the key that verifies it. */
35
+ export type Door = {
36
+ /** defaults to /<via>/webhook */
37
+ path?: string
38
+ key: string
39
+ }
40
+
41
+ /** What a config passes to a provider plugin: its transport's settings and
42
+ * credentials, and its door when it takes webhooks. Secrets are resolved by
43
+ * the host, and read at every text. */
44
+ export type Lent = Omit<Transport, 'via'> & { door?: Door }
45
+
46
+ /** What a provider's webhook said once its door read it: what it heard, or
47
+ * why it was refused (`verified`). */
48
+ export type Said = Awaited<ReturnType<typeof verified>>
49
+
50
+ /** A provider as its plugin lends it under its name: a texter to any host,
51
+ * and the rest of what the provider offers. Each part is built from the
52
+ * plugin's options at its use, so a secret set after start-up is used by
53
+ * the next. */
54
+ export type Phone = Texter & {
55
+ /** the transport its options make now, `via` its name */
56
+ transport: () => Transport
57
+ /** the number it texts from when a text names none: its options', else
58
+ * the one the provider picks, where it can say */
59
+ from: () => Promise<string | undefined>
60
+ /** the same phone with `more` laid over its options, such as a number of
61
+ * its own */
62
+ over: (more: Partial<Lent>) => Phone
63
+ /** a request to its webhook, verified with its door's key; undefined
64
+ * where it has no door or takes no webhooks */
65
+ hear: (request: Request) => Promise<Said | undefined>
66
+ /** what it is asked to do with calls, where it takes them */
67
+ caller?: () => Caller
68
+ /** the wire its calls' audio streams over, where it takes them */
69
+ line?: Line
70
+ /** how a person connects a number of their own through it, where it
71
+ * offers that: their account opens with their own settings alone */
72
+ own?: Own
73
+ /** the numbers it sells, on the account it texts through, where it
74
+ * sells them */
75
+ numbers?: () => Numbers
76
+ }
77
+
78
+ let phone = (via: string, provider: Provider, options: () => Lent): Phone => {
79
+ let transport = (): Transport => ({ ...options(), via })
80
+ let missing = () => provider.needs?.filter((key) => !transport()[key]) ?? []
81
+ let made = () => sender(transport(), provider)
82
+ return {
83
+ transport,
84
+ send: (text) => made().send(text),
85
+ from: () => made().from?.() ?? Promise.resolve(undefined),
86
+ waiting: () =>
87
+ missing().length
88
+ ? `waiting for credentials: a ${via} sender needs ${
89
+ missing().join(', ')
90
+ }`
91
+ : undefined,
92
+ over: (more) => phone(via, provider, () => ({ ...options(), ...more })),
93
+ hear: async (request) => {
94
+ let key = options().door?.key
95
+ return key && listens(provider)
96
+ ? await verified(provider, key, request)
97
+ : undefined
98
+ },
99
+ ...provider.caller ? { caller: () => provider.caller!(transport()) } : {},
100
+ ...provider.line ? { line: provider.line } : {},
101
+ ...provider.own ? { own: provider.own } : {},
102
+ ...provider.numbers
103
+ ? { numbers: () => provider.numbers!(transport()) }
104
+ : {},
105
+ }
106
+ }
107
+
108
+ /** The phone a provider lends as `via`. Until its options carry what the
109
+ * provider `needs`, it is waiting. */
110
+ export let lent = (
111
+ via: string,
112
+ provider: Provider,
113
+ options: Lent = {},
114
+ ): Phone => phone(via, provider, () => options)
115
+
116
+ /** A provider plugin's graph facet, lending its phone by name. */
117
+ export type Texters = (
118
+ host: unknown,
119
+ options?: Lent,
120
+ ) => Record<string, Phone>
121
+
122
+ /** A provider plugin's routes facet, its webhook door. */
123
+ export type Routes = (host: { graph: Graph }, options?: Lent) => Route[]
124
+
125
+ /** The graph facet of the provider plugin `via`: `texters(host, options)`
126
+ * lends its phone under that name. */
127
+ export let texters =
128
+ (via: string, provider: Provider): Texters => (_host, options = {}) => ({
129
+ [via]: lent(via, provider, options),
130
+ })
131
+
132
+ // What a door keeps of what its provider said: a text that arrived, from
133
+ // whoever here wears its number, and a sent text's later failure.
134
+ let keep = async (graph: Graph, via: string, heard: Heard): Promise<void> => {
135
+ let { arrival, outcome } = heard
136
+ if (arrival) {
137
+ let people = await graph.read(line`.phone.number=${arrival.from}`)
138
+ await graph.apply(
139
+ kept({ ...arrival, via }, people.map((p) => p.entity.eid)),
140
+ )
141
+ }
142
+ if (outcome) {
143
+ let [sent] = await graph.read(
144
+ line`.text.via=${via}&.text.message_id=${outcome.id}`,
145
+ )
146
+ if (sent) {
147
+ await graph.apply(settled(outcome, sent.entity.eid), { trusted: true })
148
+ }
149
+ }
150
+ }
151
+
152
+ // Two strings compared in time that says nothing of where they differ.
153
+ let same = (a: string, b: string): boolean => {
154
+ let x = new TextEncoder().encode(a)
155
+ let y = new TextEncoder().encode(b)
156
+ let diff = x.length ^ y.length
157
+ for (let i = 0; i < Math.max(x.length, y.length); i++) {
158
+ diff |= (x[i] ?? 0) ^ (y[i] ?? 0)
159
+ }
160
+ return diff == 0
161
+ }
162
+
163
+ /** A provider plugin's routes facet, where the options name a door. A
164
+ * provider that signs its webhooks is posted to at `POST /<via>/webhook`: a
165
+ * missing or stale signature is refused quietly; one that is complete and
166
+ * does not match, which is what a wrong key looks like, is refused and
167
+ * reported. One whose texts arrive by a callback URL it signs nothing on
168
+ * (its `own.called`, voip.ms's) is called at `GET /<via>/<key>?<query>`, the
169
+ * door's key in the path being what says the call is the provider's; the
170
+ * host points the number's callback there, with `own.callback` as its
171
+ * query. */
172
+ export let routes =
173
+ (via: string, provider: Provider): Routes => (host, options = {}) => {
174
+ let door = options.door
175
+ if (door && listens(provider)) {
176
+ return [{
177
+ method: 'POST',
178
+ path: door.path ?? `/${via}/webhook`,
179
+ handle: async (request) => {
180
+ let said = await verified(provider, door.key, request)
181
+ if ('refused' in said) {
182
+ if (said.ours) {
183
+ fault(
184
+ new Error(said.refused),
185
+ `POST ${new URL(request.url).pathname}`,
186
+ )
187
+ }
188
+ return refuse(
189
+ new Refused(`not signed by ${via}: ${said.refused}`),
190
+ request,
191
+ )
192
+ }
193
+ try {
194
+ await keep(host.graph, via, said.heard)
195
+ return json({})
196
+ } catch (error) {
197
+ return refuse(error, request)
198
+ }
199
+ },
200
+ }]
201
+ }
202
+ let called = provider.own?.called
203
+ if (!door || !called) return []
204
+ let base = door.path ?? `/${via}`
205
+ return [{
206
+ method: 'GET',
207
+ path: `${base}/*`,
208
+ sensitive: true,
209
+ handle: async (request) => {
210
+ let url = new URL(request.url)
211
+ let key = decodeURIComponent(url.pathname.slice(base.length + 1))
212
+ if (!door.key || !same(key, door.key)) {
213
+ return new Response('not ours', { status: 403 })
214
+ }
215
+ try {
216
+ let arrival = called(url.searchParams)
217
+ if (arrival) await keep(host.graph, via, { arrival })
218
+ return new Response('ok', {
219
+ headers: { 'content-type': 'text/plain' },
220
+ })
221
+ } catch (error) {
222
+ return refuse(error, request)
223
+ }
224
+ },
225
+ }]
226
+ }
package/provider.js ADDED
@@ -0,0 +1,48 @@
1
+ // Providers own their wire formats. Phone asks for a sender and normalized
2
+ // events; a provider package gives its `Provider` as data, and a plugin built
3
+ // from it (./plugin.ts) lends it under its own name.
4
+ import { ours, refusal } from "@yaks/hook";
5
+ /** Whether a provider takes webhooks: it says how they are signed and how to
6
+ * read one. */ export let listens = (transport)=>!!transport?.scheme && !!transport.heard;
7
+ /** A provider's webhook, read once its signature checks out under `key`.
8
+ * Otherwise it is refused with why; `ours` marks a refusal that can mean the
9
+ * key is wrong, which the door reports. */ export let verified = async (transport, key, request)=>{
10
+ if (!listens(transport)) throw new Error('This provider takes no webhooks');
11
+ let body = await request.text();
12
+ let why = await refusal(transport.scheme, key, body, request.headers);
13
+ return why ? {
14
+ refused: why,
15
+ ours: ours(why)
16
+ } : {
17
+ heard: transport.heard(JSON.parse(body))
18
+ };
19
+ };
20
+ /** A configured provider, with a texter's outbound provenance attached. */ export let sender = (options, transport)=>{
21
+ let built = transport.sender(options);
22
+ // A number the options name is the number it sends from; otherwise the
23
+ // provider says, where it can.
24
+ let from = options.number;
25
+ let own = from ? ()=>Promise.resolve(from) : built.from;
26
+ return {
27
+ ...own ? {
28
+ from: own
29
+ } : {},
30
+ send: async (text)=>{
31
+ let by = text.from ?? from;
32
+ let receipt = await built.send({
33
+ ...text,
34
+ ...by ? {
35
+ from: by
36
+ } : {}
37
+ });
38
+ return {
39
+ ...receipt,
40
+ via: options.via,
41
+ ...receipt.from || by ? {
42
+ from: receipt.from ?? by
43
+ } : {}
44
+ };
45
+ }
46
+ };
47
+ };
48
+ //# sourceMappingURL=provider.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"provider.js","sources":["./provider.ts"],"names":[],"mappings":"AAAA,2EAA2E;AAC3E,8EAA8E;AAC9E,qDAAqD;AACrD,SAAS,IAAI,EAAE,OAAO,0BAA4C;AAyElE;aACa,GACb,OAAO,IAAI,UAAU,CAAC,YAGjB,CAAC,CAAC,WAAW,UAAU,CAAC,CAAC,UAAU,KAAK,CAAA;AAE7C;;yCAEyC,GACzC,OAAO,IAAI,WAAW,OACpB,WACA,KACA;EAEA,IAAI,CAAC,QAAQ,YAAY,MAAM,IAAI,MAAM;EACzC,IAAI,OAAO,MAAM,QAAQ,IAAI;EAC7B,IAAI,MAAM,MAAM,QAAQ,UAAU,MAAM,EAAE,KAAK,MAAM,QAAQ,OAAO;EACpE,OAAO,MACH;IAAE,SAAS;IAAK,MAAM,KAAK;EAAK,IAChC;IAAE,OAAO,UAAU,KAAK,CAAC,KAAK,KAAK,CAAC;EAAO;AACjD,EAAC;AAED,yEAAyE,GACzE,OAAO,IAAI,SAAS,CAAC,SAAoB;EACvC,IAAI,QAAQ,UAAU,MAAM,CAAC;EAC7B,uEAAuE;EACvE,+BAA+B;EAC/B,IAAI,OAAO,QAAQ,MAAM;EACzB,IAAI,MAAM,OAAO,IAAM,QAAQ,OAAO,CAAC,QAAQ,MAAM,IAAI;EACzD,OAAO;IACL,GAAI,MAAM;MAAE,MAAM;IAAI,IAAI,CAAC,CAAC;IAC5B,MAAM,OAAO;MACX,IAAI,KAAK,KAAK,IAAI,IAAI;MACtB,IAAI,UAAU,MAAM,MAAM,IAAI,CAAC;QAAE,GAAG,IAAI;QAAE,GAAI,KAAK;UAAE,MAAM;QAAG,IAAI,CAAC,CAAC;MAAE;MACtE,OAAO;QACL,GAAG,OAAO;QACV,KAAK,QAAQ,GAAG;QAChB,GAAI,QAAQ,IAAI,IAAI,KAAK;UAAE,MAAM,QAAQ,IAAI,IAAI;QAAG,IAAI,CAAC,CAAC;MAC5D;IACF;EACF;AACF,EAAC"}
package/provider.ts ADDED
@@ -0,0 +1,119 @@
1
+ // Providers own their wire formats. Phone asks for a sender and normalized
2
+ // events; a provider package gives its `Provider` as data, and a plugin built
3
+ // from it (./plugin.ts) lends it under its own name.
4
+ import { ours, refusal, type Scheme } from '@yaks/hook'
5
+ import type { Arrival, Outcome, Sender } from './text.ts'
6
+ import type { Transport } from './options.ts'
7
+ import type { Caller, Line, Ring } from './call.ts'
8
+ import type { Numbers } from './numbers.ts'
9
+
10
+ /** What a provider's webhook said: a text arrived or settled, a call rang,
11
+ * or a call ended. */
12
+ export type Heard = {
13
+ arrival?: Arrival
14
+ outcome?: Outcome
15
+ ring?: Ring
16
+ ended?: { id: string }
17
+ }
18
+
19
+ /** A number an account holds, as its provider keeps its texting. */
20
+ export type Held = {
21
+ /** in E.164 form */
22
+ number: string
23
+ /** whether it sends and receives texts */
24
+ sms: boolean
25
+ /** what the account calls it, as the person named it there */
26
+ label?: string
27
+ /** the URL its texts are sent to, when its callback is on */
28
+ callback?: string
29
+ }
30
+
31
+ /** A person's own account at a provider: a {@link Sender}, the numbers it
32
+ * holds, and `point`, which sends a number's texts to a URL, or to none when
33
+ * `url` is absent, and leaves every other way they reach the person as it
34
+ * was. If `before` is given, change only a callback still at that URL. */
35
+ export type Account = Sender & {
36
+ lines: () => Promise<Held[]>
37
+ point: (number: string, url?: string, before?: string) => Promise<void>
38
+ }
39
+
40
+ /** A single attempt at each carrier request, within one shared deadline. */
41
+ export type Attempt = { by: number }
42
+
43
+ /** How a person connects a number of their own through a provider: their
44
+ * account, and the callback its texts reach a host by. */
45
+ export type Own = {
46
+ /** the field of the person's connection each setting is read from */
47
+ fields: Partial<Record<keyof Transport, string>>
48
+ /** their account, opened with those settings and the methods its
49
+ * integration lists, the only ones it asks for: it reads, texts and
50
+ * points, and has no way to give a number back or reroute its calls */
51
+ account: (options: Transport, attempt?: Attempt) => Account
52
+ /** the query a callback URL asks the provider to fill in, appended to
53
+ * the host's own address */
54
+ callback: string
55
+ /** what a callback said, from its query, once the host has found its own
56
+ * secret in the URL; null when it names no text */
57
+ called: (query: URLSearchParams, at?: string) => Arrival | null
58
+ /** what a person is told, in the provider's words, when their settings
59
+ * open no account and when none of its numbers texts */
60
+ said: { unopened: string; untexting: string }
61
+ }
62
+
63
+ export type Provider = {
64
+ needs?: (keyof Transport)[]
65
+ sender: (options: Transport) => Sender
66
+ heard?: (event: unknown) => Heard
67
+ scheme?: Scheme
68
+ /** a provider that takes calls: its commands, and its audio stream */
69
+ caller?: (options: Transport) => Caller
70
+ line?: Line
71
+ /** a provider a person connects their own number through */
72
+ own?: Own
73
+ /** a provider that sells numbers: what it has on offer, buying and
74
+ * giving one back, and their toll-free verification (./numbers.ts) */
75
+ numbers?: (options: Transport) => Numbers
76
+ }
77
+ /** Whether a provider takes webhooks: it says how they are signed and how to
78
+ * read one. */
79
+ export let listens = (transport?: Provider): transport is Provider & {
80
+ scheme: Scheme
81
+ heard: (event: unknown) => Heard
82
+ } => !!transport?.scheme && !!transport.heard
83
+
84
+ /** A provider's webhook, read once its signature checks out under `key`.
85
+ * Otherwise it is refused with why; `ours` marks a refusal that can mean the
86
+ * key is wrong, which the door reports. */
87
+ export let verified = async (
88
+ transport: Provider,
89
+ key: string,
90
+ request: Request,
91
+ ): Promise<{ heard: Heard } | { refused: string; ours: boolean }> => {
92
+ if (!listens(transport)) throw new Error('This provider takes no webhooks')
93
+ let body = await request.text()
94
+ let why = await refusal(transport.scheme, key, body, request.headers)
95
+ return why
96
+ ? { refused: why, ours: ours(why) }
97
+ : { heard: transport.heard(JSON.parse(body)) }
98
+ }
99
+
100
+ /** A configured provider, with a texter's outbound provenance attached. */
101
+ export let sender = (options: Transport, transport: Provider): Sender => {
102
+ let built = transport.sender(options)
103
+ // A number the options name is the number it sends from; otherwise the
104
+ // provider says, where it can.
105
+ let from = options.number
106
+ let own = from ? () => Promise.resolve(from) : built.from
107
+ return {
108
+ ...(own ? { from: own } : {}),
109
+ send: async (text) => {
110
+ let by = text.from ?? from
111
+ let receipt = await built.send({ ...text, ...(by ? { from: by } : {}) })
112
+ return {
113
+ ...receipt,
114
+ via: options.via,
115
+ ...(receipt.from || by ? { from: receipt.from ?? by } : {}),
116
+ }
117
+ },
118
+ }
119
+ }