@verft/sdk 0.0.0-stage → 1.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +22 -0
- package/README.md +14 -2
- package/dist/activity.d.ts +12 -0
- package/dist/activity.js +59 -0
- package/dist/connection.d.ts +135 -0
- package/dist/connection.js +1032 -0
- package/dist/drafts.d.ts +13 -0
- package/dist/drafts.js +21 -0
- package/dist/encoding.d.ts +112 -0
- package/dist/encoding.js +428 -0
- package/dist/files.d.ts +31 -0
- package/dist/files.js +56 -0
- package/dist/functions.d.ts +26 -0
- package/dist/functions.js +15 -0
- package/dist/index.d.ts +15 -0
- package/dist/index.js +8 -0
- package/dist/landing.d.ts +25 -0
- package/dist/landing.js +19 -0
- package/dist/platform.d.ts +70 -0
- package/dist/platform.js +11 -0
- package/dist/protocol.d.ts +1198 -0
- package/dist/protocol.js +334 -0
- package/dist/react-native.d.ts +30 -0
- package/dist/react-native.js +34 -0
- package/dist/react.d.ts +23 -0
- package/dist/react.js +43 -0
- package/dist/readable.d.ts +14 -0
- package/dist/readable.js +31 -0
- package/dist/storage.d.ts +6 -0
- package/dist/storage.js +8 -0
- package/dist/subscriptions.d.ts +70 -0
- package/dist/subscriptions.js +168 -0
- package/dist/svelte.d.ts +26 -0
- package/dist/svelte.js +73 -0
- package/dist/tables.d.ts +17 -0
- package/dist/tables.js +18 -0
- package/dist/vue.d.ts +20 -0
- package/dist/vue.js +60 -0
- package/package.json +72 -4
|
@@ -0,0 +1,1032 @@
|
|
|
1
|
+
import { decode, encode } from "./encoding.js";
|
|
2
|
+
import { encodeArguments } from "./functions.js";
|
|
3
|
+
import { landed } from "./landing.js";
|
|
4
|
+
import { browserAuthenticator, platform } from "./platform.js";
|
|
5
|
+
import { PROTOCOL, clientMessage, serverMessage, } from "./protocol.js";
|
|
6
|
+
import { Watched } from "./readable.js";
|
|
7
|
+
import { memoryStorage } from "./storage.js";
|
|
8
|
+
import { Standing, keyOfSubscription, moduleError, pending, replies, returned, revisions, rows, wire } from "./subscriptions.js";
|
|
9
|
+
export const CALL_TIME_LIMIT = 30000;
|
|
10
|
+
export const EMAIL_TIME_LIMIT = 90000;
|
|
11
|
+
export const PROVIDER_TIME_LIMIT = 60000;
|
|
12
|
+
export const WELCOME_TIME_LIMIT = 45000;
|
|
13
|
+
export const CONNECT_TIME_LIMIT = 30000;
|
|
14
|
+
export const LONGEST_TIME_LIMIT = 2 ** 31 - 1;
|
|
15
|
+
function timeLimit(option, value, otherwise) {
|
|
16
|
+
if (value === undefined)
|
|
17
|
+
return otherwise;
|
|
18
|
+
if (typeof value === "number" && value >= 1 && value <= LONGEST_TIME_LIMIT)
|
|
19
|
+
return value;
|
|
20
|
+
throw new TypeError(`${option} must be a number of milliseconds from 1 to ${LONGEST_TIME_LIMIT}, not ${String(value)}`);
|
|
21
|
+
}
|
|
22
|
+
const ENVIRONMENT_ANSWERS = new Set(["Connected", "ActionReply", "QueryReply", "SubscribeRefused", "Update", "Ended"]);
|
|
23
|
+
const EMAILED = new Set(["SignUp", "RequestSignInLink", "RequestSignInCode", "RequestPasswordReset"]);
|
|
24
|
+
export const MANAGED_CLOUD = "verft.app";
|
|
25
|
+
function address(options) {
|
|
26
|
+
if (options.server !== undefined)
|
|
27
|
+
return options.server;
|
|
28
|
+
const { environment } = options;
|
|
29
|
+
if (!/^[a-z]([a-z0-9-]{0,28}[a-z0-9])?$/.test(environment) || environment.includes("--")) {
|
|
30
|
+
throw new TypeError(`the Environment ID "${environment}" is not one the Managed cloud issues`);
|
|
31
|
+
}
|
|
32
|
+
return `https://${environment}.${MANAGED_CLOUD}`;
|
|
33
|
+
}
|
|
34
|
+
const BASE64URL = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
|
|
35
|
+
function unbase64url(text) {
|
|
36
|
+
const digits = text.replace(/=+$/, "").replace(/\+/g, "-").replace(/\//g, "_");
|
|
37
|
+
const bytes = [];
|
|
38
|
+
let [held, bits] = [0, 0];
|
|
39
|
+
for (const digit of digits) {
|
|
40
|
+
const value = BASE64URL.indexOf(digit);
|
|
41
|
+
if (value < 0)
|
|
42
|
+
return new Uint8Array();
|
|
43
|
+
[held, bits] = [((held << 6) | value) & 0xffff, bits + 6];
|
|
44
|
+
if (bits >= 8) {
|
|
45
|
+
bits -= 8;
|
|
46
|
+
bytes.push((held >> bits) & 0xff);
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
return new Uint8Array(bytes);
|
|
50
|
+
}
|
|
51
|
+
function wireDevice(device) {
|
|
52
|
+
switch (device.service) {
|
|
53
|
+
case "apns":
|
|
54
|
+
return { tag: "Apns", value: { token: device.token, sandbox: device.sandbox ?? false } };
|
|
55
|
+
case "fcm":
|
|
56
|
+
return { tag: "Fcm", value: { token: device.token } };
|
|
57
|
+
case "webPush": {
|
|
58
|
+
const { subscription } = device;
|
|
59
|
+
const { endpoint, keys } = "toJSON" in subscription && typeof subscription.toJSON === "function" ? subscription.toJSON() : subscription;
|
|
60
|
+
return { tag: "WebPush", value: { endpoint, p256dh: unbase64url(keys?.p256dh ?? ""), auth: unbase64url(keys?.auth ?? "") } };
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
export const ACTIVITY_PAGE = 25;
|
|
65
|
+
export function authenticatorUri(secret, account, issuer) {
|
|
66
|
+
const [named, by] = [encodeURIComponent(account), encodeURIComponent(issuer)];
|
|
67
|
+
return `otpauth://totp/${by}:${named}?secret=${secret}&issuer=${by}`;
|
|
68
|
+
}
|
|
69
|
+
export class CallError extends Error {
|
|
70
|
+
constructor(failure) {
|
|
71
|
+
super(`the call failed: ${failure.tag}`);
|
|
72
|
+
this.name = "CallError";
|
|
73
|
+
this.failure = failure;
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
export class IdentityError extends Error {
|
|
77
|
+
constructor(failure) {
|
|
78
|
+
super(`the identity operation was refused: ${failure.tag}`);
|
|
79
|
+
this.name = "IdentityError";
|
|
80
|
+
this.failure = failure;
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
class Link {
|
|
84
|
+
constructor(options) {
|
|
85
|
+
this.status = new Watched({ state: "connecting" });
|
|
86
|
+
this.failedAttempts = new Watched(0);
|
|
87
|
+
this.caller = new Watched(null);
|
|
88
|
+
this.landing = new Watched({ state: "none" });
|
|
89
|
+
this.socket = null;
|
|
90
|
+
this.greeted = false;
|
|
91
|
+
this.session = undefined;
|
|
92
|
+
this.step = null;
|
|
93
|
+
this.connected = false;
|
|
94
|
+
this.held = null;
|
|
95
|
+
this.position = null;
|
|
96
|
+
this.ephemeral = null;
|
|
97
|
+
this.attempt = 0;
|
|
98
|
+
this.attempting = undefined;
|
|
99
|
+
this.reopening = undefined;
|
|
100
|
+
this.heartbeat = 0;
|
|
101
|
+
this.heardAt = 0;
|
|
102
|
+
this.listening = undefined;
|
|
103
|
+
this.answers = 0;
|
|
104
|
+
this.evidence = new Set();
|
|
105
|
+
this.nextId = 0n;
|
|
106
|
+
this.calls = new Map();
|
|
107
|
+
this.queries = new Map();
|
|
108
|
+
this.identities = new Map();
|
|
109
|
+
this.subscriptions = new Map();
|
|
110
|
+
this.edits = new Map();
|
|
111
|
+
this.shares = new Map();
|
|
112
|
+
this.callTimeLimit = timeLimit("callTimeLimit", options.callTimeLimit, CALL_TIME_LIMIT);
|
|
113
|
+
this.emailTimeLimit = timeLimit("emailTimeLimit", options.emailTimeLimit, EMAIL_TIME_LIMIT);
|
|
114
|
+
this.providerTimeLimit = timeLimit("providerTimeLimit", options.providerTimeLimit, PROVIDER_TIME_LIMIT);
|
|
115
|
+
this.welcomeTimeLimit = timeLimit("welcomeTimeLimit", options.welcomeTimeLimit, WELCOME_TIME_LIMIT);
|
|
116
|
+
this.connectTimeLimit = timeLimit("connectTimeLimit", options.connectTimeLimit, CONNECT_TIME_LIMIT);
|
|
117
|
+
this.url = `${address(options).replace(/^http/, "ws").replace(/\/+$/, "")}/_verft/connection`;
|
|
118
|
+
this.storage = options.storage ?? platform.localStorage ?? memoryStorage();
|
|
119
|
+
this.authenticator = options.authenticator ?? browserAuthenticator();
|
|
120
|
+
this.relyingParty = options.relyingParty ?? platform.location?.hostname ?? "";
|
|
121
|
+
this.sessionKey = `verft:${options.environment}:session`;
|
|
122
|
+
this.pendingKey = `verft:${options.environment}:pending`;
|
|
123
|
+
this.bindingKey = `verft:${options.environment}:binding`;
|
|
124
|
+
this.consentBindingKey = `verft:${options.environment}:consent-binding`;
|
|
125
|
+
this.loaded = this.load();
|
|
126
|
+
this.open();
|
|
127
|
+
const href = platform.location?.href;
|
|
128
|
+
const arrived = href === undefined ? null : landed(href);
|
|
129
|
+
if (arrived === null)
|
|
130
|
+
return;
|
|
131
|
+
platform.history?.replaceState(platform.history.state, "", arrived.url);
|
|
132
|
+
void this.redeemed(arrived);
|
|
133
|
+
}
|
|
134
|
+
redeem(url) {
|
|
135
|
+
const arrived = landed(url);
|
|
136
|
+
if (arrived !== null)
|
|
137
|
+
void this.redeemed(arrived);
|
|
138
|
+
return arrived !== null;
|
|
139
|
+
}
|
|
140
|
+
wake() {
|
|
141
|
+
if (this.socket !== null || this.stopped())
|
|
142
|
+
return;
|
|
143
|
+
platform.clearTimeout(this.reopening);
|
|
144
|
+
this.attempt = 0;
|
|
145
|
+
this.open();
|
|
146
|
+
}
|
|
147
|
+
reconnect() {
|
|
148
|
+
if (this.socket !== null)
|
|
149
|
+
this.abandon(this.socket);
|
|
150
|
+
this.wake();
|
|
151
|
+
}
|
|
152
|
+
action(action, args, optimistic, options) {
|
|
153
|
+
const limit = timeLimit("timeLimit", options?.timeLimit, this.callTimeLimit);
|
|
154
|
+
const call = this.id();
|
|
155
|
+
const message = { tag: "Action", value: { call, name: action.name, arguments: encodeArguments(action, args) } };
|
|
156
|
+
return this.call(this.calls, call, message, action, limit, optimistic && revisions(optimistic));
|
|
157
|
+
}
|
|
158
|
+
query(query, args, options) {
|
|
159
|
+
const limit = timeLimit("timeLimit", options?.timeLimit, this.callTimeLimit);
|
|
160
|
+
const request = this.id();
|
|
161
|
+
const message = { tag: "Query", value: { request, name: query.name, arguments: encodeArguments(query, args) } };
|
|
162
|
+
return this.call(this.queries, request, message, query, limit);
|
|
163
|
+
}
|
|
164
|
+
subscribe(target, args) {
|
|
165
|
+
const id = this.id();
|
|
166
|
+
const unsubscribe = () => this.unsubscribe(id);
|
|
167
|
+
const copy = "sql" in target ? rows(target.row) : replies(target);
|
|
168
|
+
const standing = new Standing(wire(target, args), copy, unsubscribe, this.edits);
|
|
169
|
+
this.subscriptions.set(id, standing);
|
|
170
|
+
if (this.connected)
|
|
171
|
+
this.hold(id, standing);
|
|
172
|
+
return standing;
|
|
173
|
+
}
|
|
174
|
+
shared(target, args) {
|
|
175
|
+
const key = keyOfSubscription(wire(target, args));
|
|
176
|
+
const onChange = (listener) => {
|
|
177
|
+
const share = this.shares.get(key) ?? { subscription: this.subscribe(target, args), holders: 0 };
|
|
178
|
+
this.shares.set(key, share);
|
|
179
|
+
share.holders++;
|
|
180
|
+
const stop = share.subscription.onChange(listener);
|
|
181
|
+
return () => {
|
|
182
|
+
stop();
|
|
183
|
+
if (--share.holders > 0)
|
|
184
|
+
return;
|
|
185
|
+
this.shares.delete(key);
|
|
186
|
+
share.subscription.unsubscribe();
|
|
187
|
+
};
|
|
188
|
+
};
|
|
189
|
+
return { key, get: () => this.shares.get(key)?.subscription.get() ?? pending, onChange };
|
|
190
|
+
}
|
|
191
|
+
startAnonymous() {
|
|
192
|
+
return this.signingIn({ tag: "StartAnonymous" });
|
|
193
|
+
}
|
|
194
|
+
async signUp(email, password) {
|
|
195
|
+
const outcome = await this.identity({ tag: "SignUp", value: { email, password, anonymous: this.anonymous() } });
|
|
196
|
+
if (outcome.tag === "SignedUp")
|
|
197
|
+
await this.storage.setItem(this.pendingKey, outcome.value.pending);
|
|
198
|
+
}
|
|
199
|
+
verifyEmail(emailed) {
|
|
200
|
+
return this.verifying(emailed);
|
|
201
|
+
}
|
|
202
|
+
signIn(email, password) {
|
|
203
|
+
return this.signingIn({ tag: "SignIn", value: { email, password } });
|
|
204
|
+
}
|
|
205
|
+
async requestSignInLink(email, redirectTo) {
|
|
206
|
+
const value = { email, anonymous: this.anonymous(), redirect_to: redirectTo ?? null };
|
|
207
|
+
await this.identity({ tag: "RequestSignInLink", value });
|
|
208
|
+
}
|
|
209
|
+
signInWithLink(emailed) {
|
|
210
|
+
return this.signingIn({ tag: "SignInWithLink", value: { emailed } });
|
|
211
|
+
}
|
|
212
|
+
async requestSignInCode(email) {
|
|
213
|
+
await this.identity({ tag: "RequestSignInCode", value: { email, anonymous: this.anonymous() } });
|
|
214
|
+
}
|
|
215
|
+
signInWithCode(email, code) {
|
|
216
|
+
return this.signingIn({ tag: "SignInWithCode", value: { email, code } });
|
|
217
|
+
}
|
|
218
|
+
async requestPasswordReset(email) {
|
|
219
|
+
await this.identity({ tag: "RequestPasswordReset", value: { email } });
|
|
220
|
+
}
|
|
221
|
+
async resetPassword(emailed, password) {
|
|
222
|
+
await this.identity({ tag: "ResetPassword", value: { emailed, password } });
|
|
223
|
+
}
|
|
224
|
+
acceptInvitation(emailed) {
|
|
225
|
+
return this.signingIn({ tag: "AcceptInvitation", value: { emailed, anonymous: this.anonymous() } });
|
|
226
|
+
}
|
|
227
|
+
async startProviderSignIn(connection, redirectTo) {
|
|
228
|
+
const outcome = await this.identity({ tag: "StartProviderSignIn", value: { connection, redirect_to: redirectTo } });
|
|
229
|
+
if (outcome.tag !== "ProviderSignInStarted")
|
|
230
|
+
throw new IdentityError({ tag: "Unavailable", value: `unexpected ${outcome.tag}` });
|
|
231
|
+
await this.storage.setItem(this.bindingKey, outcome.value.binding);
|
|
232
|
+
return outcome.value.url;
|
|
233
|
+
}
|
|
234
|
+
async finishProviderSignIn(result) {
|
|
235
|
+
await this.loaded;
|
|
236
|
+
const binding = (await this.storage.getItem(this.bindingKey)) ?? "";
|
|
237
|
+
const caller = await this.signingIn({ tag: "FinishProviderSignIn", value: { result, binding, anonymous: this.anonymous() } });
|
|
238
|
+
await this.storage.removeItem(this.bindingKey);
|
|
239
|
+
return caller;
|
|
240
|
+
}
|
|
241
|
+
async startDirectoryConsent(connection, redirectTo) {
|
|
242
|
+
const outcome = await this.identity({ tag: "StartDirectoryConsent", value: { connection, redirect_to: redirectTo } });
|
|
243
|
+
if (outcome.tag !== "ProviderSignInStarted")
|
|
244
|
+
throw new IdentityError({ tag: "Unavailable", value: `unexpected ${outcome.tag}` });
|
|
245
|
+
await this.storage.setItem(this.consentBindingKey, outcome.value.binding);
|
|
246
|
+
return outcome.value.url;
|
|
247
|
+
}
|
|
248
|
+
async finishDirectoryConsent(consent) {
|
|
249
|
+
await this.loaded;
|
|
250
|
+
const binding = (await this.storage.getItem(this.consentBindingKey)) ?? "";
|
|
251
|
+
const outcome = await this.identity({ tag: "FinishDirectoryConsent", value: { result: consent, binding } });
|
|
252
|
+
if (outcome.tag !== "DirectoryConsented")
|
|
253
|
+
throw new IdentityError({ tag: "Unavailable", value: `unexpected ${outcome.tag}` });
|
|
254
|
+
await this.storage.removeItem(this.consentBindingKey);
|
|
255
|
+
return outcome.value.directory;
|
|
256
|
+
}
|
|
257
|
+
async passSecondStep(code) {
|
|
258
|
+
const caller = await this.signingIn({ tag: "PassSecondStep", value: { step: this.step ?? "", code } });
|
|
259
|
+
this.step = null;
|
|
260
|
+
return caller;
|
|
261
|
+
}
|
|
262
|
+
async startEnrolment() {
|
|
263
|
+
const outcome = await this.identity({ tag: "StartEnrolment", value: { by: await this.enrolling() } });
|
|
264
|
+
if (outcome.tag !== "EnrolmentStarted")
|
|
265
|
+
throw new IdentityError({ tag: "Unavailable", value: `the server answered ${outcome.tag}` });
|
|
266
|
+
return outcome.value.secret;
|
|
267
|
+
}
|
|
268
|
+
async finishEnrolment(code) {
|
|
269
|
+
const outcome = await this.identity({ tag: "FinishEnrolment", value: { by: await this.enrolling(), code } });
|
|
270
|
+
if (outcome.tag !== "Enrolled")
|
|
271
|
+
throw new IdentityError({ tag: "Unavailable", value: `the server answered ${outcome.tag}` });
|
|
272
|
+
const { caller, token, recovery_codes } = outcome.value;
|
|
273
|
+
if (this.session?.token !== token)
|
|
274
|
+
await this.signedIn(caller, token);
|
|
275
|
+
this.step = null;
|
|
276
|
+
return recovery_codes;
|
|
277
|
+
}
|
|
278
|
+
async startReplacement() {
|
|
279
|
+
const outcome = await this.identity({ tag: "StartReplacement", value: { token: await this.token() } });
|
|
280
|
+
if (outcome.tag !== "EnrolmentStarted")
|
|
281
|
+
throw new IdentityError({ tag: "Unavailable", value: `the server answered ${outcome.tag}` });
|
|
282
|
+
return outcome.value.secret;
|
|
283
|
+
}
|
|
284
|
+
async finishReplacement(code, newCode) {
|
|
285
|
+
await this.identity({ tag: "FinishReplacement", value: { token: await this.token(), code, new_code: newCode } });
|
|
286
|
+
}
|
|
287
|
+
async removeSecondFactor(code) {
|
|
288
|
+
await this.identity({ tag: "RemoveSecondFactor", value: { token: await this.token(), code } });
|
|
289
|
+
}
|
|
290
|
+
async reissueRecoveryCodes() {
|
|
291
|
+
const outcome = await this.identity({ tag: "ReissueRecoveryCodes", value: { token: await this.token() } });
|
|
292
|
+
if (outcome.tag !== "RecoveryCodesReissued")
|
|
293
|
+
throw new IdentityError({ tag: "Unavailable", value: `the server answered ${outcome.tag}` });
|
|
294
|
+
return outcome.value.recovery_codes;
|
|
295
|
+
}
|
|
296
|
+
async registerPasskey(account, name) {
|
|
297
|
+
await this.loaded;
|
|
298
|
+
const session = this.session?.token ?? null;
|
|
299
|
+
const starting = { session, relying_party: this.relyingParty, account, name };
|
|
300
|
+
const finishing = await this.ceremony({ tag: "StartPasskeyRegistration", value: starting }, "create");
|
|
301
|
+
const outcome = await this.identity({ tag: "FinishPasskeyRegistration", value: finishing });
|
|
302
|
+
if (outcome.tag === "SignedIn")
|
|
303
|
+
await this.signedIn(outcome.value.caller, outcome.value.token);
|
|
304
|
+
}
|
|
305
|
+
async signInWithPasskey() {
|
|
306
|
+
const starting = { relying_party: this.relyingParty };
|
|
307
|
+
const finishing = await this.ceremony({ tag: "StartPasskeySignIn", value: starting }, "get");
|
|
308
|
+
return this.signingIn({ tag: "FinishPasskeySignIn", value: finishing });
|
|
309
|
+
}
|
|
310
|
+
async passkeys() {
|
|
311
|
+
const outcome = await this.identity({ tag: "Passkeys", value: { token: await this.token() } });
|
|
312
|
+
if (outcome.tag !== "PasskeysListed")
|
|
313
|
+
throw new IdentityError({ tag: "Unavailable", value: `the server answered ${outcome.tag}` });
|
|
314
|
+
return outcome.value.passkeys;
|
|
315
|
+
}
|
|
316
|
+
async renamePasskey(id, name) {
|
|
317
|
+
await this.identity({ tag: "RenamePasskey", value: { token: await this.token(), id, name } });
|
|
318
|
+
}
|
|
319
|
+
async removePasskey(id) {
|
|
320
|
+
await this.identity({ tag: "RemovePasskey", value: { token: await this.token(), id } });
|
|
321
|
+
}
|
|
322
|
+
async accountActivity({ after, limit } = {}) {
|
|
323
|
+
const value = { token: await this.token(), after: after ?? null, limit: limit ?? ACTIVITY_PAGE };
|
|
324
|
+
const outcome = await this.identity({ tag: "AccountActivity", value });
|
|
325
|
+
if (outcome.tag !== "AccountActivityRead")
|
|
326
|
+
throw new IdentityError({ tag: "Unavailable", value: `the server answered ${outcome.tag}` });
|
|
327
|
+
return outcome.value;
|
|
328
|
+
}
|
|
329
|
+
async registerDevice(device) {
|
|
330
|
+
const value = { token: await this.token(), device: wireDevice(device) };
|
|
331
|
+
const outcome = await this.identity({ tag: "RegisterDevice", value });
|
|
332
|
+
if (outcome.tag !== "DeviceRegistered")
|
|
333
|
+
throw new IdentityError({ tag: "Unavailable", value: `the server answered ${outcome.tag}` });
|
|
334
|
+
return outcome.value.device;
|
|
335
|
+
}
|
|
336
|
+
async unregisterDevice() {
|
|
337
|
+
await this.identity({ tag: "UnregisterDevice", value: { token: await this.token() } });
|
|
338
|
+
}
|
|
339
|
+
sessionToken() {
|
|
340
|
+
return this.session?.token ?? null;
|
|
341
|
+
}
|
|
342
|
+
async issueSessionCode(bindingHash) {
|
|
343
|
+
const outcome = await this.identity({ tag: "IssueSessionCode", value: { token: await this.token(), binding_hash: bindingHash } });
|
|
344
|
+
if (outcome.tag !== "SessionCodeIssued")
|
|
345
|
+
throw new IdentityError({ tag: "Unavailable", value: `the server answered ${outcome.tag}` });
|
|
346
|
+
if (this.connected)
|
|
347
|
+
this.send({ tag: "Close" });
|
|
348
|
+
await this.unauthenticated();
|
|
349
|
+
return outcome.value.code;
|
|
350
|
+
}
|
|
351
|
+
signOut() {
|
|
352
|
+
return this.signingOut((token) => ({ tag: "SignOut", value: { token } }));
|
|
353
|
+
}
|
|
354
|
+
signOutEverywhere() {
|
|
355
|
+
return this.signingOut((token) => ({ tag: "SignOutEverywhere", value: { token } }));
|
|
356
|
+
}
|
|
357
|
+
close() {
|
|
358
|
+
if (this.status.get().state === "closed")
|
|
359
|
+
return;
|
|
360
|
+
if (this.connected)
|
|
361
|
+
this.send({ tag: "Close" });
|
|
362
|
+
this.stop({ state: "closed" });
|
|
363
|
+
}
|
|
364
|
+
stop(status) {
|
|
365
|
+
this.connected = false;
|
|
366
|
+
platform.clearTimeout(this.reopening);
|
|
367
|
+
platform.clearTimeout(this.listening);
|
|
368
|
+
this.attempting?.();
|
|
369
|
+
this.forgetEvidence();
|
|
370
|
+
const socket = this.socket;
|
|
371
|
+
this.socket = null;
|
|
372
|
+
socket?.close();
|
|
373
|
+
this.change(status);
|
|
374
|
+
this.failCalls({ tag: "NotConnected" });
|
|
375
|
+
for (const standing of this.subscriptions.values())
|
|
376
|
+
standing.stopWaiting();
|
|
377
|
+
for (const [id, request] of this.identities) {
|
|
378
|
+
this.identities.delete(id);
|
|
379
|
+
request.fail({ tag: "Unavailable", value: stoppedReason });
|
|
380
|
+
}
|
|
381
|
+
}
|
|
382
|
+
stopped() {
|
|
383
|
+
const { state } = this.status.get();
|
|
384
|
+
return state === "closed" || state === "unsupportedProtocol";
|
|
385
|
+
}
|
|
386
|
+
id() {
|
|
387
|
+
return this.nextId++;
|
|
388
|
+
}
|
|
389
|
+
anonymous() {
|
|
390
|
+
return this.session?.anonymous ? this.session.token : null;
|
|
391
|
+
}
|
|
392
|
+
call(pending, id, message, fn, limit, optimistic) {
|
|
393
|
+
return new Promise((resolve, reject) => {
|
|
394
|
+
if (!this.waitsForConnection())
|
|
395
|
+
return reject(new CallError({ tag: "NotConnected" }));
|
|
396
|
+
const due = Date.now() + limit;
|
|
397
|
+
const expiring = this.deadline(due, (at) => this.ranOut(pending, id, at));
|
|
398
|
+
const fail = (failure) => {
|
|
399
|
+
expiring();
|
|
400
|
+
this.shown(this.withdrawn([id]));
|
|
401
|
+
reject(new CallError(failure));
|
|
402
|
+
};
|
|
403
|
+
const settle = (outcome) => {
|
|
404
|
+
expiring();
|
|
405
|
+
this.shown(this.withdrawn([id]));
|
|
406
|
+
try {
|
|
407
|
+
if (outcome.tag === "Returned")
|
|
408
|
+
return resolve(returned(fn, outcome.value.value));
|
|
409
|
+
const error = moduleError(fn, outcome.value);
|
|
410
|
+
if (error === undefined)
|
|
411
|
+
fail(outcome.value);
|
|
412
|
+
else
|
|
413
|
+
resolve(error);
|
|
414
|
+
}
|
|
415
|
+
catch (error) {
|
|
416
|
+
reject(error);
|
|
417
|
+
}
|
|
418
|
+
};
|
|
419
|
+
const call = { message, settle, fail, due, sent: false, sentAt: 0, answers: 0, refused: 0 };
|
|
420
|
+
pending.set(id, call);
|
|
421
|
+
if (optimistic) {
|
|
422
|
+
this.edits.set(id, optimistic);
|
|
423
|
+
this.shown(new Set(optimistic.map(({ key }) => key)));
|
|
424
|
+
}
|
|
425
|
+
if (this.connected)
|
|
426
|
+
this.dispatch(call);
|
|
427
|
+
});
|
|
428
|
+
}
|
|
429
|
+
ranOut(pending, id, at) {
|
|
430
|
+
const call = pending.get(id);
|
|
431
|
+
const socket = this.socket;
|
|
432
|
+
if (call && socket !== null && call.sent && this.answers === call.answers && call.due >= call.sentAt + this.callTimeLimit)
|
|
433
|
+
return this.stuck(socket, at);
|
|
434
|
+
this.expired(pending, id);
|
|
435
|
+
}
|
|
436
|
+
expired(pending, id) {
|
|
437
|
+
const call = pending.get(id);
|
|
438
|
+
if (!call)
|
|
439
|
+
return;
|
|
440
|
+
pending.delete(id);
|
|
441
|
+
call.fail(call.sent ? { tag: "Indeterminate" } : (call.overloaded ?? { tag: "NotConnected" }));
|
|
442
|
+
}
|
|
443
|
+
waitsForConnection() {
|
|
444
|
+
const { state } = this.status.get();
|
|
445
|
+
return state === "connecting" || state === "connected" || state === "reconnecting";
|
|
446
|
+
}
|
|
447
|
+
dispatch(call) {
|
|
448
|
+
call.sent = true;
|
|
449
|
+
call.sentAt = Date.now();
|
|
450
|
+
call.answers = this.answers;
|
|
451
|
+
call.firstSent ?? (call.firstSent = call.sentAt);
|
|
452
|
+
this.send(call.message);
|
|
453
|
+
if (call.due < call.sentAt + this.callTimeLimit)
|
|
454
|
+
this.evidenceAt(call.sentAt + this.callTimeLimit);
|
|
455
|
+
}
|
|
456
|
+
hold(id, standing) {
|
|
457
|
+
const answers = this.answers;
|
|
458
|
+
standing.sent = true;
|
|
459
|
+
this.send({ tag: "Subscribe", value: { subscription: id, to: standing.to } });
|
|
460
|
+
standing.awaitFirst(Date.now() + this.callTimeLimit, (due) => this.deadline(due, (at) => {
|
|
461
|
+
if (this.subscriptions.get(id) !== standing || standing.delivered)
|
|
462
|
+
return;
|
|
463
|
+
if (this.socket !== null && this.answers === answers)
|
|
464
|
+
return this.stuck(this.socket, at);
|
|
465
|
+
standing.unanswered();
|
|
466
|
+
if (!this.connected)
|
|
467
|
+
return;
|
|
468
|
+
this.send({ tag: "Unsubscribe", value: { subscription: id } });
|
|
469
|
+
this.hold(id, standing);
|
|
470
|
+
}));
|
|
471
|
+
}
|
|
472
|
+
unsubscribe(id) {
|
|
473
|
+
this.subscriptions.get(id)?.stopWaiting();
|
|
474
|
+
if (!this.subscriptions.delete(id))
|
|
475
|
+
return;
|
|
476
|
+
if (this.connected)
|
|
477
|
+
this.send({ tag: "Unsubscribe", value: { subscription: id } });
|
|
478
|
+
}
|
|
479
|
+
identity(operation) {
|
|
480
|
+
return new Promise((resolve, reject) => {
|
|
481
|
+
if (this.stopped())
|
|
482
|
+
return reject(new IdentityError({ tag: "Unavailable", value: stoppedReason }));
|
|
483
|
+
const id = this.id();
|
|
484
|
+
const limit = EMAILED.has(operation.tag) ? this.emailTimeLimit : operation.tag === "FinishProviderSignIn" ? this.providerTimeLimit : this.callTimeLimit;
|
|
485
|
+
const expiring = this.deadline(Date.now() + limit, () => {
|
|
486
|
+
if (this.identities.get(id) !== request)
|
|
487
|
+
return;
|
|
488
|
+
this.identities.delete(id);
|
|
489
|
+
request.fail({ tag: "Unavailable", value: `the server did not answer within ${limit} ms` });
|
|
490
|
+
});
|
|
491
|
+
const settle = (outcome) => {
|
|
492
|
+
expiring();
|
|
493
|
+
if (outcome.tag !== "Refused")
|
|
494
|
+
return resolve(outcome);
|
|
495
|
+
const failure = outcome.value;
|
|
496
|
+
if (failure.tag === "SecondFactorNeeded" || failure.tag === "EnrolmentNeeded")
|
|
497
|
+
this.step = failure.value.step;
|
|
498
|
+
reject(new IdentityError(failure));
|
|
499
|
+
};
|
|
500
|
+
const fail = (failure) => {
|
|
501
|
+
expiring();
|
|
502
|
+
reject(new IdentityError(failure));
|
|
503
|
+
};
|
|
504
|
+
const request = { operation, settle, fail, limit, sent: false };
|
|
505
|
+
this.identities.set(id, request);
|
|
506
|
+
if (this.greeted)
|
|
507
|
+
this.ask(id, request);
|
|
508
|
+
});
|
|
509
|
+
}
|
|
510
|
+
ask(id, request) {
|
|
511
|
+
request.sent = true;
|
|
512
|
+
this.send({ tag: "Identity", value: { request: id, operation: request.operation } });
|
|
513
|
+
}
|
|
514
|
+
async verifying(emailed, link) {
|
|
515
|
+
const pending = await this.storage.getItem(this.pendingKey);
|
|
516
|
+
const caller = await this.signingIn({ tag: "VerifyEmail", value: { emailed, pending } }, link);
|
|
517
|
+
await this.storage.removeItem(this.pendingKey);
|
|
518
|
+
return caller;
|
|
519
|
+
}
|
|
520
|
+
async signingIn(operation, link) {
|
|
521
|
+
const outcome = await this.identity(operation);
|
|
522
|
+
if (outcome.tag !== "SignedIn")
|
|
523
|
+
throw new IdentityError({ tag: "Unavailable", value: `the server answered ${outcome.tag}` });
|
|
524
|
+
const { caller, token } = outcome.value;
|
|
525
|
+
return this.signedIn(caller, token, link);
|
|
526
|
+
}
|
|
527
|
+
async ceremony(start, step) {
|
|
528
|
+
const authenticator = this.authenticator;
|
|
529
|
+
if (authenticator === undefined)
|
|
530
|
+
throw new IdentityError({ tag: "Unavailable", value: "this platform has no passkeys; pass an authenticator to connect" });
|
|
531
|
+
const outcome = await this.identity(start);
|
|
532
|
+
if (outcome.tag !== "PasskeyCeremonyStarted")
|
|
533
|
+
throw new IdentityError({ tag: "Unavailable", value: `the server answered ${outcome.tag}` });
|
|
534
|
+
const { ceremony, options } = outcome.value;
|
|
535
|
+
return { ceremony, response: JSON.stringify(await authenticator[step](JSON.parse(options))) };
|
|
536
|
+
}
|
|
537
|
+
async token() {
|
|
538
|
+
await this.loaded;
|
|
539
|
+
return this.session?.token ?? "";
|
|
540
|
+
}
|
|
541
|
+
async enrolling() {
|
|
542
|
+
await this.loaded;
|
|
543
|
+
if (this.step !== null)
|
|
544
|
+
return { tag: "Required", value: { step: this.step } };
|
|
545
|
+
return { tag: "SignedIn", value: { token: this.session?.token ?? "" } };
|
|
546
|
+
}
|
|
547
|
+
async signedIn(caller, token, link) {
|
|
548
|
+
if (this.held && this.held.identity !== caller.identity) {
|
|
549
|
+
if (this.connected)
|
|
550
|
+
this.send({ tag: "Close" });
|
|
551
|
+
this.connected = false;
|
|
552
|
+
this.forget();
|
|
553
|
+
this.change({ state: "connecting" });
|
|
554
|
+
}
|
|
555
|
+
await this.keep({ token, anonymous: caller.kind.tag === "Anonymous" });
|
|
556
|
+
if (link !== undefined)
|
|
557
|
+
this.landing.set({ state: "signedIn", link, caller });
|
|
558
|
+
this.signedInAs(caller);
|
|
559
|
+
if (link !== undefined)
|
|
560
|
+
this.landing.notify();
|
|
561
|
+
this.ready();
|
|
562
|
+
return caller;
|
|
563
|
+
}
|
|
564
|
+
async signingOut(operation) {
|
|
565
|
+
if (this.session)
|
|
566
|
+
await this.identity(operation(this.session.token));
|
|
567
|
+
if (this.connected)
|
|
568
|
+
this.send({ tag: "Close" });
|
|
569
|
+
await this.unauthenticated();
|
|
570
|
+
}
|
|
571
|
+
async keep(session) {
|
|
572
|
+
this.session = session;
|
|
573
|
+
if (session === null)
|
|
574
|
+
await this.storage.removeItem(this.sessionKey);
|
|
575
|
+
else
|
|
576
|
+
await this.storage.setItem(this.sessionKey, JSON.stringify(session));
|
|
577
|
+
}
|
|
578
|
+
async load() {
|
|
579
|
+
let stored = null;
|
|
580
|
+
try {
|
|
581
|
+
stored = await this.storage.getItem(this.sessionKey);
|
|
582
|
+
}
|
|
583
|
+
catch { }
|
|
584
|
+
if (this.session !== undefined)
|
|
585
|
+
return;
|
|
586
|
+
this.session = parseSession(stored);
|
|
587
|
+
this.ready();
|
|
588
|
+
}
|
|
589
|
+
ready() {
|
|
590
|
+
if (!this.greeted || this.session === undefined)
|
|
591
|
+
return;
|
|
592
|
+
if (this.session === null)
|
|
593
|
+
this.signedOut();
|
|
594
|
+
else
|
|
595
|
+
this.connect();
|
|
596
|
+
}
|
|
597
|
+
signedOut() {
|
|
598
|
+
if (this.stopped())
|
|
599
|
+
return;
|
|
600
|
+
this.change({ state: "signedOut" });
|
|
601
|
+
this.failCalls({ tag: "NotConnected" });
|
|
602
|
+
}
|
|
603
|
+
failCalls(failure) {
|
|
604
|
+
for (const pending of [this.calls, this.queries]) {
|
|
605
|
+
for (const [id, call] of pending) {
|
|
606
|
+
pending.delete(id);
|
|
607
|
+
call.fail(failure);
|
|
608
|
+
}
|
|
609
|
+
}
|
|
610
|
+
}
|
|
611
|
+
connect() {
|
|
612
|
+
if (!this.session)
|
|
613
|
+
return;
|
|
614
|
+
if (!this.waitsForConnection())
|
|
615
|
+
this.change({ state: "connecting" });
|
|
616
|
+
const resume = this.held && {
|
|
617
|
+
connection: this.held.connection,
|
|
618
|
+
position: this.position,
|
|
619
|
+
ephemeral: this.ephemeral,
|
|
620
|
+
subscriptions: [...this.subscriptions].filter(([, standing]) => standing.delivered).map(([subscription, standing]) => ({ subscription, to: standing.to })),
|
|
621
|
+
};
|
|
622
|
+
for (const standing of this.subscriptions.values())
|
|
623
|
+
standing.sent = standing.delivered && resume !== null;
|
|
624
|
+
this.send({ tag: "Connect", value: { token: this.session.token, resume } });
|
|
625
|
+
this.limitAttempt(this.connectTimeLimit);
|
|
626
|
+
}
|
|
627
|
+
async redeemed({ link, emailed }) {
|
|
628
|
+
if (link === "passwordReset")
|
|
629
|
+
return this.land({ state: "newPassword", emailed });
|
|
630
|
+
this.land({ state: "redeeming", link });
|
|
631
|
+
try {
|
|
632
|
+
await this.loaded;
|
|
633
|
+
if (link === "verification")
|
|
634
|
+
await this.verifying(emailed, link);
|
|
635
|
+
else if (link === "signIn")
|
|
636
|
+
await this.signingIn({ tag: "SignInWithLink", value: { emailed } }, link);
|
|
637
|
+
else
|
|
638
|
+
await this.signingIn({ tag: "AcceptInvitation", value: { emailed, anonymous: this.anonymous() } }, link);
|
|
639
|
+
}
|
|
640
|
+
catch (error) {
|
|
641
|
+
this.land({ state: "refused", link, failure: error instanceof IdentityError ? error.failure : { tag: "Unavailable", value: String(error) } });
|
|
642
|
+
}
|
|
643
|
+
}
|
|
644
|
+
land(landing) {
|
|
645
|
+
this.landing.set(landing);
|
|
646
|
+
this.landing.notify();
|
|
647
|
+
}
|
|
648
|
+
signedInAs(caller) {
|
|
649
|
+
const current = this.caller.get();
|
|
650
|
+
if (current?.identity === caller?.identity && current?.kind.tag === caller?.kind.tag)
|
|
651
|
+
return;
|
|
652
|
+
this.caller.set(caller);
|
|
653
|
+
this.caller.notify();
|
|
654
|
+
}
|
|
655
|
+
change(status) {
|
|
656
|
+
if (status.state !== "connecting" && status.state !== "reconnecting")
|
|
657
|
+
this.attemptsFailed(0);
|
|
658
|
+
if (status.state === this.status.get().state && Object.keys(status).length === 1)
|
|
659
|
+
return;
|
|
660
|
+
this.status.set(status);
|
|
661
|
+
this.status.notify();
|
|
662
|
+
}
|
|
663
|
+
open() {
|
|
664
|
+
const socket = new platform.WebSocket(this.url);
|
|
665
|
+
socket.binaryType = "arraybuffer";
|
|
666
|
+
socket.onopen = () => socket.send(encode(clientMessage, { tag: "Hello", value: { protocol: PROTOCOL } }));
|
|
667
|
+
socket.onmessage = (event) => {
|
|
668
|
+
if (this.socket !== socket || !(event.data instanceof ArrayBuffer))
|
|
669
|
+
return;
|
|
670
|
+
this.heardAt = Date.now();
|
|
671
|
+
try {
|
|
672
|
+
this.received(new Uint8Array(event.data));
|
|
673
|
+
}
|
|
674
|
+
catch {
|
|
675
|
+
this.abandon(socket);
|
|
676
|
+
}
|
|
677
|
+
};
|
|
678
|
+
socket.onclose = () => this.dropped(socket);
|
|
679
|
+
socket.onerror = () => { };
|
|
680
|
+
this.socket = socket;
|
|
681
|
+
this.limitAttempt(this.welcomeTimeLimit);
|
|
682
|
+
}
|
|
683
|
+
limitAttempt(limit) {
|
|
684
|
+
const socket = this.socket;
|
|
685
|
+
this.attempting?.();
|
|
686
|
+
if (socket !== null)
|
|
687
|
+
this.attempting = this.deadline(Date.now() + limit, (at) => this.stuck(socket, at));
|
|
688
|
+
}
|
|
689
|
+
deadline(due, run) {
|
|
690
|
+
let timer;
|
|
691
|
+
const arm = (at, deferred) => {
|
|
692
|
+
timer = platform.setTimeout(() => {
|
|
693
|
+
if (!deferred && this.heartbeat > 0 && Date.now() > at + this.heartbeat)
|
|
694
|
+
return arm(Date.now() + this.heartbeat, true);
|
|
695
|
+
run(at);
|
|
696
|
+
}, Math.max(0, at - Date.now()));
|
|
697
|
+
};
|
|
698
|
+
arm(due, false);
|
|
699
|
+
return () => platform.clearTimeout(timer);
|
|
700
|
+
}
|
|
701
|
+
abandon(socket) {
|
|
702
|
+
if (this.socket !== socket)
|
|
703
|
+
return;
|
|
704
|
+
socket.close();
|
|
705
|
+
this.dropped(socket);
|
|
706
|
+
}
|
|
707
|
+
evidenceAt(at) {
|
|
708
|
+
const socket = this.socket;
|
|
709
|
+
const answers = this.answers;
|
|
710
|
+
const evident = this.deadline(at, (decided) => {
|
|
711
|
+
this.evidence.delete(evident);
|
|
712
|
+
if (socket !== null && this.answers === answers)
|
|
713
|
+
this.stuck(socket, decided);
|
|
714
|
+
});
|
|
715
|
+
this.evidence.add(evident);
|
|
716
|
+
}
|
|
717
|
+
forgetEvidence() {
|
|
718
|
+
for (const evident of this.evidence)
|
|
719
|
+
evident();
|
|
720
|
+
this.evidence.clear();
|
|
721
|
+
}
|
|
722
|
+
stuck(socket, at) {
|
|
723
|
+
if (this.socket !== socket)
|
|
724
|
+
return;
|
|
725
|
+
for (const pending of [this.calls, this.queries])
|
|
726
|
+
for (const [id, call] of pending)
|
|
727
|
+
if (call.due <= at)
|
|
728
|
+
this.expired(pending, id);
|
|
729
|
+
for (const standing of this.subscriptions.values())
|
|
730
|
+
if (standing.sent && !standing.delivered && standing.due <= at)
|
|
731
|
+
standing.unanswered();
|
|
732
|
+
this.abandon(socket);
|
|
733
|
+
}
|
|
734
|
+
attemptsFailed(count) {
|
|
735
|
+
if (this.failedAttempts.get() === count)
|
|
736
|
+
return;
|
|
737
|
+
this.failedAttempts.set(count);
|
|
738
|
+
this.failedAttempts.notify();
|
|
739
|
+
}
|
|
740
|
+
failedAttempt() {
|
|
741
|
+
const { state } = this.status.get();
|
|
742
|
+
if (state !== "connecting" && state !== "reconnecting")
|
|
743
|
+
return;
|
|
744
|
+
this.attemptsFailed(this.failedAttempts.get() + 1);
|
|
745
|
+
}
|
|
746
|
+
dropped(socket) {
|
|
747
|
+
if (this.socket !== socket)
|
|
748
|
+
return;
|
|
749
|
+
this.socket = null;
|
|
750
|
+
this.greeted = false;
|
|
751
|
+
platform.clearTimeout(this.listening);
|
|
752
|
+
this.attempting?.();
|
|
753
|
+
this.forgetEvidence();
|
|
754
|
+
const failed = !this.connected;
|
|
755
|
+
this.detached();
|
|
756
|
+
if (failed)
|
|
757
|
+
this.failedAttempt();
|
|
758
|
+
for (const [id, call] of this.calls) {
|
|
759
|
+
if (!call.sent)
|
|
760
|
+
continue;
|
|
761
|
+
this.calls.delete(id);
|
|
762
|
+
call.fail({ tag: "Indeterminate" });
|
|
763
|
+
}
|
|
764
|
+
for (const call of this.queries.values())
|
|
765
|
+
call.sent = false;
|
|
766
|
+
for (const [id, request] of this.identities) {
|
|
767
|
+
if (!request.sent)
|
|
768
|
+
continue;
|
|
769
|
+
this.identities.delete(id);
|
|
770
|
+
request.fail({ tag: "Unavailable", value: "the connection was lost before the server answered" });
|
|
771
|
+
}
|
|
772
|
+
this.reopening = platform.setTimeout(() => this.open(), backoff(this.attempt++));
|
|
773
|
+
}
|
|
774
|
+
listen(socket, due = this.heardAt + 2 * this.heartbeat, deferred = false) {
|
|
775
|
+
platform.clearTimeout(this.listening);
|
|
776
|
+
this.listening = platform.setTimeout(() => this.check(socket, due, deferred), Math.max(0, due - Date.now()));
|
|
777
|
+
}
|
|
778
|
+
check(socket, due, deferred) {
|
|
779
|
+
if (this.socket !== socket)
|
|
780
|
+
return;
|
|
781
|
+
const now = Date.now();
|
|
782
|
+
if (now < this.heardAt + 2 * this.heartbeat)
|
|
783
|
+
return this.listen(socket);
|
|
784
|
+
if (!deferred && now > due + this.heartbeat)
|
|
785
|
+
return this.listen(socket, now + this.heartbeat, true);
|
|
786
|
+
this.stuck(socket, due);
|
|
787
|
+
}
|
|
788
|
+
detached() {
|
|
789
|
+
this.connected = false;
|
|
790
|
+
for (const standing of this.subscriptions.values()) {
|
|
791
|
+
standing.sent = false;
|
|
792
|
+
standing.stopWaiting();
|
|
793
|
+
}
|
|
794
|
+
if (this.status.get().state === "connected")
|
|
795
|
+
this.change({ state: "reconnecting" });
|
|
796
|
+
}
|
|
797
|
+
send(message) {
|
|
798
|
+
this.socket?.send(encode(clientMessage, message));
|
|
799
|
+
}
|
|
800
|
+
received(bytes) {
|
|
801
|
+
const message = decode(serverMessage, bytes);
|
|
802
|
+
if (ENVIRONMENT_ANSWERS.has(message.tag))
|
|
803
|
+
this.answers++;
|
|
804
|
+
this.handle(message);
|
|
805
|
+
}
|
|
806
|
+
handle(message) {
|
|
807
|
+
switch (message.tag) {
|
|
808
|
+
case "Welcome": {
|
|
809
|
+
this.greeted = true;
|
|
810
|
+
this.attempting?.();
|
|
811
|
+
this.heartbeat = Number(message.value.heartbeat.micros / 1000n);
|
|
812
|
+
if (this.socket)
|
|
813
|
+
this.listen(this.socket);
|
|
814
|
+
for (const [id, request] of this.identities)
|
|
815
|
+
if (!request.sent)
|
|
816
|
+
this.ask(id, request);
|
|
817
|
+
this.ready();
|
|
818
|
+
return;
|
|
819
|
+
}
|
|
820
|
+
case "UnsupportedProtocol":
|
|
821
|
+
return this.stop({ state: "unsupportedProtocol", supported: message.value.supported });
|
|
822
|
+
case "Connected": {
|
|
823
|
+
const { connection, caller } = message.value;
|
|
824
|
+
this.connected = true;
|
|
825
|
+
this.held = { connection, identity: caller.identity };
|
|
826
|
+
this.attempt = 0;
|
|
827
|
+
this.attempting?.();
|
|
828
|
+
this.change({ state: "connected", connection, caller });
|
|
829
|
+
this.signedInAs(caller);
|
|
830
|
+
for (const [id, standing] of this.subscriptions)
|
|
831
|
+
if (!standing.sent)
|
|
832
|
+
this.hold(id, standing);
|
|
833
|
+
for (const pending of [this.calls, this.queries])
|
|
834
|
+
for (const call of pending.values())
|
|
835
|
+
if (!call.sent)
|
|
836
|
+
this.dispatch(call);
|
|
837
|
+
return;
|
|
838
|
+
}
|
|
839
|
+
case "Update": {
|
|
840
|
+
const awaited = (subscriptions) => new Set(subscriptions.flatMap((id) => this.subscriptions.get(id)?.key ?? []));
|
|
841
|
+
const awaiting = new Map(message.value.awaiting.map(({ call, subscriptions }) => [call, awaited(subscriptions)]));
|
|
842
|
+
const withdrawn = this.withdrawn(message.value.caused_by, awaiting);
|
|
843
|
+
const changed = new Set();
|
|
844
|
+
for (const { subscription, delivered } of message.value.changes) {
|
|
845
|
+
const standing = this.subscriptions.get(subscription);
|
|
846
|
+
if (!standing)
|
|
847
|
+
continue;
|
|
848
|
+
standing.deliver(delivered);
|
|
849
|
+
if (standing.endsWith(delivered))
|
|
850
|
+
this.subscriptions.delete(subscription);
|
|
851
|
+
changed.add(standing);
|
|
852
|
+
}
|
|
853
|
+
this.position = message.value.position;
|
|
854
|
+
this.ephemeral = message.value.ephemeral;
|
|
855
|
+
return this.shown(withdrawn, changed);
|
|
856
|
+
}
|
|
857
|
+
case "Unauthenticated":
|
|
858
|
+
return void this.unauthenticated();
|
|
859
|
+
case "ConnectRefused":
|
|
860
|
+
return this.refused(message.value.reason);
|
|
861
|
+
case "Ended": {
|
|
862
|
+
this.position = message.value.resume_from;
|
|
863
|
+
this.ephemeral = message.value.ephemeral;
|
|
864
|
+
this.detached();
|
|
865
|
+
this.connect();
|
|
866
|
+
return;
|
|
867
|
+
}
|
|
868
|
+
case "SubscribeRefused": {
|
|
869
|
+
const { subscription, reason } = message.value;
|
|
870
|
+
const standing = this.subscriptions.get(subscription);
|
|
871
|
+
if (!standing)
|
|
872
|
+
return;
|
|
873
|
+
if (reason.tag === "NotConnected" || reason.tag === "Ended") {
|
|
874
|
+
standing.sent = false;
|
|
875
|
+
return;
|
|
876
|
+
}
|
|
877
|
+
this.subscriptions.delete(subscription);
|
|
878
|
+
standing.refuse(reason);
|
|
879
|
+
standing.notify();
|
|
880
|
+
return;
|
|
881
|
+
}
|
|
882
|
+
case "ActionReply":
|
|
883
|
+
return this.answer(this.calls, message.value.call, message.value.outcome);
|
|
884
|
+
case "QueryReply":
|
|
885
|
+
return this.answer(this.queries, message.value.request, message.value.outcome);
|
|
886
|
+
case "Heartbeat":
|
|
887
|
+
return;
|
|
888
|
+
case "IdentityReply": {
|
|
889
|
+
const request = this.identities.get(message.value.request);
|
|
890
|
+
if (!request)
|
|
891
|
+
return;
|
|
892
|
+
this.identities.delete(message.value.request);
|
|
893
|
+
return request.settle(message.value.outcome);
|
|
894
|
+
}
|
|
895
|
+
}
|
|
896
|
+
}
|
|
897
|
+
refused(reason) {
|
|
898
|
+
this.attempting?.();
|
|
899
|
+
switch (reason.tag) {
|
|
900
|
+
case "NotAuthenticated":
|
|
901
|
+
return void this.unauthenticated();
|
|
902
|
+
case "Unavailable": {
|
|
903
|
+
this.failedAttempt();
|
|
904
|
+
const socket = this.socket;
|
|
905
|
+
this.reopening = platform.setTimeout(() => {
|
|
906
|
+
if (this.socket === socket && this.greeted)
|
|
907
|
+
this.connect();
|
|
908
|
+
}, backoff(this.attempt++));
|
|
909
|
+
return;
|
|
910
|
+
}
|
|
911
|
+
case "Refused": {
|
|
912
|
+
if (reason.value.tag === "LimitReached") {
|
|
913
|
+
const socket = this.socket;
|
|
914
|
+
this.change({ state: "refused", reason });
|
|
915
|
+
this.failCalls(reason.value);
|
|
916
|
+
this.reopening = platform.setTimeout(() => {
|
|
917
|
+
if (this.socket === socket && this.greeted)
|
|
918
|
+
this.connect();
|
|
919
|
+
}, limitReachedWait(reason.value.value.until));
|
|
920
|
+
return;
|
|
921
|
+
}
|
|
922
|
+
this.forget();
|
|
923
|
+
this.change({ state: "refused", reason });
|
|
924
|
+
return this.failCalls({ tag: "NotConnected" });
|
|
925
|
+
}
|
|
926
|
+
case "Subscription": {
|
|
927
|
+
const { subscription, reason: refusal } = reason.value;
|
|
928
|
+
const standing = this.subscriptions.get(subscription);
|
|
929
|
+
this.subscriptions.delete(subscription);
|
|
930
|
+
standing?.refuse(refusal);
|
|
931
|
+
standing?.notify();
|
|
932
|
+
return this.connect();
|
|
933
|
+
}
|
|
934
|
+
}
|
|
935
|
+
}
|
|
936
|
+
async unauthenticated() {
|
|
937
|
+
this.attempting?.();
|
|
938
|
+
this.connected = false;
|
|
939
|
+
const kept = this.keep(null);
|
|
940
|
+
this.signedInAs(null);
|
|
941
|
+
this.forget();
|
|
942
|
+
this.signedOut();
|
|
943
|
+
await kept;
|
|
944
|
+
}
|
|
945
|
+
forget() {
|
|
946
|
+
this.held = null;
|
|
947
|
+
this.position = null;
|
|
948
|
+
this.ephemeral = null;
|
|
949
|
+
for (const standing of this.subscriptions.values()) {
|
|
950
|
+
standing.reset();
|
|
951
|
+
standing.notify();
|
|
952
|
+
}
|
|
953
|
+
}
|
|
954
|
+
withdrawn(calls, awaiting = new Map()) {
|
|
955
|
+
const keys = new Set();
|
|
956
|
+
for (const call of calls) {
|
|
957
|
+
const revisions = this.edits.get(call);
|
|
958
|
+
if (!revisions)
|
|
959
|
+
continue;
|
|
960
|
+
const kept = awaiting.get(call) ?? new Set();
|
|
961
|
+
for (const { key } of revisions)
|
|
962
|
+
if (!kept.has(key))
|
|
963
|
+
keys.add(key);
|
|
964
|
+
const remaining = revisions.filter(({ key }) => kept.has(key));
|
|
965
|
+
if (remaining.length > 0)
|
|
966
|
+
this.edits.set(call, remaining);
|
|
967
|
+
else
|
|
968
|
+
this.edits.delete(call);
|
|
969
|
+
}
|
|
970
|
+
return keys;
|
|
971
|
+
}
|
|
972
|
+
shown(keys, changed = new Set()) {
|
|
973
|
+
for (const standing of this.subscriptions.values()) {
|
|
974
|
+
if (!keys.has(standing.key) || changed.has(standing))
|
|
975
|
+
continue;
|
|
976
|
+
standing.rebase();
|
|
977
|
+
changed.add(standing);
|
|
978
|
+
}
|
|
979
|
+
for (const standing of changed)
|
|
980
|
+
standing.notify();
|
|
981
|
+
}
|
|
982
|
+
answer(pending, id, outcome) {
|
|
983
|
+
const call = pending.get(id);
|
|
984
|
+
if (!call)
|
|
985
|
+
return;
|
|
986
|
+
if (outcome.tag === "Failed" && outcome.value.tag === "Overloaded") {
|
|
987
|
+
const wait = overloadedWait(outcome.value.value.retry_after, call.refused++);
|
|
988
|
+
call.overloaded = outcome.value;
|
|
989
|
+
if (Date.now() + wait - (call.firstSent ?? Date.now()) <= OVERLOADED_PATIENCE && Date.now() + wait < call.due) {
|
|
990
|
+
call.sent = false;
|
|
991
|
+
platform.setTimeout(() => {
|
|
992
|
+
if (pending.get(id) === call && !call.sent && this.connected)
|
|
993
|
+
this.dispatch(call);
|
|
994
|
+
}, wait);
|
|
995
|
+
return;
|
|
996
|
+
}
|
|
997
|
+
}
|
|
998
|
+
pending.delete(id);
|
|
999
|
+
call.settle(outcome);
|
|
1000
|
+
}
|
|
1001
|
+
}
|
|
1002
|
+
const stoppedReason = "the connection was closed or speaks another protocol version";
|
|
1003
|
+
const OVERLOADED_PATIENCE = 10000;
|
|
1004
|
+
const OVERLOADED_CEILING = 2000;
|
|
1005
|
+
function overloadedWait(retryAfter, refused) {
|
|
1006
|
+
const after = Math.min(OVERLOADED_CEILING, Number(retryAfter.micros) / 1000);
|
|
1007
|
+
const ceiling = Math.min(OVERLOADED_CEILING, after * 2 ** refused);
|
|
1008
|
+
return after + Math.random() * (ceiling - after);
|
|
1009
|
+
}
|
|
1010
|
+
const LIMIT_REACHED_RETRY = 60000;
|
|
1011
|
+
function limitReachedWait(until) {
|
|
1012
|
+
const untilReset = until === null ? Infinity : Number(until.microsSinceUnixEpoch / 1000n) - Date.now();
|
|
1013
|
+
return Math.max(0, Math.min(LIMIT_REACHED_RETRY, untilReset)) * (0.75 + Math.random() / 2);
|
|
1014
|
+
}
|
|
1015
|
+
function backoff(attempt) {
|
|
1016
|
+
return Math.min(10000, 250 * 2 ** attempt) * (0.5 + Math.random() / 2);
|
|
1017
|
+
}
|
|
1018
|
+
function parseSession(stored) {
|
|
1019
|
+
if (stored === null)
|
|
1020
|
+
return null;
|
|
1021
|
+
try {
|
|
1022
|
+
const session = JSON.parse(stored);
|
|
1023
|
+
if (typeof session === "object" && session !== null && "token" in session && typeof session.token === "string") {
|
|
1024
|
+
return { token: session.token, anonymous: "anonymous" in session && session.anonymous === true };
|
|
1025
|
+
}
|
|
1026
|
+
}
|
|
1027
|
+
catch { }
|
|
1028
|
+
return null;
|
|
1029
|
+
}
|
|
1030
|
+
export function connect(options) {
|
|
1031
|
+
return new Link(options);
|
|
1032
|
+
}
|