@withone/connect 0.9.0 → 0.11.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.
@@ -70,6 +70,18 @@ function tenancyHeaders(accessToken) {
70
70
  }
71
71
  }
72
72
 
73
+ /** When a refresh token stops working, in epoch milliseconds, from its
74
+ * `exp` claim. Null when the token carries no readable expiry, in which
75
+ * case only One can say whether it still works. */
76
+ function refreshTokenExpiresAt(refreshToken) {
77
+ try {
78
+ const payload = JSON.parse(Buffer.from(refreshToken.split(".")[1], "base64url").toString());
79
+ return typeof payload.exp === "number" && Number.isFinite(payload.exp) ? payload.exp * 1000 : null;
80
+ } catch {
81
+ return null;
82
+ }
83
+ }
84
+
73
85
  /** The scopes the token was granted, from its claims. Display only. */
74
86
  function tokenScopes(accessToken) {
75
87
  try {
@@ -89,8 +101,8 @@ function tokenScopes(accessToken) {
89
101
 
90
102
  /**
91
103
  * Where the app keeps each user's tokens: its database, a cache, an
92
- * encrypted cookie. The SDK never sees a token outside these three
93
- * calls. `userId` is the app's own id for its user.
104
+ * encrypted cookie. The SDK never sees a token outside these calls.
105
+ * `userId` is the app's own id for its user.
94
106
  */
95
107
 
96
108
  /** The transaction cookie the authorize leg sets and the callback reads. */
@@ -99,6 +111,14 @@ function tokenScopes(accessToken) {
99
111
 
100
112
  /** One catalog action for a platform. */
101
113
 
114
+ /**
115
+ * - `not_connected`: no tokens are stored for this user.
116
+ * - `refresh_failed`: One declared the grant dead (revoked, expired or
117
+ * reused). The tokens were cleared; ask the user to connect again.
118
+ * - `request_failed`: One answered with an error or could not be
119
+ * reached. During a refresh the tokens are kept, so retry later.
120
+ */
121
+
102
122
  class OneConnectError extends Error {
103
123
  constructor(code, message, status) {
104
124
  super(message);
@@ -126,12 +146,26 @@ class OneConnectError extends Error {
126
146
  * const reply = await oneConnect.runAction(userId, { connectionKey, actionId, method, path });
127
147
  *
128
148
  * The Next.js and Node adapters turn the first two into route handlers.
149
+ *
150
+ * Refresh. One's access token lives an hour by default, its refresh token 30
151
+ * days; every refresh rotates both, and One treats a second use of a
152
+ * rotated refresh token as theft and revokes the whole grant. So the
153
+ * client refreshes one user at a time (in this process always, across
154
+ * processes through `tokenStore.withLock`), re-reads the store before
155
+ * spending a refresh token, clears tokens only when One declares the
156
+ * grant dead, and never lets a failing old pair delete a newer one.
129
157
  */
130
158
 
131
159
  /** Refresh this long before expiry, so a call never races the clock. */
132
160
  const REFRESH_MARGIN_MS = 60_000;
133
161
  const CATALOG_PAGE_SIZE = 100;
134
162
  const CATALOG_MAX_PAGES = 20;
163
+
164
+ /** What One's token endpoint answered. A network failure throws instead. */
165
+
166
+ /** The one refusal that means the grant is gone for good: revoked by the
167
+ * user, expired, or burned by a reused refresh token (RFC 6749 §5.2). */
168
+ const isDeadGrant = answer => !answer.ok && answer.status === 400 && answer.error === "invalid_grant";
135
169
  function createOneConnect(config) {
136
170
  const oneApiUrl = (config.oneApiUrl ?? DEFAULT_ONE_API_URL).replace(/\/+$/, "");
137
171
  const authorizeUrl = `${oneApiUrl}/oauth/authorize`;
@@ -152,7 +186,7 @@ function createOneConnect(config) {
152
186
  if (message) url.searchParams.set(RETURN_MESSAGE_PARAM, message);
153
187
  return url.toString();
154
188
  };
155
- const exchange = async body => {
189
+ const postToken = async body => {
156
190
  const response = await fetch(tokenUrl, {
157
191
  method: "POST",
158
192
  headers: {
@@ -161,10 +195,40 @@ function createOneConnect(config) {
161
195
  },
162
196
  body
163
197
  });
164
- if (!response.ok) {
165
- throw new OneConnectError("request_failed", `One refused the token request (HTTP ${response.status}).`, response.status);
198
+ if (response.ok) return {
199
+ ok: true,
200
+ body: await response.json()
201
+ };
202
+ let error;
203
+ try {
204
+ const refusal = await response.json();
205
+ if (typeof refusal.error === "string") error = refusal.error;
206
+ } catch {
207
+ /* not an OAuth error body: a proxy page or a server error */
208
+ }
209
+ return {
210
+ ok: false,
211
+ status: response.status,
212
+ error
213
+ };
214
+ };
215
+ const exchange = async body => {
216
+ const answer = await postToken(body);
217
+ if (!answer.ok) {
218
+ throw new OneConnectError("request_failed", `One refused the token request (HTTP ${answer.status}).`, answer.status);
166
219
  }
167
- return await response.json();
220
+ return answer.body;
221
+ };
222
+
223
+ /** Runs `run` under the app's cross-process lock for this user, when
224
+ * the store has one. */
225
+ const locked = (userId, run) => tokenStore.withLock ? tokenStore.withLock(userId, run) : run();
226
+
227
+ /** Whether either token of the pair stops working within `withinMs`. */
228
+ const expiresWithin = (tokens, withinMs) => {
229
+ const horizon = Date.now() + withinMs;
230
+ const refreshExpiresAt = refreshTokenExpiresAt(tokens.refreshToken);
231
+ return tokens.expiresAt <= horizon || refreshExpiresAt !== null && refreshExpiresAt <= horizon;
168
232
  };
169
233
  const toTokens = response => ({
170
234
  accessToken: response.access_token,
@@ -214,7 +278,9 @@ function createOneConnect(config) {
214
278
  redirect_uri: config.redirectUri,
215
279
  code_verifier: verifier
216
280
  })));
217
- await tokenStore.saveTokens(input.userId, tokens);
281
+ // Under the lock, so a refresh in flight on another server cannot
282
+ // interleave with this save.
283
+ await locked(input.userId, () => tokenStore.saveTokens(input.userId, tokens));
218
284
  } catch (error) {
219
285
  const status = error instanceof OneConnectError ? error.status : undefined;
220
286
  return fail("failed", status ? `One rejected the code exchange (HTTP ${status}).` : "One could not be reached to complete the connection.");
@@ -225,39 +291,81 @@ function createOneConnect(config) {
225
291
  clearCookieName: cookieName
226
292
  };
227
293
  };
228
- const refreshTokens = userId => {
294
+ const notConnected = () => new OneConnectError("not_connected", "This user is not connected.");
295
+
296
+ /**
297
+ * The grant behind `failed` is dead. Clears it, unless a newer pair
298
+ * landed while it was failing (a reconnect's callback, another
299
+ * server's refresh): that pair is returned instead, because the user
300
+ * did nothing wrong and deleting it would disconnect them.
301
+ */
302
+ const retire = async (userId, failed, status) => {
303
+ const latest = await tokenStore.loadTokens(userId);
304
+ if (latest && latest.refreshToken !== failed.refreshToken) return latest;
305
+ await tokenStore.clearTokens(userId, failed);
306
+ throw new OneConnectError("refresh_failed", "The connection to One has expired or was revoked. Ask the user to connect again.", status);
307
+ };
308
+
309
+ /**
310
+ * The one place a refresh token is spent. Under the app's lock it
311
+ * re-reads the store, and refreshes only when `stillNeeded` says the
312
+ * stored pair still needs it: another process may have refreshed while
313
+ * this one waited, and spending the same refresh token twice makes One
314
+ * revoke the grant.
315
+ */
316
+ const refreshUnderLock = (userId, stillNeeded) => locked(userId, async () => {
317
+ const current = await tokenStore.loadTokens(userId);
318
+ if (!current) throw notConnected();
319
+ if (!stillNeeded(current)) return current;
320
+
321
+ // An expired refresh token cannot work, and One answers one with a
322
+ // server error rather than invalid_grant, so settle it here.
323
+ const refreshExpiresAt = refreshTokenExpiresAt(current.refreshToken);
324
+ if (refreshExpiresAt !== null && refreshExpiresAt <= Date.now()) return retire(userId, current);
325
+ let answer;
326
+ try {
327
+ answer = await postToken(new URLSearchParams({
328
+ grant_type: "refresh_token",
329
+ refresh_token: current.refreshToken
330
+ }));
331
+ } catch {
332
+ throw new OneConnectError("request_failed", "One could not be reached to refresh the connection. The tokens were kept; try again.");
333
+ }
334
+ if (answer.ok) {
335
+ // Both tokens: One rotates the pair on every refresh.
336
+ const next = toTokens(answer.body);
337
+ await tokenStore.saveTokens(userId, next);
338
+ return next;
339
+ }
340
+ if (isDeadGrant(answer)) return retire(userId, current, answer.status);
341
+ // A server error, a rate limit, a misconfigured secret: nothing says
342
+ // the grant is gone, so keep the tokens and let the caller retry.
343
+ throw new OneConnectError("request_failed", `One could not refresh the connection (HTTP ${answer.status}). The tokens were kept; try again.`, answer.status);
344
+ });
345
+
346
+ /** One refresh per user in this process; concurrent callers share it. */
347
+ const singleFlight = (userId, job) => {
229
348
  const inFlight = refreshing.get(userId);
230
349
  if (inFlight) return inFlight;
231
- const job = (async () => {
232
- const current = await tokenStore.loadTokens(userId);
233
- if (!current) throw new OneConnectError("not_connected", "This user is not connected.");
234
- try {
235
- const next = toTokens(await exchange(new URLSearchParams({
236
- grant_type: "refresh_token",
237
- refresh_token: current.refreshToken
238
- })));
239
- // Both tokens: One rotates the pair on every refresh.
240
- await tokenStore.saveTokens(userId, next);
241
- return next;
242
- } catch (error) {
243
- // The family is dead: revoked, expired or reused. Keeping the
244
- // pair would only fail again; the user has to reconnect.
245
- await tokenStore.clearTokens(userId);
246
- const status = error instanceof OneConnectError ? error.status : undefined;
247
- throw new OneConnectError("refresh_failed", "The connection to One has expired or was revoked. Ask the user to connect again.", status);
248
- } finally {
249
- refreshing.delete(userId);
250
- }
251
- })();
252
- refreshing.set(userId, job);
253
- return job;
350
+ const running = job().finally(() => refreshing.delete(userId));
351
+ refreshing.set(userId, running);
352
+ return running;
254
353
  };
255
- const getAccessToken = async userId => {
354
+ const refreshTokens = userId => singleFlight(userId, async () => {
355
+ const before = await tokenStore.loadTokens(userId);
356
+ if (!before) throw notConnected();
357
+ // Rotate the pair seen now; a pair someone else rotated since is
358
+ // already fresh.
359
+ return refreshUnderLock(userId, current => current.refreshToken === before.refreshToken);
360
+ });
361
+ const refreshIfExpiring = async (userId, options = {}) => {
362
+ const withinMs = options.withinMs ?? REFRESH_MARGIN_MS;
256
363
  const tokens = await tokenStore.loadTokens(userId);
257
- if (!tokens) throw new OneConnectError("not_connected", "This user is not connected.");
258
- if (Date.now() < tokens.expiresAt - REFRESH_MARGIN_MS) return tokens.accessToken;
259
- return (await refreshTokens(userId)).accessToken;
364
+ if (!tokens) throw notConnected();
365
+ if (!expiresWithin(tokens, withinMs)) return tokens;
366
+ return singleFlight(userId, () => refreshUnderLock(userId, current => expiresWithin(current, withinMs)));
260
367
  };
368
+ const getAccessToken = async userId => (await refreshIfExpiring(userId)).accessToken;
261
369
  const oneFetch = async (userId, path, init = {}) => {
262
370
  const accessToken = await getAccessToken(userId);
263
371
  const headers = new Headers(init.headers);
@@ -333,6 +441,7 @@ function createOneConnect(config) {
333
441
  getAccessToken,
334
442
  getTokens: userId => tokenStore.loadTokens(userId),
335
443
  refreshTokens,
444
+ refreshIfExpiring,
336
445
  disconnect: userId => tokenStore.clearTokens(userId),
337
446
  listConnections,
338
447
  listActions,
@@ -341,4 +450,4 @@ function createOneConnect(config) {
341
450
  };
342
451
  }
343
452
 
344
- export { OneConnectError, createOneConnect, tenancyHeaders, tokenScopes };
453
+ export { OneConnectError, createOneConnect, refreshTokenExpiresAt, tenancyHeaders, tokenScopes };
@@ -20,5 +20,9 @@ export declare function basicAuthorization(clientId: string, clientSecret: strin
20
20
  * these headers, and without them the call runs in the user's personal
21
21
  * space. The access token's claims name the tenant, so echo them. */
22
22
  export declare function tenancyHeaders(accessToken: string): Record<string, string>;
23
+ /** When a refresh token stops working, in epoch milliseconds, from its
24
+ * `exp` claim. Null when the token carries no readable expiry, in which
25
+ * case only One can say whether it still works. */
26
+ export declare function refreshTokenExpiresAt(refreshToken: string): number | null;
23
27
  /** The scopes the token was granted, from its claims. Display only. */
24
28
  export declare function tokenScopes(accessToken: string): string[];
@@ -11,13 +11,44 @@ export interface OneConnectTokens {
11
11
  }
12
12
  /**
13
13
  * Where the app keeps each user's tokens: its database, a cache, an
14
- * encrypted cookie. The SDK never sees a token outside these three
15
- * calls. `userId` is the app's own id for its user.
14
+ * encrypted cookie. The SDK never sees a token outside these calls.
15
+ * `userId` is the app's own id for its user.
16
16
  */
17
17
  export interface OneConnectTokenStore {
18
18
  saveTokens: (userId: string, tokens: OneConnectTokens) => Promise<void>;
19
19
  loadTokens: (userId: string) => Promise<OneConnectTokens | null>;
20
- clearTokens: (userId: string) => Promise<void>;
20
+ /**
21
+ * Deletes the user's tokens.
22
+ *
23
+ * `failed` is set when the SDK clears because One declared that pair
24
+ * dead. Delete only when the stored refresh token is still
25
+ * `failed.refreshToken`: a newer pair saved in the meantime (a
26
+ * reconnect, another server's refresh) must survive. `failed` is
27
+ * undefined for `disconnect`, which always deletes.
28
+ */
29
+ clearTokens: (userId: string, failed?: OneConnectTokens) => Promise<void>;
30
+ /**
31
+ * Runs `run` while holding a lock on this user that every server and
32
+ * worker of the app shares: a Postgres advisory lock, a Redis lock, a
33
+ * row lock. The SDK loads, refreshes and saves the user's tokens
34
+ * inside it.
35
+ *
36
+ * Required when the app runs more than one process (serverless,
37
+ * several instances, a background worker). One rotates the refresh
38
+ * token on every use and treats a second use of the old one as theft,
39
+ * revoking the whole grant, so two processes refreshing the same user
40
+ * at once disconnect that user. Without a lock the SDK can only stop
41
+ * that inside a single process.
42
+ *
43
+ * Hold it for at least 60 seconds before any timeout: it spans one
44
+ * call to One's token endpoint.
45
+ */
46
+ withLock?: <T>(userId: string, run: () => Promise<T>) => Promise<T>;
47
+ }
48
+ export interface RefreshIfExpiringOptions {
49
+ /** Refresh when the access token or the refresh token expires within
50
+ * this many milliseconds. One minute when omitted. */
51
+ withinMs?: number;
21
52
  }
22
53
  export interface OneConnectServerConfig {
23
54
  /** The app's client id from the dashboard. */
@@ -128,6 +159,13 @@ export interface RunActionResult {
128
159
  blockedByGrant: boolean;
129
160
  data: unknown;
130
161
  }
162
+ /**
163
+ * - `not_connected`: no tokens are stored for this user.
164
+ * - `refresh_failed`: One declared the grant dead (revoked, expired or
165
+ * reused). The tokens were cleared; ask the user to connect again.
166
+ * - `request_failed`: One answered with an error or could not be
167
+ * reached. During a refresh the tokens are kept, so retry later.
168
+ */
131
169
  export type OneConnectErrorCode = "not_connected" | "refresh_failed" | "request_failed";
132
170
  export declare class OneConnectError extends Error {
133
171
  readonly code: OneConnectErrorCode;
package/dist/types.d.ts CHANGED
@@ -60,11 +60,9 @@ export interface ConnectButtonOptions {
60
60
  variant?: ConnectButtonVariant;
61
61
  /** Matches the host page, not One's page (that is connect.appTheme). */
62
62
  theme?: OneConnectTheme;
63
- /** Connector chips. The first three render; the rest fold into the
64
- * "+N" chip together with moreCount. */
63
+ /** Connector chips. The first three render; the rest fold into a "+N"
64
+ * chip, so that count only ever describes this list. */
65
65
  platforms?: ConnectButtonPlatformInput[];
66
- /** Extra count for the "+N" chip, e.g. 274 for "the whole catalog". */
67
- moreCount?: number;
68
66
  /** Sub-line on the block variant, shown while idle. */
69
67
  description?: string;
70
68
  /** Fill of the accent variant; One's lime when omitted. */
package/dist/vue.cjs.js CHANGED
@@ -1 +1 @@
1
- "use strict";var e=require("vue"),t=require("@withone/connect");const o=e.defineComponent({name:"OneConnectButton",props:{authorizeUrl:{type:String,required:!0},appTheme:{type:String,default:void 0},label:{type:String,default:void 0},variant:{type:String,default:void 0},theme:{type:String,default:void 0},platforms:{type:Array,default:void 0},moreCount:{type:Number,default:void 0},description:{type:String,default:void 0},accentColor:{type:String,default:void 0},connectedLabel:{type:String,default:void 0}},emits:{success:()=>!0,error:e=>"string"==typeof e},setup(o,{emit:n}){const r=e.ref(null);let u=null;const i=()=>{var e;null===(e=u)||void 0===e||e.destroy(),u=null,r.value&&(u=t.mountConnectButton(r.value,t.optionsFromProps({...o},{onSuccess:()=>n("success"),onError:e=>n("error",e)})))};return e.onMounted(i),e.watch(()=>t.propsIdentity({...o}),i),e.onBeforeUnmount(()=>{var e;null===(e=u)||void 0===e||e.destroy(),u=null}),()=>e.h("div",{ref:r})}});exports.ConnectButton=o;
1
+ "use strict";var e=require("vue"),t=require("@withone/connect");const n=e.defineComponent({name:"OneConnectButton",props:{authorizeUrl:{type:String,required:!0},appTheme:{type:String,default:void 0},label:{type:String,default:void 0},variant:{type:String,default:void 0},theme:{type:String,default:void 0},platforms:{type:Array,default:void 0},description:{type:String,default:void 0},accentColor:{type:String,default:void 0},connectedLabel:{type:String,default:void 0}},emits:{success:()=>!0,error:e=>"string"==typeof e},setup(n,{emit:o}){const r=e.ref(null);let i=null;const u=()=>{var e;null===(e=i)||void 0===e||e.destroy(),i=null,r.value&&(i=t.mountConnectButton(r.value,t.optionsFromProps({...n},{onSuccess:()=>o("success"),onError:e=>o("error",e)})))};return e.onMounted(u),e.watch(()=>t.propsIdentity({...n}),u),e.onBeforeUnmount(()=>{var e;null===(e=i)||void 0===e||e.destroy(),i=null}),()=>e.h("div",{ref:r})}});exports.ConnectButton=n;
package/dist/vue.d.ts CHANGED
@@ -25,10 +25,6 @@ export declare const ConnectButton: import("vue").DefineComponent<import("vue").
25
25
  type: PropType<ConnectButtonPlatformInput[]>;
26
26
  default: undefined;
27
27
  };
28
- moreCount: {
29
- type: NumberConstructor;
30
- default: undefined;
31
- };
32
28
  description: {
33
29
  type: StringConstructor;
34
30
  default: undefined;
@@ -71,10 +67,6 @@ export declare const ConnectButton: import("vue").DefineComponent<import("vue").
71
67
  type: PropType<ConnectButtonPlatformInput[]>;
72
68
  default: undefined;
73
69
  };
74
- moreCount: {
75
- type: NumberConstructor;
76
- default: undefined;
77
- };
78
70
  description: {
79
71
  type: StringConstructor;
80
72
  default: undefined;
@@ -97,7 +89,6 @@ export declare const ConnectButton: import("vue").DefineComponent<import("vue").
97
89
  platforms: ConnectButtonPlatformInput[];
98
90
  description: string;
99
91
  appTheme: OneConnectTheme;
100
- moreCount: number;
101
92
  accentColor: string;
102
93
  connectedLabel: string;
103
94
  }, {}, {}, {}, string, import("vue").ComponentProvideOptions, true, {}, any>;
package/dist/vue.esm.js CHANGED
@@ -1 +1 @@
1
- import{defineComponent as e,ref as t,onMounted as r,watch as o,onBeforeUnmount as n,h as i}from"vue";import{propsIdentity as l,mountConnectButton as u,optionsFromProps as d}from"@withone/connect";const a=e({name:"OneConnectButton",props:{authorizeUrl:{type:String,required:!0},appTheme:{type:String,default:void 0},label:{type:String,default:void 0},variant:{type:String,default:void 0},theme:{type:String,default:void 0},platforms:{type:Array,default:void 0},moreCount:{type:Number,default:void 0},description:{type:String,default:void 0},accentColor:{type:String,default:void 0},connectedLabel:{type:String,default:void 0}},emits:{success:()=>!0,error:e=>"string"==typeof e},setup(e,{emit:a}){const p=t(null);let s=null;const v=()=>{var t;null===(t=s)||void 0===t||t.destroy(),s=null,p.value&&(s=u(p.value,d({...e},{onSuccess:()=>a("success"),onError:e=>a("error",e)})))};return r(v),o(()=>l({...e}),v),n(()=>{var e;null===(e=s)||void 0===e||e.destroy(),s=null}),()=>i("div",{ref:p})}});export{a as ConnectButton};
1
+ import{defineComponent as e,ref as t,onMounted as r,watch as o,onBeforeUnmount as n,h as i}from"vue";import{propsIdentity as l,mountConnectButton as u,optionsFromProps as d}from"@withone/connect";const a=e({name:"OneConnectButton",props:{authorizeUrl:{type:String,required:!0},appTheme:{type:String,default:void 0},label:{type:String,default:void 0},variant:{type:String,default:void 0},theme:{type:String,default:void 0},platforms:{type:Array,default:void 0},description:{type:String,default:void 0},accentColor:{type:String,default:void 0},connectedLabel:{type:String,default:void 0}},emits:{success:()=>!0,error:e=>"string"==typeof e},setup(e,{emit:a}){const p=t(null);let s=null;const c=()=>{var t;null===(t=s)||void 0===t||t.destroy(),s=null,p.value&&(s=u(p.value,d({...e},{onSuccess:()=>a("success"),onError:e=>a("error",e)})))};return r(c),o(()=>l({...e}),c),n(()=>{var e;null===(e=s)||void 0===e||e.destroy(),s=null}),()=>i("div",{ref:p})}});export{a as ConnectButton};
@@ -15,7 +15,6 @@ export interface ConnectButtonProps {
15
15
  theme?: OneConnectTheme;
16
16
  /** Connector slugs, or objects to override name or logo. */
17
17
  platforms?: ConnectButtonPlatformInput[];
18
- moreCount?: number;
19
18
  description?: string;
20
19
  accentColor?: string;
21
20
  connectedLabel?: string;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@withone/connect",
3
- "version": "0.9.0",
3
+ "version": "0.11.0",
4
4
  "description": "One Connect for your app: the button your users press, the two backend routes as one import, and a server client that calls One with the grant. Users keep their connections in One; your app holds only what they granted.",
5
5
  "files": [
6
6
  "dist",
@@ -72,7 +72,9 @@ export const oneConnect = createOneConnect({
72
72
  tokenStore: {
73
73
  saveTokens: (userId, tokens) => /* write to this app's database, encrypted, keyed by its user */,
74
74
  loadTokens: (userId) => /* read; null when the user never connected */,
75
- clearTokens: (userId) => /* delete */,
75
+ clearTokens: (userId, failed) => /* delete; when `failed` is set, only if the stored refreshToken is still failed.refreshToken */,
76
+ // Required when the app runs more than one process (serverless, several instances, a worker):
77
+ withLock: (userId, run) => /* run() while holding a per-user lock all processes share, e.g. pg_advisory_xact_lock */,
76
78
  },
77
79
  });
78
80
  ```
@@ -81,6 +83,14 @@ export const oneConnect = createOneConnect({
81
83
  id as the key. Implement the store on whatever the app already uses; do not
82
84
  add a database for it.
83
85
 
86
+ One rotates the refresh token on every refresh and revokes the whole grant if
87
+ an old one is used again. So when two processes could refresh the same user,
88
+ `withLock` is not optional: without it, a web request and a worker refreshing
89
+ together disconnect the user. The README's "Tokens" section has a Postgres
90
+ version. For background work, call `refreshIfExpiring(userId, { withinMs })`:
91
+ every few minutes with a window of minutes to keep access tokens warm, and
92
+ once a day with a window of days so idle users' 30-day refresh tokens renew.
93
+
84
94
  ## 4 - The two routes
85
95
 
86
96
  Next.js App Router (also Remix, SvelteKit, Hono, Bun: anything with the web `Request`):
@@ -170,14 +180,22 @@ grant; the provider was never called. Do not retry. Any other `/v1` call:
170
180
  `oneConnect.fetch(userId, "/connections", init)`.
171
181
 
172
182
  `OneConnectError` codes: `not_connected` (no tokens stored), `refresh_failed`
173
- (One refused the refresh; the tokens were cleared; ask the user to connect
174
- again), `request_failed` (One answered with an error; `status` carries it).
183
+ (One declared the grant dead: revoked, expired or reused; the tokens were
184
+ cleared; ask the user to connect again), `request_failed` (One answered with
185
+ an error or could not be reached; `status` carries it; during a refresh the
186
+ tokens are KEPT, so retry later rather than asking the user to reconnect).
187
+
188
+ To ask users for more tools later, edit the app's permission set in the
189
+ dashboard. The next Connect shows only the new tools as "needs one more
190
+ connection" and the callback stores the new pair; no code change.
175
191
 
176
192
  ## 7 - Rules
177
193
 
178
194
  - Never put the secret in a client bundle, a log line or an error report.
179
195
  - Store tokens encrypted, keyed by the app's user. Delete them when the user
180
- is deleted. The client deletes them itself when a refresh fails.
196
+ is deleted. The client deletes them itself only when One declares the
197
+ grant dead, and never deletes a newer pair saved in the meantime.
198
+ - Give the store `withLock` whenever more than one process can refresh.
181
199
  - The registered redirect URI and `ONE_REDIRECT_URI` must be the same string.
182
200
  - Do not build a completion page. The callback redirect is the completion.
183
201
  - Do not write the OAuth steps by hand when the package exposes them.
package/src/button.ts CHANGED
@@ -58,8 +58,13 @@ const DARK: Palette = {
58
58
  shadow: "0 1px 2px rgba(0,0,0,.4), 0 8px 24px rgba(0,0,0,.35)",
59
59
  };
60
60
 
61
- const ONE_MARK_SVG =
62
- '<svg viewBox="0 0 24 24" width="12" height="12" fill="none" stroke="currentColor" stroke-width="2.4" style="flex-shrink:0"><circle cx="12" cy="12" r="8.5"/></svg>';
61
+ /** One's lockup — the mark and the wordmark as one asset, every fill set
62
+ * to `currentColor` so a single copy works on either palette. Inlined
63
+ * rather than fetched: this is the trust mark, and it has to draw even
64
+ * behind a strict content policy or offline. Source:
65
+ * core-ui/public/logo/logo-full-dark.svg (viewBox 3152x990). */
66
+ const ONE_LOCKUP_SVG =
67
+ '<svg viewBox="0 0 3152 990" width="35" height="11" fill="none" aria-hidden="true" style="flex-shrink:0;display:block"><path d="M1698.02 793.203C1525.75 793.203 1401 666.834 1401 495.102C1401 323.909 1524.67 197 1698.02 197C1870.83 197 1996.12 323.909 1996.12 495.102C1996.12 666.834 1869.75 793.203 1698.02 793.203ZM1698.02 694.916C1801.71 694.916 1884.88 615.53 1884.88 495.102C1884.88 374.133 1801.71 295.827 1698.02 295.827C1594.87 295.827 1511.71 373.053 1511.71 495.102C1511.71 616.61 1595.41 694.916 1698.02 694.916Z" fill="currentColor"/><path d="M2326.71 197.54C2480.62 197.54 2565.95 289.887 2565.95 467.56V779.702H2455.24V468.64C2455.24 361.172 2411.5 292.587 2308.35 292.587C2217.63 292.587 2140.4 356.852 2140.4 484.841V779.702H2030.77V211.041H2140.4V272.065C2185.76 225.082 2248.41 197.54 2326.71 197.54Z" fill="currentColor"/><path d="M3151.98 493.481C3151.98 514.003 3150.36 520.483 3148.74 529.124H2700.51C2715.63 637.672 2794.47 686.815 2922.46 686.815C3031.01 686.815 3099.6 650.633 3116.88 643.072V747.84C3100.68 755.4 3023.45 793.203 2908.96 793.203C2699.97 793.203 2588.18 661.434 2588.18 497.802C2588.18 332.55 2702.67 197 2871.7 197C3031.55 197 3151.98 317.969 3151.98 493.481ZM2876.02 300.688C2784.75 300.688 2720.49 345.511 2702.67 434.617H3050.45C3034.79 344.971 2967.29 300.688 2876.02 300.688Z" fill="currentColor"/><path d="M537.494 782.175C641.011 827.7 767.922 858.83 880.501 839.875C983.155 822.599 1069.64 764.946 1094.39 659.271C1114.47 573.493 1088.54 481.273 1047.27 405.311C983.124 287.246 874.768 183.791 759.847 114.657C644.926 45.5225 507.181 -5.02605 372.102 0.398669C289.698 3.69665 205.938 26.536 146.544 85.6685C112.069 119.989 88.3818 171.231 83.1266 219.823C78.1642 265.64 84.3749 310.317 99.8478 354.007C168.243 547.14 354.009 701.467 537.51 782.191L537.494 782.175ZM751.956 818.053C583.05 796.2 415.7 707.108 292.472 593.004C222.536 528.246 159.366 444.979 125.985 355.471C102.961 293.734 96.3956 223.367 122.41 161.969C137.158 127.14 160.367 98.244 190.743 75.9133C275.581 13.5752 395.819 6.99464 495.977 26.8596C608.848 49.252 713.875 99.4615 806.712 166.515C907.085 239.025 999.537 339.922 1048.42 454.627C1072.45 511.001 1083.99 570.103 1075.64 630.869C1067.38 690.957 1034.57 742.353 983.987 775.379C917.626 818.715 830.861 828.255 751.972 818.053H751.956Z" fill="currentColor"/><path d="M1103.27 661.228C1086.68 755.313 1024.9 818.622 934.021 848.69C821.751 885.846 685.146 860.263 576.251 818.915C452.515 771.942 340.336 699.91 245.157 607.813C209.002 572.83 177.255 534.456 148.837 493.031C100.384 422.402 61.7024 335.19 65.8326 248.071C68.2213 197.769 83.987 159.241 111.403 116.938C45.8289 171.308 31.404 262.511 47.1543 342.002C53.4728 373.841 62.9815 403.23 76.528 432.958C100.338 485.202 130.914 532.992 167.747 577.238C255.452 682.573 367.83 765.13 491.073 824.124C614.317 883.118 769.307 920.691 900.471 889.128C985.788 868.601 1061.47 816.095 1090.83 730.856C1098.18 708.71 1104.61 686.564 1103.25 661.244L1103.27 661.228Z" fill="currentColor"/><path d="M883.297 963.502C923.15 947.074 960.877 926.022 988.309 893.967C954.265 917.839 920.931 934.807 882.403 944.993C751.747 979.53 595.123 942.589 474.731 886.57C422.102 862.082 372.617 834.018 325.181 800.591C205.128 715.984 89.4825 597.996 36.7762 458.756C20.2092 414.973 11.7793 370.404 11.5327 323.739C11.4249 302.641 15.4627 283.747 19.0226 263.004C-2.52219 310.486 -3.66265 380.915 5.21419 431.617C32.0605 584.881 147.151 721.146 266.988 813.983C343.443 873.224 436.403 924.913 528.424 954.672C620.444 984.431 713.851 999.426 808.491 983.598C834.459 979.252 858.362 973.781 883.297 963.502Z" fill="currentColor"/><path d="M1045.09 830.737C1053.55 816.158 1061.75 802.95 1066.99 787.061C1043.75 824.541 1013.3 854.408 974.29 874.982C947.752 888.991 920.228 899.27 890.577 905.219C864.578 910.428 839.673 914.481 812.781 914.851C739.716 915.852 668.717 903.092 599.459 880.854C418.686 822.8 238.422 697.6 127.985 543.165C94.8819 496.87 68.8679 447.847 50.7135 394.031C28.1978 324.45 25.7782 258.69 53.4104 189.078C36.1345 211.825 26.9956 237.793 20.4151 264.916C18.3654 282.732 14.713 299.345 15.0828 317.561C15.9613 360.774 23.5436 402.692 38.477 443.562C73.1522 538.464 134.936 621.869 207.368 691.913C307.34 788.587 426.762 862.268 558.127 907.993C689.491 953.718 871.975 973.768 992.614 885.446C1013.28 870.312 1029.39 851.773 1045.07 830.752L1045.09 830.737Z" fill="currentColor"/><path d="M552.552 745.664C671.079 797.831 835.825 835.526 954.768 769.12C999.137 744.354 1031.99 705.626 1047.99 657.312C1086.75 540.264 1020.28 405.817 947.124 315.631C855.536 202.745 729.688 114.516 592.76 66.0323C506.349 35.4412 418.968 22.0797 328.211 37.46C262.313 48.6177 195.29 81.7054 157.563 138.234C118.912 196.133 115.891 270.785 136.758 335.882C176.519 459.926 276.769 570.763 381.01 646.277C434.995 685.391 491.662 718.864 552.567 745.664H552.552ZM210.162 422.955C199.898 402.381 189.141 382.701 184.733 360.385C182.267 347.918 184.625 333.477 184.564 320.64C184.44 293.223 194.072 269.059 209.992 247.93C219.609 235.17 229.456 224.844 243.018 215.906C341.218 151.179 476.051 175.991 576.763 223.904C661.971 264.435 737.394 321.534 796.11 395.862C836.919 447.52 871.193 513.634 880.502 579.501C888.238 634.272 873.243 695.485 826.763 729.189C807.853 742.905 785.045 751.721 761.728 755.974C721.921 763.217 688.802 758.008 649.565 748.916C594.27 736.094 542.488 715.212 492.279 688.889C441.977 662.521 396.745 631.483 353.008 595.436C314.372 563.597 280.252 537.845 248.458 498.007L248.274 497.837L221.504 461.945L211.379 445.84C194.103 418.408 177.398 391.346 165.238 361.202C151.291 326.604 142.676 291.852 143.678 254.279C146.19 160.564 203.766 96.7467 290.238 67.82C434.394 19.5985 611.561 79.4246 735.298 157.636C825.099 214.411 904.435 286.581 963.321 375.134C989.767 414.894 1010.42 456.998 1023.78 502.646C1049.84 591.66 1036.79 685.884 957.404 742.659C890.257 790.68 785.6 793.146 707.295 776.486C680.403 769.736 654.065 766.007 629.222 754.818C732.107 783.93 882.397 797.723 963.938 715.35C990.599 688.412 1007.55 656.218 1013.75 618.537C1020.87 575.232 1016.12 531.634 1002.62 489.931C985.498 437.071 956.34 384.026 922.405 340.289C876.911 281.665 823.188 230.531 762.468 187.981C681.112 130.975 588.783 88.887 490.799 71.0872C425.595 59.2514 349.463 60.4072 287.557 85.0959C256.441 97.5019 228.501 114.5 205.924 138.85C158.303 190.2 147.176 256.036 161.539 323.383C166.856 348.334 175.456 371.296 185.596 394.737C194.488 415.295 222.676 461.883 236.022 477.649L226.729 456.196L210.162 423.001V422.955ZM832.342 286.936C756.904 211.544 666.44 154.076 564.896 120.249C526.553 107.473 487.948 99.4899 447.648 96.084C401.26 92.1696 356.167 96.7313 312.215 111.341C222.337 141.208 169.399 217.277 175.255 312.333C177.567 324.847 179.555 335.774 180.603 348.503C152.971 264.944 174.454 175.236 251.356 125.581C310.797 87.2072 387.39 78.2071 456.694 86.7603C503.714 92.5549 555.387 106.656 599.078 124.317C706.016 167.546 800.764 234.615 876.741 321.395C912.002 361.664 942.085 405.756 963.876 454.532C996.779 528.166 1011.85 610.046 965.895 681.369C952.379 702.359 935.427 718.818 914.283 731.871C884.432 747.421 852.947 758.671 818.872 761.06C839.523 755.959 859.404 750.981 878.637 740.424C929.186 717.061 964.601 671.567 974.818 616.488C987.671 547.245 964.693 475.429 930.881 415.357C903.834 367.305 871.471 326.049 832.311 286.905L832.342 286.936ZM890.673 420.18C861.623 370.387 825.515 327.621 783.288 287.999C721.659 230.161 650.028 185.345 570.598 156.033C513.623 135.013 454.506 124.394 393.786 128.108C353.316 130.59 315.728 139.867 280.498 159.516C245.268 179.166 216.819 204.918 201.023 240.394L188.617 268.242C204.583 180.445 278.325 132.054 361.931 119.355C412.757 111.634 462.658 116.643 512.421 129.048C596.905 150.116 674.1 189.923 743.45 242.028C816.607 296.999 885.526 373.531 924.578 456.982C949.713 510.675 965.094 571.61 949.837 630.234C939.018 671.768 912.511 706.566 875.308 727.987C847.013 744.292 816.191 754.679 783.242 758.101C825.915 745.926 863.75 731.917 895.327 698.799C913.512 679.72 926.535 657.62 933.054 631.714C951.347 558.989 927.49 483.274 890.642 420.134L890.673 420.18ZM726.19 279.369C625.678 198.799 493.404 141.917 362.655 156.973C343.854 159.131 326.547 164.17 308.639 169.195C301.18 171.29 295.201 177.732 286.493 176.253C378.313 130.081 492.063 149.545 583.143 188.119C684.102 230.87 775.952 302.825 840.664 391.069C871.794 433.527 895.805 479.652 909.506 530.386C918.382 563.273 920.232 596.654 911.941 629.294C905.622 654.153 895.481 677.778 875.786 694.9C893.987 666.327 905.452 637.693 907.086 604.128C908.72 570.562 903.141 536.565 891.567 503.57C861.392 417.53 797.066 336.19 726.205 279.384L726.19 279.369Z" fill="currentColor"/></svg>';
63
68
  const ARROW_SVG =
64
69
  '<svg class="owcb-arrow" width="14" height="14" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"><path d="M6 3l5 5-5 5"/></svg>';
65
70
  const TICK_SVG =
@@ -104,7 +109,7 @@ function buildStack(
104
109
  chipRing: string,
105
110
  ): HTMLElement | null {
106
111
  const platforms = normalizePlatforms(options.platforms);
107
- if (platforms.length === 0 && !options.moreCount) return null;
112
+ if (platforms.length === 0) return null;
108
113
  const stack = document.createElement("span");
109
114
  stack.className = "owcb-stack";
110
115
  stack.setAttribute("aria-hidden", "true");
@@ -124,9 +129,9 @@ function buildStack(
124
129
  chip.appendChild(img);
125
130
  stack.appendChild(chip);
126
131
  }
127
- const extra =
128
- (options.moreCount ?? 0) +
129
- Math.max(0, platforms.length - MAX_VISIBLE_CHIPS);
132
+ // Only ever the apps the caller listed beyond the first three: the chip
133
+ // can never claim a number that has nothing to do with them.
134
+ const extra = Math.max(0, platforms.length - MAX_VISIBLE_CHIPS);
130
135
  if (extra > 0) {
131
136
  const more = document.createElement("span");
132
137
  more.className = "owcb-chip owcb-more";
@@ -237,8 +242,7 @@ export const mountConnectButton = (
237
242
  foot.style.borderTop = `1px solid ${palette.line}`;
238
243
  foot.innerHTML =
239
244
  `<span style="font-size:11px;color:${palette.muted}">Secured by</span>` +
240
- `<span style="display:inline-flex;color:${palette.foreground}">${ONE_MARK_SVG}</span>` +
241
- `<span style="font-size:12px;font-weight:600;letter-spacing:-0.02em;color:${palette.foreground}">one</span>`;
245
+ `<span style="display:inline-flex;color:${palette.foreground}">${ONE_LOCKUP_SVG}</span>`;
242
246
  button.appendChild(foot);
243
247
  return;
244
248
  }
@@ -295,7 +299,7 @@ export const mountConnectButton = (
295
299
  * HTMLElement.
296
300
  *
297
301
  * Attributes: authorize-url (required), app-theme, label, variant,
298
- * theme, platforms ("stripe, notion" or a JSON array), more-count,
302
+ * theme, platforms ("stripe, notion" or a JSON array),
299
303
  * description, accent-color, connected-label.
300
304
  * Events: "success" and "error" (detail: message), plus the matching
301
305
  * onSuccess and onError function properties that React 19, Vue and
@@ -314,7 +318,6 @@ export function registerConnectButton(): void {
314
318
  "variant",
315
319
  "theme",
316
320
  "platforms",
317
- "more-count",
318
321
  "description",
319
322
  "accent-color",
320
323
  "connected-label",
@@ -344,9 +347,6 @@ export function registerConnectButton(): void {
344
347
  const authorizeUrl = this.getAttribute("authorize-url");
345
348
  if (!authorizeUrl) return;
346
349
 
347
- const moreCountRaw = this.getAttribute("more-count");
348
- const moreCount = moreCountRaw ? parseInt(moreCountRaw, 10) : NaN;
349
-
350
350
  this.handle = mountConnectButton(this, {
351
351
  connect: {
352
352
  authorizeUrl,
@@ -364,7 +364,6 @@ export function registerConnectButton(): void {
364
364
  variant: attributeAs(this, "variant", ["default", "accent", "block"]),
365
365
  theme: attributeAs(this, "theme", ["light", "dark"]),
366
366
  platforms: parsePlatformsAttribute(this.getAttribute("platforms")),
367
- moreCount: Number.isFinite(moreCount) ? moreCount : undefined,
368
367
  description: this.getAttribute("description") ?? undefined,
369
368
  accentColor: this.getAttribute("accent-color") ?? undefined,
370
369
  connectedLabel: this.getAttribute("connected-label") ?? undefined,