@rebasepro/client 0.26.0 → 0.27.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/dist/admin.d.ts +21 -1
- package/dist/apple-sign-in.d.ts +59 -0
- package/dist/auth.d.ts +52 -9
- package/dist/exports-contract.types.d.ts +4 -1
- package/dist/index.d.ts +19 -8
- package/dist/index.es.js +430 -35
- package/dist/index.es.js.map +1 -1
- package/dist/offline-store-BhYXViha.js.map +1 -1
- package/dist/realtime-channel.d.ts +20 -0
- package/dist/storage-contract.types.d.ts +16 -0
- package/dist/storage.d.ts +2 -2
- package/dist/transport.d.ts +18 -1
- package/dist/websocket.d.ts +28 -0
- package/package.json +4 -4
package/dist/index.es.js
CHANGED
|
@@ -2,6 +2,118 @@ import { c as invalidBulkBody, d as RebaseApiError, h as parseRebaseJson, i as i
|
|
|
2
2
|
import { DEFAULT_STORAGE_SOURCE_KEY, PUBLIC_STORAGE_PREFIX, RebaseApiError as RebaseApiError$1, RebaseClientError as RebaseClientError$1, STORAGE_REFERENCE_SCHEME, isPublicStoragePath, isStorageReference, isUnsupported, parseStorageReference, resolveStorageReferences, simulationHeaders, storageObjectPath, storageReference, storageReferencesForDownloadUrls, storageTargetOfDownloadUrl, storageTargetsInText } from "@rebasepro/types";
|
|
3
3
|
import { COMPOSITE_ID_SEPARATOR, DOWNLOAD_URL_CONCURRENCY, RESUMABLE_UPLOAD_THRESHOLD, RebasePaginationError, and, buildCompositeId, cond, createBatchLoader, createConcurrencyLimit, createDownloadUrlCache, not, or, warnDeprecated, withETag } from "@rebasepro/common";
|
|
4
4
|
import { toSnakeCase, unref } from "@rebasepro/utils";
|
|
5
|
+
//#region src/apple-sign-in.ts
|
|
6
|
+
/**
|
|
7
|
+
* The browser half of Sign in with Apple.
|
|
8
|
+
*
|
|
9
|
+
* Apple is the one provider a single-page app cannot take through the usual
|
|
10
|
+
* redirect: asking for the `name` or `email` scope obliges
|
|
11
|
+
* `response_mode=form_post`, so Apple answers with a cross-site POST to the
|
|
12
|
+
* redirect URI — a request a static page never sees. Apple's own JS SDK has a
|
|
13
|
+
* popup mode that hands the answer back to the opening page with
|
|
14
|
+
* `postMessage` instead, and that is what this uses. The redirect URI still
|
|
15
|
+
* has to be listed under the Services ID's Return URLs (HTTPS, no
|
|
16
|
+
* `localhost`), because Apple matches it and the token exchange repeats it.
|
|
17
|
+
*
|
|
18
|
+
* `state` is generated and checked here, which is what binds the code that
|
|
19
|
+
* comes back to the click that started it.
|
|
20
|
+
*/
|
|
21
|
+
/** Apple's JS SDK, the only way into its popup mode. */
|
|
22
|
+
var APPLE_JS_SDK_URL = "https://appleid.cdn-apple.com/appleauth/static/jsapi/appleid/1/en_US/appleauth.js";
|
|
23
|
+
/** Apple's popup answers with `{ error }` when the visitor backs out. */
|
|
24
|
+
var APPLE_CANCELLATIONS = /* @__PURE__ */ new Set(["popup_closed_by_user", "user_cancelled_authorize"]);
|
|
25
|
+
var sdkLoad = null;
|
|
26
|
+
function appleIdGlobal() {
|
|
27
|
+
return globalThis.AppleID;
|
|
28
|
+
}
|
|
29
|
+
/**
|
|
30
|
+
* Load Apple's SDK once per page. A failed load is forgotten, so a retry tries
|
|
31
|
+
* again. A tag someone else added and that has not finished yet is not waited
|
|
32
|
+
* on — it may already have failed, and its events would never come — so a
|
|
33
|
+
* second, cached copy is added instead, which is harmless.
|
|
34
|
+
*/
|
|
35
|
+
function loadAppleSdk() {
|
|
36
|
+
const loaded = appleIdGlobal();
|
|
37
|
+
if (loaded) return Promise.resolve(loaded);
|
|
38
|
+
if (sdkLoad) return sdkLoad;
|
|
39
|
+
sdkLoad = new Promise((resolve, reject) => {
|
|
40
|
+
const script = document.createElement("script");
|
|
41
|
+
script.src = APPLE_JS_SDK_URL;
|
|
42
|
+
script.async = true;
|
|
43
|
+
script.onload = () => {
|
|
44
|
+
const apple = appleIdGlobal();
|
|
45
|
+
if (apple) resolve(apple);
|
|
46
|
+
else reject(/* @__PURE__ */ new Error("Apple's sign-in script loaded without defining AppleID"));
|
|
47
|
+
};
|
|
48
|
+
script.onerror = () => reject(/* @__PURE__ */ new Error("Apple's sign-in script could not be loaded"));
|
|
49
|
+
document.head.appendChild(script);
|
|
50
|
+
}).catch((err) => {
|
|
51
|
+
sdkLoad = null;
|
|
52
|
+
throw new RebaseClientError("Sign in with Apple could not be loaded. Check your connection or any script blockers, then try again.", {
|
|
53
|
+
code: "APPLE_SIGN_IN_UNAVAILABLE",
|
|
54
|
+
cause: err
|
|
55
|
+
});
|
|
56
|
+
});
|
|
57
|
+
return sdkLoad;
|
|
58
|
+
}
|
|
59
|
+
/**
|
|
60
|
+
* Start loading Apple's SDK ahead of the click. Worth calling when the sign-in
|
|
61
|
+
* button mounts: with the SDK already on the page, the popup opens in the same
|
|
62
|
+
* task as the click, and Safari blocks a popup that opens later than that.
|
|
63
|
+
*/
|
|
64
|
+
async function preloadAppleSignIn() {
|
|
65
|
+
if (typeof document === "undefined") return;
|
|
66
|
+
await loadAppleSdk();
|
|
67
|
+
}
|
|
68
|
+
function randomState() {
|
|
69
|
+
const bytes = /* @__PURE__ */ new Uint8Array(16);
|
|
70
|
+
crypto.getRandomValues(bytes);
|
|
71
|
+
return Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("");
|
|
72
|
+
}
|
|
73
|
+
/**
|
|
74
|
+
* Open Apple's sign-in popup and return the authorization code, without
|
|
75
|
+
* spending it. Call it from a click handler: browsers block a popup that no
|
|
76
|
+
* gesture opened. Call {@link preloadAppleSignIn} first (on mount) so the
|
|
77
|
+
* popup does not wait on a script download.
|
|
78
|
+
*
|
|
79
|
+
* Throws a `RebaseClientError` whose `code` is `APPLE_SIGN_IN_CANCELLED` when
|
|
80
|
+
* the visitor closes the popup or declines, `APPLE_SIGN_IN_UNAVAILABLE` when
|
|
81
|
+
* Apple's script cannot load or this is not a browser, and
|
|
82
|
+
* `APPLE_SIGN_IN_FAILED` otherwise.
|
|
83
|
+
*/
|
|
84
|
+
async function requestAppleAuthorization(request) {
|
|
85
|
+
if (typeof window === "undefined" || typeof document === "undefined") throw new RebaseClientError("Sign in with Apple's popup needs a browser. A native app gets the code from ASAuthorizationController and passes it to signInWithApple({ code, bundleId }).", { code: "APPLE_SIGN_IN_UNAVAILABLE" });
|
|
86
|
+
const apple = appleIdGlobal() ?? await loadAppleSdk();
|
|
87
|
+
const redirectUri = request.redirectUri ?? `${window.location.origin}/`;
|
|
88
|
+
const state = randomState();
|
|
89
|
+
apple.auth.init({
|
|
90
|
+
clientId: request.clientId,
|
|
91
|
+
scope: "name email",
|
|
92
|
+
redirectURI: redirectUri,
|
|
93
|
+
state,
|
|
94
|
+
usePopup: true
|
|
95
|
+
});
|
|
96
|
+
let response;
|
|
97
|
+
try {
|
|
98
|
+
response = await apple.auth.signIn();
|
|
99
|
+
} catch (err) {
|
|
100
|
+
const reason = typeof err === "object" && err !== null && "error" in err && typeof err.error === "string" ? err.error : void 0;
|
|
101
|
+
if (reason && APPLE_CANCELLATIONS.has(reason)) throw new RebaseClientError("Sign in with Apple was cancelled.", { code: "APPLE_SIGN_IN_CANCELLED" });
|
|
102
|
+
throw new RebaseClientError(reason ? `Sign in with Apple failed: ${reason}` : "Sign in with Apple failed. Please try again.", {
|
|
103
|
+
code: "APPLE_SIGN_IN_FAILED",
|
|
104
|
+
cause: err
|
|
105
|
+
});
|
|
106
|
+
}
|
|
107
|
+
const authorization = response.authorization;
|
|
108
|
+
if (!authorization?.code) throw new RebaseClientError("Apple returned no authorization code.", { code: "APPLE_SIGN_IN_FAILED" });
|
|
109
|
+
if (authorization.state !== state) throw new RebaseClientError("This Apple sign-in could not be verified as one started on this page. Please try again.", { code: "APPLE_SIGN_IN_FAILED" });
|
|
110
|
+
return {
|
|
111
|
+
code: authorization.code,
|
|
112
|
+
redirectUri,
|
|
113
|
+
...response.user?.name ? { user: { name: response.user.name } } : {}
|
|
114
|
+
};
|
|
115
|
+
}
|
|
116
|
+
//#endregion
|
|
5
117
|
//#region src/auth.ts
|
|
6
118
|
/** Map a raw user object from an auth response (`/login`, `/refresh`, `/me`) to a `User`. */
|
|
7
119
|
function mapRawUser(raw) {
|
|
@@ -51,13 +163,31 @@ function detectStorage() {
|
|
|
51
163
|
} catch (e) {}
|
|
52
164
|
return createMemoryStorage();
|
|
53
165
|
}
|
|
166
|
+
/**
|
|
167
|
+
* The flow mode a client uses when `authFlowMode` is not set.
|
|
168
|
+
*
|
|
169
|
+
* Cookie in a browser. A backend run by the Rebase runtime always keeps the
|
|
170
|
+
* refresh token in a cookie and answers the body's with `""`, so a browser
|
|
171
|
+
* client defaulting to json held nothing to renew with, and was signed out
|
|
172
|
+
* without a word once its access token expired, about an hour after sign-in.
|
|
173
|
+
*
|
|
174
|
+
* Json off the browser (Node, a worker, React Native), where there is no
|
|
175
|
+
* cookie jar to keep it in — and in a browser that passes its own `storage`,
|
|
176
|
+
* which says where the session is to be kept: a second client on the page
|
|
177
|
+
* that keeps its own sign-in apart from the page's cookie. In cookie mode
|
|
178
|
+
* nothing would be kept there, and every reload would lose that sign-in.
|
|
179
|
+
*/
|
|
180
|
+
function resolveAuthFlowMode(options) {
|
|
181
|
+
if (options?.authFlowMode) return options.authFlowMode;
|
|
182
|
+
return typeof document !== "undefined" && !options?.storage ? "cookie" : "json";
|
|
183
|
+
}
|
|
54
184
|
function createAuth(transport, options) {
|
|
55
185
|
const opts = options || {};
|
|
56
186
|
const storage = opts.storage || detectStorage();
|
|
57
187
|
const authPath = opts.authPath || "/auth";
|
|
58
188
|
const autoRefresh = opts.autoRefresh !== false;
|
|
59
189
|
const persistSession = opts.persistSession !== false;
|
|
60
|
-
const authFlowMode = opts
|
|
190
|
+
const authFlowMode = resolveAuthFlowMode(opts);
|
|
61
191
|
const STORAGE_KEY = "rebase_auth";
|
|
62
192
|
const REFRESH_BUFFER_MS = 12e4;
|
|
63
193
|
/**
|
|
@@ -129,6 +259,25 @@ function createAuth(transport, options) {
|
|
|
129
259
|
if (authFlowMode === "cookie") return "";
|
|
130
260
|
return received || currentSession?.refreshToken || "";
|
|
131
261
|
}
|
|
262
|
+
let flowMismatchReported = false;
|
|
263
|
+
/**
|
|
264
|
+
* Say so at sign-in, once, when the server's answer shows this client
|
|
265
|
+
* cannot renew the session it is starting.
|
|
266
|
+
*
|
|
267
|
+
* A server with `cookieAuth` answers `refreshToken: ""` and puts the token
|
|
268
|
+
* in the cookie; one without it puts the token in the body. A client in
|
|
269
|
+
* the other mode holds nothing it can renew with, and finds out when the
|
|
270
|
+
* access token expires — in json mode by dropping the session without a
|
|
271
|
+
* word. The answer to the sign-in is the first moment it is known.
|
|
272
|
+
*/
|
|
273
|
+
function reportFlowMismatch(received, expiresAt) {
|
|
274
|
+
if (flowMismatchReported || received === void 0) return;
|
|
275
|
+
const serverUsesCookie = received === "";
|
|
276
|
+
if (serverUsesCookie === (authFlowMode === "cookie")) return;
|
|
277
|
+
flowMismatchReported = true;
|
|
278
|
+
const ends = Number.isFinite(expiresAt) ? `in about ${Math.max(1, Math.round((expiresAt - Date.now()) / 6e4))} minutes` : "when its access token expires";
|
|
279
|
+
console.error(serverUsesCookie ? `[rebase] This server keeps the refresh token in an HttpOnly cookie (its \`auth.cookieAuth\`), but this client is in json mode and was handed none, so the session it just started cannot be renewed and ends ${ends}. Create the client with \`auth: { authFlowMode: "cookie" }\`.` : `[rebase] This server returned the refresh token in the response body, so it does not use \`auth.cookieAuth\`, and this client, in cookie mode, cannot renew the session it just started: it ends ${ends}. Turn on \`auth.cookieAuth\` on the server, or create the client with \`auth: { authFlowMode: "json" }\`.`);
|
|
280
|
+
}
|
|
132
281
|
/**
|
|
133
282
|
* Whether the server refused a refresh as malformed: a 400, which says the
|
|
134
283
|
* request this client built is not one that server accepts.
|
|
@@ -267,6 +416,15 @@ function createAuth(transport, options) {
|
|
|
267
416
|
*/
|
|
268
417
|
const SPENT_TOKEN_MARGIN_MS = 1e4;
|
|
269
418
|
/**
|
|
419
|
+
* Whether a request about to carry this session's token should first get a
|
|
420
|
+
* fresh one: the token has expired or is about to, and can be renewed.
|
|
421
|
+
*/
|
|
422
|
+
function needsFreshToken(session) {
|
|
423
|
+
if (!Number.isFinite(session.expiresAt)) return false;
|
|
424
|
+
if (session.expiresAt > Date.now() + SPENT_TOKEN_MARGIN_MS) return false;
|
|
425
|
+
return authFlowMode === "cookie" || !!session.refreshToken;
|
|
426
|
+
}
|
|
427
|
+
/**
|
|
270
428
|
* The transport's {@link TokenRefresher}: whether a request should wait for
|
|
271
429
|
* a fresher token than the one held, and which token to send when it does.
|
|
272
430
|
*
|
|
@@ -294,9 +452,7 @@ function createAuth(transport, options) {
|
|
|
294
452
|
if (refreshOwnRequests > 0) return void 0;
|
|
295
453
|
const session = currentSession;
|
|
296
454
|
if (!session) return cookieRestore?.then(() => void 0);
|
|
297
|
-
if (!
|
|
298
|
-
if (session.expiresAt > Date.now() + SPENT_TOKEN_MARGIN_MS) return void 0;
|
|
299
|
-
if (authFlowMode !== "cookie" && !session.refreshToken) return void 0;
|
|
455
|
+
if (!needsFreshToken(session)) return void 0;
|
|
300
456
|
const epoch = sessionEpoch;
|
|
301
457
|
return refreshSession().then((fresh) => epoch === sessionEpoch ? fresh.accessToken : void 0, () => epoch === sessionEpoch ? session.accessToken : void 0);
|
|
302
458
|
}
|
|
@@ -368,6 +524,7 @@ function createAuth(transport, options) {
|
|
|
368
524
|
}
|
|
369
525
|
function handleAuthResponse(data, event) {
|
|
370
526
|
sessionEpoch++;
|
|
527
|
+
reportFlowMismatch(data.tokens.refreshToken, data.tokens.accessTokenExpiresAt);
|
|
371
528
|
const user = mapRawUser(data.user);
|
|
372
529
|
const session = {
|
|
373
530
|
accessToken: data.tokens.accessToken,
|
|
@@ -505,13 +662,55 @@ function createAuth(transport, options) {
|
|
|
505
662
|
redirectUri
|
|
506
663
|
});
|
|
507
664
|
}
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
|
|
665
|
+
/**
|
|
666
|
+
* Sign in with an Apple authorization code.
|
|
667
|
+
*
|
|
668
|
+
* - Web: `signInWithApple({ code, redirectUri, user })` — or let
|
|
669
|
+
* {@link signInWithApplePopup} obtain the code for you.
|
|
670
|
+
* - Native (iOS, iPadOS, macOS): `signInWithApple({ code, bundleId, user })`
|
|
671
|
+
* with the `authorizationCode` from `ASAuthorizationController`. The
|
|
672
|
+
* bundle id must be in the backend's `APPLE_BUNDLE_IDS`.
|
|
673
|
+
*
|
|
674
|
+
* `user` carries the name Apple reports on the first authorization only.
|
|
675
|
+
* The positional `(code, redirectUri, user)` form is the web call, kept for
|
|
676
|
+
* existing callers.
|
|
677
|
+
*/
|
|
678
|
+
async function signInWithApple(payloadOrCode, redirectUri, user) {
|
|
679
|
+
const payload = typeof payloadOrCode === "string" ? {
|
|
680
|
+
code: payloadOrCode,
|
|
511
681
|
redirectUri,
|
|
512
682
|
user
|
|
683
|
+
} : payloadOrCode;
|
|
684
|
+
return signInWithOAuth("apple", {
|
|
685
|
+
code: payload.code,
|
|
686
|
+
...payload.redirectUri !== void 0 ? { redirectUri: payload.redirectUri } : {},
|
|
687
|
+
...payload.bundleId !== void 0 ? { bundleId: payload.bundleId } : {},
|
|
688
|
+
...payload.user?.name ? { user: { name: payload.user.name } } : {}
|
|
513
689
|
});
|
|
514
690
|
}
|
|
691
|
+
/**
|
|
692
|
+
* Sign in with Apple in a browser: opens Apple's popup, then spends the
|
|
693
|
+
* code it returns. Call it from a click handler, since browsers block a
|
|
694
|
+
* popup that no gesture opened.
|
|
695
|
+
*
|
|
696
|
+
* `clientId` defaults to the Services ID the backend publishes in
|
|
697
|
+
* `GET /auth/config` — but pass it when you can: fetching it first delays
|
|
698
|
+
* the popup past the click, which Safari blocks. Call
|
|
699
|
+
* `preloadAppleSignIn()` on mount for the same reason. `redirectUri`
|
|
700
|
+
* defaults to this page's origin plus `/`; either way it must be a Return
|
|
701
|
+
* URL registered on the Services ID.
|
|
702
|
+
*
|
|
703
|
+
* A closed popup rejects with a `RebaseClientError` whose `code` is
|
|
704
|
+
* `APPLE_SIGN_IN_CANCELLED` — an answer, not a failure.
|
|
705
|
+
*/
|
|
706
|
+
async function signInWithApplePopup(options = {}) {
|
|
707
|
+
const clientId = options.clientId ?? (await getAuthConfig()).providerClientIds?.apple;
|
|
708
|
+
if (!clientId) throw new RebaseClientError$1("Sign in with Apple needs a Services ID: set APPLE_CLIENT_ID on the backend, or pass clientId.", { code: "APPLE_SIGN_IN_UNAVAILABLE" });
|
|
709
|
+
return signInWithApple(await requestAppleAuthorization({
|
|
710
|
+
clientId,
|
|
711
|
+
redirectUri: options.redirectUri
|
|
712
|
+
}));
|
|
713
|
+
}
|
|
515
714
|
async function signInWithFacebook(code, redirectUri) {
|
|
516
715
|
return signInWithOAuth("facebook", {
|
|
517
716
|
code,
|
|
@@ -1208,9 +1407,49 @@ function createAuth(transport, options) {
|
|
|
1208
1407
|
if (!res.ok) throwApiError(res.status, body, res.statusText);
|
|
1209
1408
|
return body;
|
|
1210
1409
|
}
|
|
1410
|
+
/**
|
|
1411
|
+
* The session as it is now, or `null`.
|
|
1412
|
+
*
|
|
1413
|
+
* A snapshot: every renewal of the access token (about hourly) replaces
|
|
1414
|
+
* the session with a new object, so one kept from an earlier call carries
|
|
1415
|
+
* a token the server refuses once it expires. Read it when you need it.
|
|
1416
|
+
* For a token to send, use {@link getAccessToken}.
|
|
1417
|
+
*/
|
|
1211
1418
|
function getSession() {
|
|
1212
1419
|
return currentSession;
|
|
1213
1420
|
}
|
|
1421
|
+
/**
|
|
1422
|
+
* The access token to put on a request of your own — a route outside
|
|
1423
|
+
* Rebase, a header for an upload — renewed first when it has expired or
|
|
1424
|
+
* is about to. `null` when no one is signed in.
|
|
1425
|
+
*
|
|
1426
|
+
* Ask for it for each request rather than keeping it: every renewal
|
|
1427
|
+
* replaces it. A Rebase function needs none of this, since
|
|
1428
|
+
* `functions.invoke` renews before sending and retries once on a 401.
|
|
1429
|
+
*
|
|
1430
|
+
* Waits for the session restored on load, and calls made together share
|
|
1431
|
+
* one renewal. A renewal the server refuses ends the session, as a refused
|
|
1432
|
+
* request does, and answers `null`. One that cannot reach the server
|
|
1433
|
+
* answers the token held, for the server to judge.
|
|
1434
|
+
*/
|
|
1435
|
+
async function getAccessToken() {
|
|
1436
|
+
await isInitialized;
|
|
1437
|
+
const session = currentSession;
|
|
1438
|
+
if (!session) return null;
|
|
1439
|
+
if (!needsFreshToken(session)) return session.accessToken;
|
|
1440
|
+
const epoch = sessionEpoch;
|
|
1441
|
+
try {
|
|
1442
|
+
const fresh = await refreshSession();
|
|
1443
|
+
return epoch === sessionEpoch ? fresh.accessToken : currentSession?.accessToken ?? null;
|
|
1444
|
+
} catch (err) {
|
|
1445
|
+
if (epoch !== sessionEpoch) return currentSession?.accessToken ?? null;
|
|
1446
|
+
if (isFatalRefreshError(err)) {
|
|
1447
|
+
abandonSessionLocally();
|
|
1448
|
+
return null;
|
|
1449
|
+
}
|
|
1450
|
+
return session.accessToken;
|
|
1451
|
+
}
|
|
1452
|
+
}
|
|
1214
1453
|
function onAuthStateChange(callback) {
|
|
1215
1454
|
listeners.add(callback);
|
|
1216
1455
|
return () => listeners.delete(callback);
|
|
@@ -1261,6 +1500,7 @@ function createAuth(transport, options) {
|
|
|
1261
1500
|
signInWithGitHub,
|
|
1262
1501
|
signInWithMicrosoft,
|
|
1263
1502
|
signInWithApple,
|
|
1503
|
+
signInWithApplePopup,
|
|
1264
1504
|
signInWithFacebook,
|
|
1265
1505
|
signInWithTwitter,
|
|
1266
1506
|
signInWithDiscord,
|
|
@@ -1295,6 +1535,7 @@ function createAuth(transport, options) {
|
|
|
1295
1535
|
revokeAllSessions,
|
|
1296
1536
|
getAuthConfig,
|
|
1297
1537
|
getSession,
|
|
1538
|
+
getAccessToken,
|
|
1298
1539
|
onAuthStateChange,
|
|
1299
1540
|
canRestoreSession: () => persistSession || authFlowMode === "cookie",
|
|
1300
1541
|
isInitialized: () => isInitialized,
|
|
@@ -1346,6 +1587,7 @@ function createCookieStorage(options = {}) {
|
|
|
1346
1587
|
}
|
|
1347
1588
|
//#endregion
|
|
1348
1589
|
//#region src/admin.ts
|
|
1590
|
+
var isoDate = (date) => date instanceof Date ? date.toISOString() : date;
|
|
1349
1591
|
function createAdmin(transport, options) {
|
|
1350
1592
|
const adminPath = (options || {}).adminPath || "/admin";
|
|
1351
1593
|
/**
|
|
@@ -1409,6 +1651,29 @@ function createAdmin(transport, options) {
|
|
|
1409
1651
|
async function resetMfa(userId) {
|
|
1410
1652
|
return transport.request(adminPath + "/users/" + encodeURIComponent(userId) + "/mfa", { method: "DELETE" });
|
|
1411
1653
|
}
|
|
1654
|
+
/** One page of guests, the ones last seen longest ago first, with the `total` matching. */
|
|
1655
|
+
async function listGuests(options) {
|
|
1656
|
+
const params = new URLSearchParams();
|
|
1657
|
+
if (options?.limit !== void 0) params.set("limit", String(options.limit));
|
|
1658
|
+
if (options?.offset !== void 0) params.set("offset", String(options.offset));
|
|
1659
|
+
if (options?.lastSeenBefore !== void 0) params.set("lastSeenBefore", isoDate(options.lastSeenBefore));
|
|
1660
|
+
const qs = params.toString();
|
|
1661
|
+
return transport.request(adminPath + "/guests" + (qs ? "?" + qs : ""), { method: "GET" });
|
|
1662
|
+
}
|
|
1663
|
+
/** Delete one guest. An account is refused with `NOT_ANONYMOUS`; {@link deleteUser} deletes those. */
|
|
1664
|
+
async function deleteGuest(userId) {
|
|
1665
|
+
return transport.request(adminPath + "/guests/" + encodeURIComponent(userId), { method: "DELETE" });
|
|
1666
|
+
}
|
|
1667
|
+
/**
|
|
1668
|
+
* Delete one batch of the guests last seen before a date. It can only ever
|
|
1669
|
+
* touch guests. Repeat it while `remaining` is not 0, passing how many have
|
|
1670
|
+
* been skipped so far as `offset`.
|
|
1671
|
+
*/
|
|
1672
|
+
async function deleteGuests(options) {
|
|
1673
|
+
const params = new URLSearchParams({ lastSeenBefore: isoDate(options.lastSeenBefore) });
|
|
1674
|
+
if (options.offset) params.set("offset", String(options.offset));
|
|
1675
|
+
return transport.request(adminPath + "/guests?" + params.toString(), { method: "DELETE" });
|
|
1676
|
+
}
|
|
1412
1677
|
async function resetPassword(userId, options) {
|
|
1413
1678
|
return transport.request(adminPath + "/users/" + encodeURIComponent(userId) + "/reset-password", {
|
|
1414
1679
|
method: "POST",
|
|
@@ -1429,6 +1694,9 @@ function createAdmin(transport, options) {
|
|
|
1429
1694
|
updateUser,
|
|
1430
1695
|
deleteUser,
|
|
1431
1696
|
resetMfa,
|
|
1697
|
+
listGuests,
|
|
1698
|
+
deleteGuest,
|
|
1699
|
+
deleteGuests,
|
|
1432
1700
|
resetPassword,
|
|
1433
1701
|
listRoles,
|
|
1434
1702
|
bootstrap
|
|
@@ -2238,15 +2506,31 @@ var SOCKET_OPT_INS = [
|
|
|
2238
2506
|
"channel_seq",
|
|
2239
2507
|
"cancel_sql"
|
|
2240
2508
|
];
|
|
2509
|
+
/**
|
|
2510
|
+
* The query parameter naming the group a socket belongs to. A platform that
|
|
2511
|
+
* routes on it sends sockets with the same value to the same instance; the
|
|
2512
|
+
* server itself never reads it.
|
|
2513
|
+
*/
|
|
2514
|
+
var SOCKET_AFFINITY_PARAM = "affinity";
|
|
2241
2515
|
/** Slack on top of two heartbeat intervals before a silent socket is given up on. */
|
|
2242
2516
|
var HEARTBEAT_GRACE_MS = 5e3;
|
|
2243
2517
|
/**
|
|
2244
|
-
* `url` with the opt-ins named on it
|
|
2245
|
-
* `URL`, which would rewrite the address
|
|
2246
|
-
* a `/`).
|
|
2518
|
+
* `url` with the opt-ins named on it, and `affinity` when there is one.
|
|
2519
|
+
* Appended rather than rebuilt through `URL`, which would rewrite the address
|
|
2520
|
+
* the caller gave (a bare origin gains a `/`).
|
|
2521
|
+
*
|
|
2522
|
+
* `affinity` replaces one already in `url`: a router takes one value, and it
|
|
2523
|
+
* may not be the last.
|
|
2247
2524
|
*/
|
|
2248
|
-
function withOptIns(url) {
|
|
2249
|
-
|
|
2525
|
+
function withOptIns(url, affinity) {
|
|
2526
|
+
const queryAt = url.indexOf("?");
|
|
2527
|
+
const address = queryAt === -1 ? url : url.slice(0, queryAt);
|
|
2528
|
+
const params = queryAt === -1 ? [] : url.slice(queryAt + 1).split("&");
|
|
2529
|
+
return `${address}?${[
|
|
2530
|
+
...affinity ? params.filter((param) => !param.startsWith(`${SOCKET_AFFINITY_PARAM}=`)) : params,
|
|
2531
|
+
...affinity ? [`${SOCKET_AFFINITY_PARAM}=${encodeURIComponent(affinity)}`] : [],
|
|
2532
|
+
`${SOCKET_OPT_IN_PARAM}=${SOCKET_OPT_INS.join(",")}`
|
|
2533
|
+
].join("&")}`;
|
|
2250
2534
|
}
|
|
2251
2535
|
/**
|
|
2252
2536
|
* Broadcast and presence frames.
|
|
@@ -2334,8 +2618,15 @@ function isCollectionUpdate(message) {
|
|
|
2334
2618
|
function isChannelMessage(message) {
|
|
2335
2619
|
return typeof message.channel === "string" && CHANNEL_FRAME_TYPES.has(message.type);
|
|
2336
2620
|
}
|
|
2621
|
+
/** The code of a channel `ERROR` frame, if it is one and carries a code. */
|
|
2622
|
+
function channelErrorCode(message) {
|
|
2623
|
+
if (message.type !== "ERROR" && message.type !== "error") return void 0;
|
|
2624
|
+
const raw = message.payload?.error;
|
|
2625
|
+
if (raw && typeof raw === "object" && "code" in raw && typeof raw.code === "string") return raw.code;
|
|
2626
|
+
}
|
|
2337
2627
|
var RebaseWebSocketClient = class {
|
|
2338
2628
|
websocketUrl;
|
|
2629
|
+
affinity;
|
|
2339
2630
|
ws = null;
|
|
2340
2631
|
/**
|
|
2341
2632
|
* Where the socket's token comes from. A client built by
|
|
@@ -2527,6 +2818,7 @@ var RebaseWebSocketClient = class {
|
|
|
2527
2818
|
}
|
|
2528
2819
|
constructor(config) {
|
|
2529
2820
|
this.websocketUrl = config.websocketUrl;
|
|
2821
|
+
this.affinity = config.affinity;
|
|
2530
2822
|
this.getAuthToken = config.getAuthToken;
|
|
2531
2823
|
this.onUnauthorized = config.onUnauthorized;
|
|
2532
2824
|
this.impersonate = config.impersonate;
|
|
@@ -2534,6 +2826,13 @@ var RebaseWebSocketClient = class {
|
|
|
2534
2826
|
this.WebSocketConstructor = config.WebSocket || (typeof WebSocket !== "undefined" ? WebSocket : void 0);
|
|
2535
2827
|
}
|
|
2536
2828
|
/**
|
|
2829
|
+
* Name the group this socket belongs to, or clear it with `null`. Read at
|
|
2830
|
+
* each dial, so a socket already open stays where it is until it redials.
|
|
2831
|
+
*/
|
|
2832
|
+
setAffinity(key) {
|
|
2833
|
+
this.affinity = key ?? void 0;
|
|
2834
|
+
}
|
|
2835
|
+
/**
|
|
2537
2836
|
* Open the socket if it is not open (or opening) already.
|
|
2538
2837
|
*
|
|
2539
2838
|
* Idempotent, synchronous, and safe to call on every operation that needs a
|
|
@@ -2637,6 +2936,55 @@ var RebaseWebSocketClient = class {
|
|
|
2637
2936
|
/**
|
|
2638
2937
|
* Authenticate the WebSocket connection
|
|
2639
2938
|
*/
|
|
2939
|
+
/**
|
|
2940
|
+
* {@link authenticate}, asked again a few times when the server could not
|
|
2941
|
+
* answer (its auth store busy, `ROLE_LOOKUP_FAILED`, a timeout) — not when
|
|
2942
|
+
* it refused the session or the socket ceiling, which a retry cannot
|
|
2943
|
+
* change. Stops as soon as `socket` is no longer this client's.
|
|
2944
|
+
*/
|
|
2945
|
+
async authenticateRetrying(token, socket) {
|
|
2946
|
+
const delays = [
|
|
2947
|
+
500,
|
|
2948
|
+
1500,
|
|
2949
|
+
3500
|
|
2950
|
+
];
|
|
2951
|
+
for (let attempt = 0;; attempt++) try {
|
|
2952
|
+
await this.authenticate(token);
|
|
2953
|
+
return;
|
|
2954
|
+
} catch (error) {
|
|
2955
|
+
if (attempt >= delays.length || this.ws !== socket || isSocketCeilingRefusal(error) || isSessionRefusal(error)) throw error;
|
|
2956
|
+
await new Promise((resolve) => setTimeout(resolve, delays[attempt]));
|
|
2957
|
+
if (this.ws !== socket) throw error;
|
|
2958
|
+
}
|
|
2959
|
+
}
|
|
2960
|
+
/** A sign-in again after a channel was refused for not being signed in, in flight. */
|
|
2961
|
+
channelAuthRecovery = null;
|
|
2962
|
+
/**
|
|
2963
|
+
* A channel frame refused `UNAUTHORIZED` while this client holds a way to
|
|
2964
|
+
* get a token: the socket is open but not signed in (an authentication that
|
|
2965
|
+
* failed on a reconnect, a token that expired). Nothing else signs it in —
|
|
2966
|
+
* channel frames expect no answer, so the refusal reaches only the channel —
|
|
2967
|
+
* and every later frame is refused the same way. Sign in again, once for
|
|
2968
|
+
* all the channels that noticed, and have them re-join.
|
|
2969
|
+
*/
|
|
2970
|
+
recoverChannelAuth() {
|
|
2971
|
+
if (this.channelAuthRecovery || !this.getAuthToken || this.isAuthenticated) return;
|
|
2972
|
+
const socket = this.ws;
|
|
2973
|
+
this.channelAuthRecovery = (async () => {
|
|
2974
|
+
try {
|
|
2975
|
+
const token = await this.getAuthToken();
|
|
2976
|
+
if (!token || !socket || this.ws !== socket) return;
|
|
2977
|
+
await this.authenticateRetrying(token, socket);
|
|
2978
|
+
if (this.ws === socket) this.emit("reconnect");
|
|
2979
|
+
} catch (error) {
|
|
2980
|
+
this.connectionDebug("Could not sign the socket in again for a channel:", error?.message || error);
|
|
2981
|
+
} finally {
|
|
2982
|
+
setTimeout(() => {
|
|
2983
|
+
this.channelAuthRecovery = null;
|
|
2984
|
+
}, 2e3);
|
|
2985
|
+
}
|
|
2986
|
+
})();
|
|
2987
|
+
}
|
|
2640
2988
|
async authenticate(token) {
|
|
2641
2989
|
return new Promise((resolve, reject) => {
|
|
2642
2990
|
const requestId = `auth_${Date.now()}_${Math.random().toString(36).substring(2, 9)}`;
|
|
@@ -2733,7 +3081,7 @@ var RebaseWebSocketClient = class {
|
|
|
2733
3081
|
this.ws = null;
|
|
2734
3082
|
}
|
|
2735
3083
|
try {
|
|
2736
|
-
const socket = new this.WebSocketConstructor(withOptIns(this.websocketUrl));
|
|
3084
|
+
const socket = new this.WebSocketConstructor(withOptIns(this.websocketUrl, this.affinity));
|
|
2737
3085
|
this.ws = socket;
|
|
2738
3086
|
this.ws.onopen = async () => {
|
|
2739
3087
|
this.connectionDebug("Connected to PostgreSQL backend");
|
|
@@ -2748,7 +3096,7 @@ var RebaseWebSocketClient = class {
|
|
|
2748
3096
|
try {
|
|
2749
3097
|
token = await this.getAuthToken();
|
|
2750
3098
|
if (token) {
|
|
2751
|
-
await this.
|
|
3099
|
+
await this.authenticateRetrying(token, socket);
|
|
2752
3100
|
this.connectionDebug("WebSocket auto-authenticated");
|
|
2753
3101
|
}
|
|
2754
3102
|
} catch (error) {
|
|
@@ -2756,7 +3104,13 @@ var RebaseWebSocketClient = class {
|
|
|
2756
3104
|
this.noteSocketCeiling(error);
|
|
2757
3105
|
return;
|
|
2758
3106
|
}
|
|
2759
|
-
if (!(token && this.noteSessionRefused(token, error)))
|
|
3107
|
+
if (!(token && this.noteSessionRefused(token, error))) {
|
|
3108
|
+
this.connectionDebug("WebSocket connected, not signed in yet:", error?.message || error);
|
|
3109
|
+
if (token && this.ws === socket && !this.refusedSession) {
|
|
3110
|
+
socket.close(4e3, "Could not authenticate; reconnecting");
|
|
3111
|
+
return;
|
|
3112
|
+
}
|
|
3113
|
+
}
|
|
2760
3114
|
}
|
|
2761
3115
|
}
|
|
2762
3116
|
if (this.ws !== socket) return;
|
|
@@ -3059,6 +3413,7 @@ var RebaseWebSocketClient = class {
|
|
|
3059
3413
|
return;
|
|
3060
3414
|
}
|
|
3061
3415
|
if (isChannelMessage(message)) {
|
|
3416
|
+
if (channelErrorCode(message) === "UNAUTHORIZED") this.recoverChannelAuth();
|
|
3062
3417
|
const handlers = this.channelHandlers.get(message.channel);
|
|
3063
3418
|
if (handlers) for (const handler of [...handlers]) try {
|
|
3064
3419
|
handler(message);
|
|
@@ -4103,6 +4458,28 @@ var RebaseRealtimeChannel = class {
|
|
|
4103
4458
|
await this.send("presence_state");
|
|
4104
4459
|
if (this.wantsHistory) await this.requestHistory();
|
|
4105
4460
|
}
|
|
4461
|
+
/** Consecutive re-joins asked for by refusals, for the backoff; reset after a quiet minute. */
|
|
4462
|
+
rejoinAttempts = 0;
|
|
4463
|
+
rejoinTimer;
|
|
4464
|
+
lastRejoinAt = 0;
|
|
4465
|
+
/**
|
|
4466
|
+
* Re-join after the server refused this channel for a reason a retry can
|
|
4467
|
+
* change: it could not check permissions at that moment, or it has no record
|
|
4468
|
+
* of the join (a join that was itself refused, so every broadcast after it
|
|
4469
|
+
* came back "not a member"). The join was fire-and-forget and `joined` was
|
|
4470
|
+
* already set, so nothing else would ever send it again. Backs off 1, 2, 4…
|
|
4471
|
+
* up to 30 seconds, one re-join at a time.
|
|
4472
|
+
*/
|
|
4473
|
+
scheduleRejoin() {
|
|
4474
|
+
if (this.rejoinTimer || !this.joined) return;
|
|
4475
|
+
if (Date.now() - this.lastRejoinAt > 6e4) this.rejoinAttempts = 0;
|
|
4476
|
+
const delay = Math.min(3e4, 1e3 * 2 ** this.rejoinAttempts++);
|
|
4477
|
+
this.rejoinTimer = setTimeout(() => {
|
|
4478
|
+
this.rejoinTimer = void 0;
|
|
4479
|
+
this.lastRejoinAt = Date.now();
|
|
4480
|
+
if (this.joined) this.rejoin();
|
|
4481
|
+
}, delay);
|
|
4482
|
+
}
|
|
4106
4483
|
async rejoin() {
|
|
4107
4484
|
try {
|
|
4108
4485
|
await this.send("join_channel");
|
|
@@ -4290,6 +4667,10 @@ var RebaseRealtimeChannel = class {
|
|
|
4290
4667
|
/** Leave the channel and release every listener and timer. */
|
|
4291
4668
|
async leave() {
|
|
4292
4669
|
this.stopHeartbeat();
|
|
4670
|
+
if (this.rejoinTimer) {
|
|
4671
|
+
clearTimeout(this.rejoinTimer);
|
|
4672
|
+
this.rejoinTimer = void 0;
|
|
4673
|
+
}
|
|
4293
4674
|
this.trackedState = null;
|
|
4294
4675
|
this.presences = {};
|
|
4295
4676
|
this.presenceHandlers.clear();
|
|
@@ -4433,6 +4814,7 @@ var RebaseRealtimeChannel = class {
|
|
|
4433
4814
|
const asObject = typeof raw === "object" ? raw : void 0;
|
|
4434
4815
|
const text = asObject?.message ?? (typeof raw === "string" ? raw : void 0) ?? message.error ?? "The server refused a channel operation.";
|
|
4435
4816
|
this.emitError(new RebaseApiError$1(text, { ...asObject?.code ? { code: asObject.code } : {} }));
|
|
4817
|
+
if (this.joined && rejoinsAfter(asObject?.code, text)) this.scheduleRejoin();
|
|
4436
4818
|
break;
|
|
4437
4819
|
}
|
|
4438
4820
|
}
|
|
@@ -4507,6 +4889,16 @@ var RebaseRealtimeChannel = class {
|
|
|
4507
4889
|
for (const handler of this.presenceHandlers) handler(snapshot, diff);
|
|
4508
4890
|
}
|
|
4509
4891
|
};
|
|
4892
|
+
/**
|
|
4893
|
+
* Whether a channel refusal is one a re-join can recover from: the server's
|
|
4894
|
+
* auth store could not answer (`ROLE_LOOKUP_FAILED`, `DATABASE_UNAVAILABLE`), or
|
|
4895
|
+
* it no longer counts this client a member. A channel the client may not use
|
|
4896
|
+
* (any other `CHANNEL_FORBIDDEN`) is not retried.
|
|
4897
|
+
*/
|
|
4898
|
+
function rejoinsAfter(code, message) {
|
|
4899
|
+
if (code === "ROLE_LOOKUP_FAILED" || code === "DATABASE_UNAVAILABLE") return true;
|
|
4900
|
+
return code === "CHANNEL_FORBIDDEN" && /not a member/i.test(message);
|
|
4901
|
+
}
|
|
4510
4902
|
//#endregion
|
|
4511
4903
|
//#region src/offline-lazy.ts
|
|
4512
4904
|
/**
|
|
@@ -4728,7 +5120,7 @@ function deriveWebSocketUrl(baseUrl) {
|
|
|
4728
5120
|
return toWsProtocol(baseUrl);
|
|
4729
5121
|
}
|
|
4730
5122
|
function createRebaseClient(options) {
|
|
4731
|
-
const transport = createTransport(options, { credentialOutOfBand: options.auth
|
|
5123
|
+
const transport = createTransport(options, { credentialOutOfBand: resolveAuthFlowMode(options.auth) === "cookie" });
|
|
4732
5124
|
const auth = createAuth(transport, options.auth);
|
|
4733
5125
|
const admin = createAdmin(transport, options.admin);
|
|
4734
5126
|
const cron = createCron(transport, options.cron);
|
|
@@ -4776,6 +5168,7 @@ function createRebaseClient(options) {
|
|
|
4776
5168
|
if (resolvedWsUrl) {
|
|
4777
5169
|
ws = new RebaseWebSocketClient({
|
|
4778
5170
|
websocketUrl: resolvedWsUrl,
|
|
5171
|
+
affinity: options.realtime && options.realtime !== true ? options.realtime.affinity : void 0,
|
|
4779
5172
|
getAuthToken: () => transport.resolveToken(),
|
|
4780
5173
|
onUnauthorized: () => onUnauthorized(),
|
|
4781
5174
|
impersonate: options.impersonate,
|
|
@@ -4957,24 +5350,26 @@ function createRebaseClient(options) {
|
|
|
4957
5350
|
createStorageSource,
|
|
4958
5351
|
fetchStorageSources,
|
|
4959
5352
|
ws,
|
|
4960
|
-
realtime: {
|
|
4961
|
-
|
|
4962
|
-
|
|
4963
|
-
|
|
4964
|
-
|
|
4965
|
-
|
|
4966
|
-
|
|
4967
|
-
|
|
4968
|
-
|
|
4969
|
-
channel: (name, options) => {
|
|
4970
|
-
|
|
4971
|
-
|
|
4972
|
-
|
|
4973
|
-
|
|
4974
|
-
|
|
4975
|
-
|
|
4976
|
-
|
|
4977
|
-
|
|
5353
|
+
realtime: {
|
|
5354
|
+
/**
|
|
5355
|
+
* Join a broadcast/presence channel.
|
|
5356
|
+
*
|
|
5357
|
+
* Repeated calls with the same name return the same channel, so
|
|
5358
|
+
* separate components can attach handlers without each opening its
|
|
5359
|
+
* own membership — and `leave()` from one would otherwise silently
|
|
5360
|
+
* cut off the others.
|
|
5361
|
+
*/
|
|
5362
|
+
channel: (name, options) => {
|
|
5363
|
+
if (!ws) throw new RebaseClientError(realtimeUnreachable ? `Realtime is enabled but ${unreachableReason}` : "Realtime is disabled on this client (realtime: false), so channels are unavailable.", { code: "REALTIME_DISABLED" });
|
|
5364
|
+
let existing = realtimeChannels.get(name);
|
|
5365
|
+
if (!existing) {
|
|
5366
|
+
existing = new RebaseRealtimeChannel(name, ws, options);
|
|
5367
|
+
realtimeChannels.set(name, existing);
|
|
5368
|
+
} else if (options?.history) existing.enableHistory();
|
|
5369
|
+
return existing;
|
|
5370
|
+
},
|
|
5371
|
+
setAffinity: (key) => ws?.setAffinity(key)
|
|
5372
|
+
},
|
|
4978
5373
|
/**
|
|
4979
5374
|
* Release every handle that can keep a process alive — see the
|
|
4980
5375
|
* `close` docblock on the client interface.
|
|
@@ -5062,6 +5457,6 @@ channel: (name, options) => {
|
|
|
5062
5457
|
};
|
|
5063
5458
|
}
|
|
5064
5459
|
//#endregion
|
|
5065
|
-
export { MemoryOfflineStore, RebaseApiError, RebaseClientError, RebasePaginationError, RebaseRealtimeChannel, RebaseWebSocketClient, STORAGE_REFERENCE_SCHEME, and, cond, createCookieStorage, createMemoryStorage, createRebaseClient, etagOf, isOfflineError, isStorageReference, not, or, parseStorageReference, resolveStorageReferences, storageReference, storageReferencesForDownloadUrls, storageTargetOfDownloadUrl, storageTargetsInText };
|
|
5460
|
+
export { APPLE_JS_SDK_URL, MemoryOfflineStore, RebaseApiError, RebaseClientError, RebasePaginationError, RebaseRealtimeChannel, RebaseWebSocketClient, STORAGE_REFERENCE_SCHEME, and, cond, createCookieStorage, createMemoryStorage, createRebaseClient, etagOf, isOfflineError, isStorageReference, not, or, parseStorageReference, preloadAppleSignIn, requestAppleAuthorization, resolveStorageReferences, storageReference, storageReferencesForDownloadUrls, storageTargetOfDownloadUrl, storageTargetsInText };
|
|
5066
5461
|
|
|
5067
5462
|
//# sourceMappingURL=index.es.js.map
|