@spacelr/sdk 0.18.4 → 0.19.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/README.md CHANGED
@@ -127,6 +127,48 @@ Notes:
127
127
  consumers performing the ceremony — Node/server usage of the SDK never
128
128
  needs it.
129
129
 
130
+ ## Push subscriptions and the session
131
+
132
+ A push subscription is bound to the session it was registered under. When a
133
+ session is revoked remotely ("sign out this device", "sign out all other
134
+ devices", removing a passkey), the server deactivates that device's push
135
+ subscription, so a lost or stolen device stops showing notifications.
136
+
137
+ The SDK keeps this device's subscription in sync for you (`autoManagePush`,
138
+ default `true`):
139
+
140
+ - After every sign-in, it re-registers the device's last push registration
141
+ for the signed-in user and their new session. Signing in over a live
142
+ session (user B without a logout of user A) first unregisters the device for
143
+ the outgoing session, so its pushes move from A to B.
144
+ - `auth.logout()` first unregisters this device's subscription, while the
145
+ session is still valid, so a signed-out device stops receiving the user's
146
+ pushes. Logout waits at most 3 seconds for this.
147
+ - Calling `notifications.unsubscribe()` / `unsubscribeById()` for this device
148
+ turns push off for good: the SDK no longer re-registers it, even if the
149
+ server call fails.
150
+ - Within a client instance, all register/unregister calls run in call order,
151
+ so a late re-register never lands after a logout's unregister. If that
152
+ unregister hangs, the next sign-in's re-register waits for it (at most the
153
+ client's request `timeout`).
154
+
155
+ Everything here is best-effort and never fails a sign-in or logout. If the
156
+ unregister cannot reach the server (offline logout), the device keeps the
157
+ previous user's subscription. A later registration for another user on that
158
+ device is then refused (`DEVICE_ALREADY_REGISTERED`) until the previous user
159
+ deletes that subscription, e.g. via `getSubscriptions()` + `unsubscribeById()`
160
+ from another device. A remote session revoke only deactivates it.
161
+
162
+ The registration is remembered in `localStorage` (per project), falling back
163
+ to memory. With `createClient({ ..., autoManagePush: false })` nothing changes
164
+ automatically, and `subscribe()` / `unsubscribe()` are entirely up to the app.
165
+ In that case, call `subscribe()` after every sign-in yourself.
166
+
167
+ Apps that sign in or out by setting tokens directly (`setTokens()` /
168
+ `clearTokens()`) bypass the automatic handling. They call
169
+ `notifications.resubscribeAfterLogin()` after `setTokens()`, and
170
+ `notifications.unsubscribeBeforeLogout()` before `clearTokens()`.
171
+
130
172
  ## Requirements
131
173
 
132
174
  - Node.js >= 18
package/dist/index.d.mts CHANGED
@@ -380,6 +380,14 @@ interface SpacelrClientConfig {
380
380
  tokenStorage?: TokenStorage;
381
381
  /** Buffer in seconds before token expiry to trigger auto-refresh (default: 60) */
382
382
  refreshBufferSeconds?: number;
383
+ /**
384
+ * Keep this device's push subscription in sync with the session (default:
385
+ * true). After every login the SDK re-registers the device's last push
386
+ * registration for the signed-in user; `auth.logout()` unregisters it first.
387
+ * Set to false to manage `notifications.subscribe()` / `unsubscribe()`
388
+ * entirely yourself.
389
+ */
390
+ autoManagePush?: boolean;
383
391
  }
384
392
 
385
393
  interface FileInfo {
@@ -1080,7 +1088,19 @@ declare class AuthModule {
1080
1088
  private stateListeners;
1081
1089
  private unsubscribeAuthLost;
1082
1090
  private lastEmittedState;
1083
- constructor(http: HttpClient, tokenManager: TokenManager, config: SpacelrClientConfig);
1091
+ private beforeLogout?;
1092
+ private afterSignIn?;
1093
+ constructor(http: HttpClient, tokenManager: TokenManager, config: SpacelrClientConfig,
1094
+ /**
1095
+ * Wired by `createClient`. `beforeLogout` runs while the session is still
1096
+ * valid during `logout()`; `afterSignIn` runs after EVERY sign-in, even
1097
+ * one that does not change the auth state, because each sign-in starts a
1098
+ * new session.
1099
+ */
1100
+ hooks?: {
1101
+ beforeLogout?: () => Promise<void>;
1102
+ afterSignIn?: () => Promise<void>;
1103
+ });
1084
1104
  /**
1085
1105
  * Returns true if a non-expired access token is currently in storage.
1086
1106
  * Does NOT make a network request — safe for route guards and other
@@ -1122,6 +1142,13 @@ declare class AuthModule {
1122
1142
  * onAuthLost subscription. Idempotent — safe to call more than once.
1123
1143
  */
1124
1144
  dispose(): void;
1145
+ /**
1146
+ * Install the tokens of a completed sign-in. Signing in over a live session
1147
+ * (e.g. user B over user A without a logout) first runs `beforeLogout` with
1148
+ * the outgoing session's still-valid token, so this device's push leaves
1149
+ * the previous user before it is re-registered for the new one.
1150
+ */
1151
+ private installSession;
1125
1152
  private emitState;
1126
1153
  login(params: LoginParams): Promise<LoginResponse>;
1127
1154
  register(params: RegisterParams): Promise<RegisterResponse>;
@@ -2104,11 +2131,27 @@ interface PushSubscriptionInfo {
2104
2131
  interface VapidKeyResponse {
2105
2132
  publicKey: string;
2106
2133
  }
2134
+ type PushSubscriptionInput = {
2135
+ platform: PushPlatform;
2136
+ endpoint?: string;
2137
+ keys?: {
2138
+ p256dh: string;
2139
+ auth: string;
2140
+ };
2141
+ deviceToken?: string;
2142
+ };
2143
+ interface NotificationsModuleOptions {
2144
+ /** Scopes the remembered push registration to one project. */
2145
+ projectId?: string;
2146
+ }
2107
2147
  declare class NotificationsModule {
2108
2148
  private http;
2109
2149
  private customDeviceId;
2110
2150
  private customDeviceName;
2111
- constructor(http: HttpClient);
2151
+ private readonly registrationKey;
2152
+ private memoryRegistration;
2153
+ private pushQueue;
2154
+ constructor(http: HttpClient, options?: NotificationsModuleOptions);
2112
2155
  /** Set a custom device ID (e.g. from Capacitor Preferences for persistence beyond localStorage) */
2113
2156
  setDeviceId(id: string): void;
2114
2157
  /** Set a custom device name (e.g. "iOS App", "macOS - Chrome") */
@@ -2121,17 +2164,20 @@ declare class NotificationsModule {
2121
2164
  private detectDeviceName;
2122
2165
  /** Get the VAPID public key for Web Push setup */
2123
2166
  getVapidPublicKey(): Promise<VapidKeyResponse>;
2124
- /** Register a push subscription (web, android, ios, or web-fcm) */
2125
- subscribe(subscription: {
2126
- platform: PushPlatform;
2127
- endpoint?: string;
2128
- keys?: {
2129
- p256dh: string;
2130
- auth: string;
2131
- };
2132
- deviceToken?: string;
2133
- }, deviceName?: string): Promise<PushSubscriptionInfo>;
2134
- /** Unregister a push subscription */
2167
+ /**
2168
+ * Register a push subscription (web, android, ios, or web-fcm).
2169
+ *
2170
+ * The SDK remembers this device's registration. Unless the client was
2171
+ * created with `autoManagePush: false`, it re-registers it after every
2172
+ * login and unregisters it on `auth.logout()`, so the subscription always
2173
+ * belongs to the signed-in user's current session.
2174
+ */
2175
+ subscribe(subscription: PushSubscriptionInput, deviceName?: string): Promise<PushSubscriptionInfo>;
2176
+ private register;
2177
+ /**
2178
+ * Unregister a push subscription. Unregistering this device's own
2179
+ * subscription also stops the SDK from re-registering it after a login.
2180
+ */
2135
2181
  unsubscribe(platform: PushPlatform, identifier: string): Promise<{
2136
2182
  deleted: boolean;
2137
2183
  }>;
@@ -2144,6 +2190,30 @@ declare class NotificationsModule {
2144
2190
  unsubscribeById(subscriptionId: string): Promise<{
2145
2191
  deleted: boolean;
2146
2192
  }>;
2193
+ /**
2194
+ * Re-register this device's remembered subscription for the user who just
2195
+ * signed in, binding it to their new session (#1003). The client calls this
2196
+ * after every sign-in unless `autoManagePush` is false; call it yourself
2197
+ * after signing in via `setTokens()`. No-op when this device never
2198
+ * subscribed. Best-effort: a failure leaves the device without push until
2199
+ * the app subscribes again.
2200
+ */
2201
+ resubscribeAfterLogin(): Promise<void>;
2202
+ /**
2203
+ * Unregister this device's subscription while the session is still valid,
2204
+ * so a signed-out device stops receiving the user's pushes. The remembered
2205
+ * registration is kept, so the next sign-in re-registers it. `auth.logout()`
2206
+ * calls this first unless `autoManagePush` is false; call it yourself before
2207
+ * clearing tokens via `clearTokens()`. Best-effort.
2208
+ */
2209
+ unsubscribeBeforeLogout(): Promise<void>;
2210
+ private enqueue;
2211
+ private deleteSubscription;
2212
+ /** The value `unsubscribe()` identifies a subscription by: endpoint for web, token otherwise. */
2213
+ private static identifierOf;
2214
+ private static isStoredRegistration;
2215
+ private loadRegistration;
2216
+ private saveRegistration;
2147
2217
  /** Get all subscriptions for the current user */
2148
2218
  getSubscriptions(): Promise<PushSubscriptionInfo[]>;
2149
2219
  /**
package/dist/index.d.ts CHANGED
@@ -380,6 +380,14 @@ interface SpacelrClientConfig {
380
380
  tokenStorage?: TokenStorage;
381
381
  /** Buffer in seconds before token expiry to trigger auto-refresh (default: 60) */
382
382
  refreshBufferSeconds?: number;
383
+ /**
384
+ * Keep this device's push subscription in sync with the session (default:
385
+ * true). After every login the SDK re-registers the device's last push
386
+ * registration for the signed-in user; `auth.logout()` unregisters it first.
387
+ * Set to false to manage `notifications.subscribe()` / `unsubscribe()`
388
+ * entirely yourself.
389
+ */
390
+ autoManagePush?: boolean;
383
391
  }
384
392
 
385
393
  interface FileInfo {
@@ -1080,7 +1088,19 @@ declare class AuthModule {
1080
1088
  private stateListeners;
1081
1089
  private unsubscribeAuthLost;
1082
1090
  private lastEmittedState;
1083
- constructor(http: HttpClient, tokenManager: TokenManager, config: SpacelrClientConfig);
1091
+ private beforeLogout?;
1092
+ private afterSignIn?;
1093
+ constructor(http: HttpClient, tokenManager: TokenManager, config: SpacelrClientConfig,
1094
+ /**
1095
+ * Wired by `createClient`. `beforeLogout` runs while the session is still
1096
+ * valid during `logout()`; `afterSignIn` runs after EVERY sign-in, even
1097
+ * one that does not change the auth state, because each sign-in starts a
1098
+ * new session.
1099
+ */
1100
+ hooks?: {
1101
+ beforeLogout?: () => Promise<void>;
1102
+ afterSignIn?: () => Promise<void>;
1103
+ });
1084
1104
  /**
1085
1105
  * Returns true if a non-expired access token is currently in storage.
1086
1106
  * Does NOT make a network request — safe for route guards and other
@@ -1122,6 +1142,13 @@ declare class AuthModule {
1122
1142
  * onAuthLost subscription. Idempotent — safe to call more than once.
1123
1143
  */
1124
1144
  dispose(): void;
1145
+ /**
1146
+ * Install the tokens of a completed sign-in. Signing in over a live session
1147
+ * (e.g. user B over user A without a logout) first runs `beforeLogout` with
1148
+ * the outgoing session's still-valid token, so this device's push leaves
1149
+ * the previous user before it is re-registered for the new one.
1150
+ */
1151
+ private installSession;
1125
1152
  private emitState;
1126
1153
  login(params: LoginParams): Promise<LoginResponse>;
1127
1154
  register(params: RegisterParams): Promise<RegisterResponse>;
@@ -2104,11 +2131,27 @@ interface PushSubscriptionInfo {
2104
2131
  interface VapidKeyResponse {
2105
2132
  publicKey: string;
2106
2133
  }
2134
+ type PushSubscriptionInput = {
2135
+ platform: PushPlatform;
2136
+ endpoint?: string;
2137
+ keys?: {
2138
+ p256dh: string;
2139
+ auth: string;
2140
+ };
2141
+ deviceToken?: string;
2142
+ };
2143
+ interface NotificationsModuleOptions {
2144
+ /** Scopes the remembered push registration to one project. */
2145
+ projectId?: string;
2146
+ }
2107
2147
  declare class NotificationsModule {
2108
2148
  private http;
2109
2149
  private customDeviceId;
2110
2150
  private customDeviceName;
2111
- constructor(http: HttpClient);
2151
+ private readonly registrationKey;
2152
+ private memoryRegistration;
2153
+ private pushQueue;
2154
+ constructor(http: HttpClient, options?: NotificationsModuleOptions);
2112
2155
  /** Set a custom device ID (e.g. from Capacitor Preferences for persistence beyond localStorage) */
2113
2156
  setDeviceId(id: string): void;
2114
2157
  /** Set a custom device name (e.g. "iOS App", "macOS - Chrome") */
@@ -2121,17 +2164,20 @@ declare class NotificationsModule {
2121
2164
  private detectDeviceName;
2122
2165
  /** Get the VAPID public key for Web Push setup */
2123
2166
  getVapidPublicKey(): Promise<VapidKeyResponse>;
2124
- /** Register a push subscription (web, android, ios, or web-fcm) */
2125
- subscribe(subscription: {
2126
- platform: PushPlatform;
2127
- endpoint?: string;
2128
- keys?: {
2129
- p256dh: string;
2130
- auth: string;
2131
- };
2132
- deviceToken?: string;
2133
- }, deviceName?: string): Promise<PushSubscriptionInfo>;
2134
- /** Unregister a push subscription */
2167
+ /**
2168
+ * Register a push subscription (web, android, ios, or web-fcm).
2169
+ *
2170
+ * The SDK remembers this device's registration. Unless the client was
2171
+ * created with `autoManagePush: false`, it re-registers it after every
2172
+ * login and unregisters it on `auth.logout()`, so the subscription always
2173
+ * belongs to the signed-in user's current session.
2174
+ */
2175
+ subscribe(subscription: PushSubscriptionInput, deviceName?: string): Promise<PushSubscriptionInfo>;
2176
+ private register;
2177
+ /**
2178
+ * Unregister a push subscription. Unregistering this device's own
2179
+ * subscription also stops the SDK from re-registering it after a login.
2180
+ */
2135
2181
  unsubscribe(platform: PushPlatform, identifier: string): Promise<{
2136
2182
  deleted: boolean;
2137
2183
  }>;
@@ -2144,6 +2190,30 @@ declare class NotificationsModule {
2144
2190
  unsubscribeById(subscriptionId: string): Promise<{
2145
2191
  deleted: boolean;
2146
2192
  }>;
2193
+ /**
2194
+ * Re-register this device's remembered subscription for the user who just
2195
+ * signed in, binding it to their new session (#1003). The client calls this
2196
+ * after every sign-in unless `autoManagePush` is false; call it yourself
2197
+ * after signing in via `setTokens()`. No-op when this device never
2198
+ * subscribed. Best-effort: a failure leaves the device without push until
2199
+ * the app subscribes again.
2200
+ */
2201
+ resubscribeAfterLogin(): Promise<void>;
2202
+ /**
2203
+ * Unregister this device's subscription while the session is still valid,
2204
+ * so a signed-out device stops receiving the user's pushes. The remembered
2205
+ * registration is kept, so the next sign-in re-registers it. `auth.logout()`
2206
+ * calls this first unless `autoManagePush` is false; call it yourself before
2207
+ * clearing tokens via `clearTokens()`. Best-effort.
2208
+ */
2209
+ unsubscribeBeforeLogout(): Promise<void>;
2210
+ private enqueue;
2211
+ private deleteSubscription;
2212
+ /** The value `unsubscribe()` identifies a subscription by: endpoint for web, token otherwise. */
2213
+ private static identifierOf;
2214
+ private static isStoredRegistration;
2215
+ private loadRegistration;
2216
+ private saveRegistration;
2147
2217
  /** Get all subscriptions for the current user */
2148
2218
  getSubscriptions(): Promise<PushSubscriptionInfo[]>;
2149
2219
  /**
package/dist/index.js CHANGED
@@ -440,6 +440,9 @@ var HttpClient = class {
440
440
  };
441
441
 
442
442
  // libs/sdk/src/core/token-storage.ts
443
+ function isStoredTokens(value) {
444
+ return typeof value === "object" && value !== null && "accessToken" in value && typeof value.accessToken === "string";
445
+ }
443
446
  var MemoryTokenStorage = class {
444
447
  constructor() {
445
448
  this.tokens = null;
@@ -462,7 +465,8 @@ var BrowserTokenStorage = class {
462
465
  try {
463
466
  const raw = localStorage.getItem(this.storageKey);
464
467
  if (!raw) return null;
465
- return JSON.parse(raw);
468
+ const parsed = JSON.parse(raw);
469
+ return isStoredTokens(parsed) ? parsed : null;
466
470
  } catch {
467
471
  return null;
468
472
  }
@@ -1963,12 +1967,14 @@ function mapProfile(u) {
1963
1967
  };
1964
1968
  }
1965
1969
  var AuthModule = class _AuthModule {
1966
- constructor(http, tokenManager, config) {
1970
+ constructor(http, tokenManager, config, hooks = {}) {
1967
1971
  this.stateListeners = /* @__PURE__ */ new Set();
1968
1972
  this.lastEmittedState = null;
1969
1973
  this.http = http;
1970
1974
  this.tokenManager = tokenManager;
1971
1975
  this.config = config;
1976
+ this.beforeLogout = hooks.beforeLogout;
1977
+ this.afterSignIn = hooks.afterSignIn;
1972
1978
  this.tokenManager.setRefreshCallback(async (refreshToken) => {
1973
1979
  const result = await this.refresh(refreshToken);
1974
1980
  const expiresAt = result.expires_in ? Math.floor(Date.now() / 1e3) + result.expires_in : void 0;
@@ -2042,8 +2048,26 @@ var AuthModule = class _AuthModule {
2042
2048
  };
2043
2049
  this.stateListeners.clear();
2044
2050
  this.lastEmittedState = null;
2051
+ this.beforeLogout = void 0;
2052
+ this.afterSignIn = void 0;
2053
+ }
2054
+ /**
2055
+ * Install the tokens of a completed sign-in. Signing in over a live session
2056
+ * (e.g. user B over user A without a logout) first runs `beforeLogout` with
2057
+ * the outgoing session's still-valid token, so this device's push leaves
2058
+ * the previous user before it is re-registered for the new one.
2059
+ */
2060
+ async installSession(tokens) {
2061
+ if (this.beforeLogout && await this.tokenManager.getStoredTokens()) {
2062
+ await this.beforeLogout().catch(() => void 0);
2063
+ }
2064
+ await this.tokenManager.setTokens(tokens);
2065
+ this.emitState("authenticated");
2045
2066
  }
2046
2067
  emitState(state) {
2068
+ if (state === "authenticated") {
2069
+ this.afterSignIn?.().catch(() => void 0);
2070
+ }
2047
2071
  if (state === this.lastEmittedState) return;
2048
2072
  this.lastEmittedState = state;
2049
2073
  for (const listener of this.stateListeners) {
@@ -2093,6 +2117,7 @@ var AuthModule = class _AuthModule {
2093
2117
  return mapProfile(data.user ?? data);
2094
2118
  }
2095
2119
  async logout() {
2120
+ await this.beforeLogout?.().catch(() => void 0);
2096
2121
  try {
2097
2122
  await this.http.request({
2098
2123
  method: "POST",
@@ -2180,12 +2205,11 @@ var AuthModule = class _AuthModule {
2180
2205
  body
2181
2206
  });
2182
2207
  const expiresAt = response.expires_in ? Math.floor(Date.now() / 1e3) + response.expires_in : void 0;
2183
- await this.tokenManager.setTokens({
2208
+ await this.installSession({
2184
2209
  accessToken: response.access_token,
2185
2210
  refreshToken: response.refresh_token,
2186
2211
  expiresAt
2187
2212
  });
2188
- this.emitState("authenticated");
2189
2213
  return response;
2190
2214
  }
2191
2215
  async generatePKCE() {
@@ -2431,12 +2455,11 @@ var AuthModule = class _AuthModule {
2431
2455
  }
2432
2456
  async storeTokensFromLogin(response) {
2433
2457
  const expiresAt = response.expires_in ? Math.floor(Date.now() / 1e3) + response.expires_in : void 0;
2434
- await this.tokenManager.setTokens({
2458
+ await this.installSession({
2435
2459
  accessToken: response.access_token,
2436
2460
  refreshToken: response.refresh_token,
2437
2461
  expiresAt
2438
2462
  });
2439
- this.emitState("authenticated");
2440
2463
  }
2441
2464
  // ─── Recover-with-phrase (#784) ───
2442
2465
  // For an email-less passkey account (#780) that has lost every passkey. The
@@ -2667,12 +2690,11 @@ var AuthModule = class _AuthModule {
2667
2690
  async storeTokensFromRegister(response) {
2668
2691
  if (!response.access_token) return;
2669
2692
  const expiresAt = response.expires_in ? Math.floor(Date.now() / 1e3) + response.expires_in : void 0;
2670
- await this.tokenManager.setTokens({
2693
+ await this.installSession({
2671
2694
  accessToken: response.access_token,
2672
2695
  refreshToken: response.refresh_token,
2673
2696
  expiresAt
2674
2697
  });
2675
- this.emitState("authenticated");
2676
2698
  }
2677
2699
  };
2678
2700
 
@@ -4160,11 +4182,20 @@ var DatabaseModule = class {
4160
4182
 
4161
4183
  // libs/sdk/src/modules/notifications.module.ts
4162
4184
  var DEVICE_ID_KEY = "spacelr_device_id";
4163
- var NotificationsModule = class {
4164
- constructor(http) {
4185
+ var REGISTRATION_KEY_PREFIX = "spacelr_push_registration:";
4186
+ var PUSH_LOGOUT_TIMEOUT_MS = 3e3;
4187
+ var NotificationsModule = class _NotificationsModule {
4188
+ constructor(http, options = {}) {
4165
4189
  this.http = http;
4166
4190
  this.customDeviceId = null;
4167
4191
  this.customDeviceName = null;
4192
+ // Fallback when localStorage is unavailable or refuses writes.
4193
+ this.memoryRegistration = null;
4194
+ // Push register/unregister calls run strictly in call order, so a late
4195
+ // re-register can never land after the logout's unregister (or overwrite a
4196
+ // newer registration the app just made).
4197
+ this.pushQueue = Promise.resolve();
4198
+ this.registrationKey = `${REGISTRATION_KEY_PREFIX}${options.projectId ?? "default"}`;
4168
4199
  }
4169
4200
  /** Set a custom device ID (e.g. from Capacitor Preferences for persistence beyond localStorage) */
4170
4201
  setDeviceId(id) {
@@ -4178,12 +4209,16 @@ var NotificationsModule = class {
4178
4209
  getDeviceId() {
4179
4210
  if (this.customDeviceId) return this.customDeviceId;
4180
4211
  if (typeof localStorage === "undefined") return void 0;
4181
- let id = localStorage.getItem(DEVICE_ID_KEY);
4182
- if (!id) {
4183
- id = crypto.randomUUID();
4184
- localStorage.setItem(DEVICE_ID_KEY, id);
4212
+ try {
4213
+ let id = localStorage.getItem(DEVICE_ID_KEY);
4214
+ if (!id) {
4215
+ id = crypto.randomUUID();
4216
+ localStorage.setItem(DEVICE_ID_KEY, id);
4217
+ }
4218
+ return id;
4219
+ } catch {
4220
+ return void 0;
4185
4221
  }
4186
- return id;
4187
4222
  }
4188
4223
  /** Get device name: custom name > auto-detected from user agent > undefined */
4189
4224
  getDeviceName() {
@@ -4216,9 +4251,19 @@ var NotificationsModule = class {
4216
4251
  authenticated: true
4217
4252
  });
4218
4253
  }
4219
- /** Register a push subscription (web, android, ios, or web-fcm) */
4254
+ /**
4255
+ * Register a push subscription (web, android, ios, or web-fcm).
4256
+ *
4257
+ * The SDK remembers this device's registration. Unless the client was
4258
+ * created with `autoManagePush: false`, it re-registers it after every
4259
+ * login and unregisters it on `auth.logout()`, so the subscription always
4260
+ * belongs to the signed-in user's current session.
4261
+ */
4220
4262
  async subscribe(subscription, deviceName) {
4221
- return this.http.request({
4263
+ return this.enqueue(() => this.register(subscription, deviceName));
4264
+ }
4265
+ async register(subscription, deviceName) {
4266
+ const info = await this.http.request({
4222
4267
  method: "POST",
4223
4268
  path: "/notifications/subscribe",
4224
4269
  body: {
@@ -4228,20 +4273,23 @@ var NotificationsModule = class {
4228
4273
  },
4229
4274
  authenticated: true
4230
4275
  });
4276
+ this.saveRegistration({ id: info?.id, subscription, deviceName });
4277
+ return info;
4231
4278
  }
4232
- /** Unregister a push subscription */
4279
+ /**
4280
+ * Unregister a push subscription. Unregistering this device's own
4281
+ * subscription also stops the SDK from re-registering it after a login.
4282
+ */
4233
4283
  async unsubscribe(platform, identifier) {
4234
- const body = { platform };
4235
- if (platform === "web") {
4236
- body["endpoint"] = identifier;
4237
- } else {
4238
- body["deviceToken"] = identifier;
4239
- }
4240
- return this.http.request({
4241
- method: "DELETE",
4242
- path: "/notifications/subscribe",
4243
- body,
4244
- authenticated: true
4284
+ return this.enqueue(async () => {
4285
+ try {
4286
+ return await this.deleteSubscription(platform, identifier);
4287
+ } finally {
4288
+ const stored = this.loadRegistration();
4289
+ if (stored?.subscription.platform === platform && _NotificationsModule.identifierOf(stored.subscription) === identifier) {
4290
+ this.saveRegistration(null);
4291
+ }
4292
+ }
4245
4293
  });
4246
4294
  }
4247
4295
  /**
@@ -4251,12 +4299,114 @@ var NotificationsModule = class {
4251
4299
  * by the listing and so cannot be passed to {@link unsubscribe}).
4252
4300
  */
4253
4301
  async unsubscribeById(subscriptionId) {
4302
+ return this.enqueue(async () => {
4303
+ try {
4304
+ return await this.http.request({
4305
+ method: "DELETE",
4306
+ path: `/notifications/subscriptions/${encodeURIComponent(subscriptionId)}`,
4307
+ authenticated: true
4308
+ });
4309
+ } finally {
4310
+ if (this.loadRegistration()?.id === subscriptionId) {
4311
+ this.saveRegistration(null);
4312
+ }
4313
+ }
4314
+ });
4315
+ }
4316
+ /**
4317
+ * Re-register this device's remembered subscription for the user who just
4318
+ * signed in, binding it to their new session (#1003). The client calls this
4319
+ * after every sign-in unless `autoManagePush` is false; call it yourself
4320
+ * after signing in via `setTokens()`. No-op when this device never
4321
+ * subscribed. Best-effort: a failure leaves the device without push until
4322
+ * the app subscribes again.
4323
+ */
4324
+ async resubscribeAfterLogin() {
4325
+ await this.enqueue(async () => {
4326
+ const stored = this.loadRegistration();
4327
+ if (!stored) return;
4328
+ try {
4329
+ await this.register(stored.subscription, stored.deviceName);
4330
+ } catch (error) {
4331
+ console.warn("[spacelr] Could not re-register push after login:", error);
4332
+ }
4333
+ });
4334
+ }
4335
+ /**
4336
+ * Unregister this device's subscription while the session is still valid,
4337
+ * so a signed-out device stops receiving the user's pushes. The remembered
4338
+ * registration is kept, so the next sign-in re-registers it. `auth.logout()`
4339
+ * calls this first unless `autoManagePush` is false; call it yourself before
4340
+ * clearing tokens via `clearTokens()`. Best-effort.
4341
+ */
4342
+ async unsubscribeBeforeLogout() {
4343
+ const unregistered = this.enqueue(async () => {
4344
+ const stored = this.loadRegistration();
4345
+ if (!stored) return;
4346
+ await this.deleteSubscription(
4347
+ stored.subscription.platform,
4348
+ _NotificationsModule.identifierOf(stored.subscription)
4349
+ ).catch(() => void 0);
4350
+ });
4351
+ let timer;
4352
+ await Promise.race([
4353
+ unregistered,
4354
+ new Promise((resolve) => {
4355
+ timer = setTimeout(resolve, PUSH_LOGOUT_TIMEOUT_MS);
4356
+ })
4357
+ ]);
4358
+ clearTimeout(timer);
4359
+ }
4360
+ enqueue(op) {
4361
+ const run = this.pushQueue.then(op, op);
4362
+ this.pushQueue = run.catch(() => void 0);
4363
+ return run;
4364
+ }
4365
+ deleteSubscription(platform, identifier) {
4366
+ const body = { platform };
4367
+ if (platform === "web") {
4368
+ body["endpoint"] = identifier;
4369
+ } else {
4370
+ body["deviceToken"] = identifier;
4371
+ }
4254
4372
  return this.http.request({
4255
4373
  method: "DELETE",
4256
- path: `/notifications/subscriptions/${encodeURIComponent(subscriptionId)}`,
4374
+ path: "/notifications/subscribe",
4375
+ body,
4257
4376
  authenticated: true
4258
4377
  });
4259
4378
  }
4379
+ /** The value `unsubscribe()` identifies a subscription by: endpoint for web, token otherwise. */
4380
+ static identifierOf(subscription) {
4381
+ return (subscription.platform === "web" ? subscription.endpoint : subscription.deviceToken) ?? "";
4382
+ }
4383
+ static isStoredRegistration(value) {
4384
+ if (typeof value !== "object" || value === null) return false;
4385
+ const subscription = value.subscription;
4386
+ return typeof subscription === "object" && subscription !== null && typeof subscription.platform === "string";
4387
+ }
4388
+ loadRegistration() {
4389
+ if (typeof localStorage === "undefined") return this.memoryRegistration;
4390
+ try {
4391
+ const raw = localStorage.getItem(this.registrationKey);
4392
+ const parsed = raw ? JSON.parse(raw) : null;
4393
+ return _NotificationsModule.isStoredRegistration(parsed) ? parsed : this.memoryRegistration;
4394
+ } catch {
4395
+ return this.memoryRegistration;
4396
+ }
4397
+ }
4398
+ saveRegistration(registration) {
4399
+ this.memoryRegistration = registration;
4400
+ if (typeof localStorage === "undefined") return;
4401
+ try {
4402
+ if (registration) {
4403
+ localStorage.setItem(this.registrationKey, JSON.stringify(registration));
4404
+ } else {
4405
+ localStorage.removeItem(this.registrationKey);
4406
+ }
4407
+ } catch {
4408
+ }
4409
+ }
4260
4410
  /** Get all subscriptions for the current user */
4261
4411
  async getSubscriptions() {
4262
4412
  return this.http.request({
@@ -4459,10 +4609,21 @@ function createClient(config) {
4459
4609
  getToken: () => tokenManager.getAccessToken(),
4460
4610
  onTokenRefreshed: (listener) => tokenManager.onTokenRefreshed((tokens) => listener(tokens.accessToken))
4461
4611
  });
4462
- const auth = new AuthModule(httpClient, tokenManager, config);
4612
+ const notifications = new NotificationsModule(httpClient, {
4613
+ projectId: config.projectId
4614
+ });
4615
+ const autoManagePush = config.autoManagePush ?? true;
4616
+ const auth = new AuthModule(
4617
+ httpClient,
4618
+ tokenManager,
4619
+ config,
4620
+ autoManagePush ? {
4621
+ beforeLogout: () => notifications.unsubscribeBeforeLogout(),
4622
+ afterSignIn: () => notifications.resubscribeAfterLogin()
4623
+ } : {}
4624
+ );
4463
4625
  const storage = new StorageModule(httpClient, tokenManager, config);
4464
4626
  const db = new DatabaseModule(httpClient, config.projectId, realtime);
4465
- const notifications = new NotificationsModule(httpClient);
4466
4627
  const functions = new FunctionsModule(httpClient);
4467
4628
  const schedule = new ScheduleModule(httpClient, config.projectId);
4468
4629
  return {