@motherbase/client 1.4.0 → 1.5.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.
Files changed (90) hide show
  1. package/README.md +379 -284
  2. package/package.json +1 -1
  3. package/dist/admin.d.ts +0 -81
  4. package/dist/admin.d.ts.map +0 -1
  5. package/dist/admin.js +0 -85
  6. package/dist/admin.js.map +0 -1
  7. package/dist/auth.d.ts +0 -362
  8. package/dist/auth.d.ts.map +0 -1
  9. package/dist/auth.js +0 -721
  10. package/dist/auth.js.map +0 -1
  11. package/dist/channel.d.ts +0 -122
  12. package/dist/channel.d.ts.map +0 -1
  13. package/dist/channel.js +0 -213
  14. package/dist/channel.js.map +0 -1
  15. package/dist/compat.d.ts +0 -40
  16. package/dist/compat.d.ts.map +0 -1
  17. package/dist/compat.js +0 -98
  18. package/dist/compat.js.map +0 -1
  19. package/dist/cookie.d.ts +0 -68
  20. package/dist/cookie.d.ts.map +0 -1
  21. package/dist/cookie.js +0 -152
  22. package/dist/cookie.js.map +0 -1
  23. package/dist/database.d.ts +0 -188
  24. package/dist/database.d.ts.map +0 -1
  25. package/dist/database.js +0 -2
  26. package/dist/database.js.map +0 -1
  27. package/dist/devices.d.ts +0 -13
  28. package/dist/devices.d.ts.map +0 -1
  29. package/dist/devices.js +0 -13
  30. package/dist/devices.js.map +0 -1
  31. package/dist/edge.d.ts +0 -7
  32. package/dist/edge.d.ts.map +0 -1
  33. package/dist/edge.js +0 -13
  34. package/dist/edge.js.map +0 -1
  35. package/dist/functions.d.ts +0 -60
  36. package/dist/functions.d.ts.map +0 -1
  37. package/dist/functions.js +0 -75
  38. package/dist/functions.js.map +0 -1
  39. package/dist/http.d.ts +0 -123
  40. package/dist/http.d.ts.map +0 -1
  41. package/dist/http.js +0 -205
  42. package/dist/http.js.map +0 -1
  43. package/dist/index.d.ts +0 -185
  44. package/dist/index.d.ts.map +0 -1
  45. package/dist/index.js +0 -331
  46. package/dist/index.js.map +0 -1
  47. package/dist/mfa.d.ts +0 -109
  48. package/dist/mfa.d.ts.map +0 -1
  49. package/dist/mfa.js +0 -134
  50. package/dist/mfa.js.map +0 -1
  51. package/dist/postgrest.d.ts +0 -326
  52. package/dist/postgrest.d.ts.map +0 -1
  53. package/dist/postgrest.js +0 -629
  54. package/dist/postgrest.js.map +0 -1
  55. package/dist/profile.d.ts +0 -16
  56. package/dist/profile.d.ts.map +0 -1
  57. package/dist/profile.js +0 -26
  58. package/dist/profile.js.map +0 -1
  59. package/dist/query.d.ts +0 -97
  60. package/dist/query.d.ts.map +0 -1
  61. package/dist/query.js +0 -94
  62. package/dist/query.js.map +0 -1
  63. package/dist/realtime.d.ts +0 -114
  64. package/dist/realtime.d.ts.map +0 -1
  65. package/dist/realtime.js +0 -372
  66. package/dist/realtime.js.map +0 -1
  67. package/dist/rest.d.ts +0 -50
  68. package/dist/rest.d.ts.map +0 -1
  69. package/dist/rest.js +0 -75
  70. package/dist/rest.js.map +0 -1
  71. package/dist/session.d.ts +0 -47
  72. package/dist/session.d.ts.map +0 -1
  73. package/dist/session.js +0 -136
  74. package/dist/session.js.map +0 -1
  75. package/dist/storage.d.ts +0 -239
  76. package/dist/storage.d.ts.map +0 -1
  77. package/dist/storage.js +0 -391
  78. package/dist/storage.js.map +0 -1
  79. package/dist/testing.d.ts +0 -38
  80. package/dist/testing.d.ts.map +0 -1
  81. package/dist/testing.js +0 -50
  82. package/dist/testing.js.map +0 -1
  83. package/dist/types.d.ts +0 -343
  84. package/dist/types.d.ts.map +0 -1
  85. package/dist/types.js +0 -2
  86. package/dist/types.js.map +0 -1
  87. package/dist/warn.d.ts +0 -4
  88. package/dist/warn.d.ts.map +0 -1
  89. package/dist/warn.js +0 -27
  90. package/dist/warn.js.map +0 -1
package/dist/index.js DELETED
@@ -1,331 +0,0 @@
1
- import { HttpClient, toError } from './http.js';
2
- import { contractPath } from '@motherbase/contracts';
3
- import { SessionStore, memoryStorage, localStorageStorage, keyValueStorage, isKeyValueStorage } from './session.js';
4
- import { AuthClient } from './auth.js';
5
- import { StorageClient } from './storage.js';
6
- import { FunctionsClient } from './functions.js';
7
- import { RealtimeModule } from './realtime.js';
8
- import { RealtimeChannel } from './channel.js';
9
- import { PostgrestQueryBuilder } from './postgrest.js';
10
- import { isProduction } from './cookie.js';
11
- /**
12
- * Pick the session storage from either options shape.
13
- *
14
- * Precedence: the native `storage` (explicit and already the right shape), then
15
- * supabase-js's `auth.storage` (wrapped if it is a key/value store), then
16
- * `auth.persistSession` on its own, which in supabase-js means localStorage.
17
- * Returns `undefined` when nothing was asked for, so the caller can tell "no
18
- * choice made" from "memory was chosen" and warn accordingly.
19
- */
20
- function resolveStorage(options) {
21
- if (options.storage)
22
- return options.storage;
23
- const key = options.auth?.storageKey;
24
- const provided = options.auth?.storage;
25
- if (provided) {
26
- return isKeyValueStorage(provided) ? keyValueStorage(provided, key) : provided;
27
- }
28
- if (options.auth?.persistSession === true)
29
- return localStorageStorage(key);
30
- if (options.auth?.persistSession === false)
31
- return memoryStorage();
32
- return undefined;
33
- }
34
- /**
35
- * Supabase-js-compatible client for a Motherbase backend.
36
- *
37
- * Drop-in shaped: `client.from(table).select()…`, `client.auth.signInWithPassword()`,
38
- * `client.storage.from(bucket)`, `client.channel(name)`, `client.functions.invoke()`.
39
- *
40
- * Pass the type generated by `motherbase gen types typescript` to get real
41
- * inference: `createClient<Database>(url, key)` then types every row, rejects
42
- * unknown columns in `.select()`, checks `.insert()` payloads against the
43
- * Insert shape and types `.rpc()` from `Functions`. Without it the client
44
- * behaves exactly as it did before generics existed.
45
- */
46
- export class MotherbaseClient {
47
- constructor(url,
48
- /** Accepted for supabase-js signature parity; sent as an `apikey` header when set. */
49
- key, options = {}) {
50
- this.url = url;
51
- this.key = key;
52
- this.channels = new Map();
53
- this.requestObservers = new Set();
54
- // `globalThis.fetch` is a native function that requires `this === window`
55
- // (or an equivalent global) when invoked: copying the reference without
56
- // binding it throws "Illegal invocation" the moment it's called as
57
- // `this.opts.fetch(...)` inside HttpClient. Bind it once here.
58
- const fetchImpl = options.fetch ?? options.global?.fetch ?? globalThis.fetch?.bind(globalThis);
59
- if (!fetchImpl) {
60
- throw new Error('No fetch implementation found. Pass `fetch` in options for this runtime.');
61
- }
62
- const autoRefresh = options.autoRefresh ?? options.auth?.autoRefreshToken ?? true;
63
- const headers = { ...options.global?.headers, ...options.headers };
64
- if (key)
65
- headers['apikey'] = key;
66
- this.compat = options.compat === 'supabase';
67
- // Only `public` is exposed by the REST layer. A ported app that asked for
68
- // another schema would otherwise read `public` under a different name and
69
- // find the wrong rows (or none), which is far harder to diagnose than the
70
- // error it gets here.
71
- const schema = options.db?.schema;
72
- if (schema && schema !== 'public') {
73
- throw new Error(`db.schema: '${schema}' is not exposed. The Motherbase REST API serves the public schema only. `
74
- + 'Move the tables to public, or expose them through a view or an RPC.');
75
- }
76
- // A secret key runs every request as service_role, which bypasses row level
77
- // security. In a browser it is readable by anyone who opens devtools, so it
78
- // is not "a key that leaked", it is the whole database published. Warn
79
- // rather than throw: a legitimate caller may run in a runtime that defines
80
- // `window` (a test harness, an Electron main process), and refusing to
81
- // construct would break them for a heuristic.
82
- if (key?.startsWith('mb_secret_') && typeof window !== 'undefined') {
83
- console.warn('[motherbase] A secret API key was passed to createClient in a browser context. '
84
- + 'Secret keys bypass row level security and must stay server side. '
85
- + 'Use the publishable key here.');
86
- }
87
- const storageAdapter = resolveStorage(options);
88
- // The default adapter keeps the session in memory only: it does not survive
89
- // a reload, and the server never sees it. That is the right default for a
90
- // script or a test, and a bug in a browser app, and it presents as
91
- // "getUser() returns null everywhere", which reads like an auth problem
92
- // rather than a storage one. Point at the fix once, in development.
93
- if (!storageAdapter && typeof window !== 'undefined' && !MotherbaseClient.warnedAboutStorage) {
94
- MotherbaseClient.warnedAboutStorage = true;
95
- if (!isProduction()) {
96
- console.warn('[motherbase] createClient() was called in a browser without a `storage` adapter, so the '
97
- + 'session lives in memory and is lost on reload. Pass `storage: cookieStorage()` (or '
98
- + '`localStorageStorage()`), or use `createBrowserClient` from `@motherbase/ssr`, which '
99
- + 'writes the cookie the server needs to read.');
100
- }
101
- }
102
- this.store = new SessionStore(storageAdapter ?? memoryStorage());
103
- // auth needs the http client, and http needs auth._refresh for the 401 path,
104
- // so wire them in two steps with a late-bound refresh callback.
105
- // prefer-const cannot see the closure above: `auth` is read by the refresh
106
- // callback before this line's assignment happens, so it has to be a `let`.
107
- // eslint-disable-next-line prefer-const
108
- let auth;
109
- this.http = new HttpClient(url, this.store, { autoRefresh, fetch: fetchImpl, headers }, () => auth._refresh());
110
- auth = new AuthClient(this.http, this.store);
111
- this.auth = auth;
112
- this.storage = new StorageClient(this.http, url, fetchImpl);
113
- this.functions = new FunctionsClient(this.http);
114
- this.realtime = new RealtimeModule(url, this.store, fetchImpl, options.realtimeIoFactory);
115
- // supabase-js finishes an OAuth redirect on its own (detectSessionInUrl
116
- // defaults to true), so ported code never calls anything after the provider
117
- // sends the browser back. Do the same, and only when there is actually a
118
- // token in the fragment: on every other page load this is a no-op with no
119
- // network call. Opt out with `auth: { detectSessionInUrl: false }`.
120
- if (options.auth?.detectSessionInUrl !== false
121
- && typeof window !== 'undefined'
122
- && window.location?.hash?.includes('access_token=')) {
123
- void this.auth.getSessionFromUrl();
124
- }
125
- }
126
- from(table) {
127
- return new PostgrestQueryBuilder(this.http, table, this.compat);
128
- }
129
- /**
130
- * Call a database function, typed from the generated `Functions` map.
131
- *
132
- * The transport is `POST /rest/v1/rpc/<fn>`, which the REST layer gains in
133
- * Phase 2.8. The typing is independent of that work: it reads only the
134
- * generated `Database`, so it is correct the moment the route exists.
135
- *
136
- * `get` and `head` switch to the read-only forms, which carry their arguments
137
- * as query parameters rather than as a body, exactly as supabase-js does.
138
- */
139
- async rpc(fn, args, options = {}) {
140
- try {
141
- const method = options.head ? 'HEAD' : options.get ? 'GET' : 'POST';
142
- const params = new URLSearchParams();
143
- if (method !== 'POST') {
144
- for (const [name, value] of Object.entries((args ?? {}))) {
145
- if (value === undefined)
146
- continue;
147
- params.append(name, Array.isArray(value) ? `{${value.join(',')}}` : String(value));
148
- }
149
- }
150
- const query = params.toString();
151
- const path = `${contractPath.rest('rpc')}/${encodeURIComponent(fn)}${query ? `?${query}` : ''}`;
152
- const headers = options.count ? { Prefer: `count=${options.count}` } : undefined;
153
- const result = await this.http.requestWithHeaders(path, {
154
- method,
155
- body: method === 'POST' ? (args ?? {}) : undefined,
156
- headers,
157
- });
158
- const range = result.headers.get('content-range');
159
- const total = range?.split('/')[1];
160
- const count = total && total !== '*' && Number.isFinite(Number(total)) ? Number(total) : null;
161
- return { data: options.head ? null : result.data, error: null, count };
162
- }
163
- catch (err) {
164
- return { data: null, error: toError(err), count: null };
165
- }
166
- }
167
- /**
168
- * Watch every HTTP request this client makes.
169
- *
170
- * One event per round trip, with method, path, status, duration and the
171
- * `x-request-id` the server logged it under. That id is the whole point: it
172
- * is what turns "a query was slow for a user yesterday" into a line in the
173
- * project's logs.
174
- *
175
- * ```ts
176
- * client.on('request', e => console.log(e.method, e.path, e.status, e.durationMs))
177
- * ```
178
- *
179
- * Returns the unsubscribe function. An observer that throws is ignored: it is
180
- * a spectator, and a broken logger must not fail the request it was logging.
181
- */
182
- on(event, listener) {
183
- if (event !== 'request')
184
- throw new Error(`Unknown client event '${String(event)}'. Only 'request' exists.`);
185
- this.requestObservers.add(listener);
186
- this.syncRequestObserver();
187
- return () => {
188
- this.requestObservers.delete(listener);
189
- this.syncRequestObserver();
190
- };
191
- }
192
- syncRequestObserver() {
193
- this.http.setRequestObserver(this.requestObservers.size
194
- ? (event) => {
195
- for (const listener of this.requestObservers)
196
- listener(event);
197
- }
198
- : undefined);
199
- }
200
- /**
201
- * Several writes, applied in one database transaction, all or nothing.
202
- *
203
- * supabase-js has no equivalent. What people write instead is a sequence of
204
- * awaited writes inside a `try`, which is not a rollback: whatever already
205
- * committed stays committed, and the catch block is left holding half a
206
- * change it cannot undo.
207
- *
208
- * The callback does not await anything. It DESCRIBES the writes; they are
209
- * sent together and applied together:
210
- *
211
- * ```ts
212
- * const { data, error } = await client.transaction(tx => {
213
- * tx.from('orders').insert({ id, total })
214
- * tx.from('stock').update({ count: 4 }).eq('sku', sku)
215
- * })
216
- * ```
217
- *
218
- * `data` is one result array per operation, in the order they were declared.
219
- * Reads are refused: a batch exists to make writes atomic, and a read in the
220
- * middle of one invites expectations about ordering that nothing guarantees.
221
- */
222
- async transaction(build) {
223
- const recorded = [];
224
- const tx = {
225
- from: ((table) => {
226
- const builder = new PostgrestQueryBuilder(this.http, table, this.compat);
227
- recorded.push(builder);
228
- return builder;
229
- }),
230
- };
231
- try {
232
- build(tx);
233
- const operations = recorded.map(builder => {
234
- const request = builder.toRequest();
235
- if (request.method === 'GET' || request.method === 'HEAD') {
236
- throw new Error(`transaction(): '${request.model}' was read, not written. A transaction takes writes only `
237
- + '(insert, upsert, update, delete).');
238
- }
239
- return request;
240
- });
241
- if (!operations.length) {
242
- throw new Error('transaction(): the callback declared no writes.');
243
- }
244
- const result = await this.http.request(`${contractPath.rest('batch')}`, {
245
- method: 'POST',
246
- body: { operations },
247
- });
248
- return { data: result.results, error: null, count: null };
249
- }
250
- catch (err) {
251
- return { data: null, error: toError(err), count: null };
252
- }
253
- }
254
- /** Create (or reuse) a realtime channel. */
255
- channel(name, opts = {}) {
256
- const existing = this.channels.get(name);
257
- if (existing)
258
- return existing;
259
- const channel = new RealtimeChannel(name, this.realtime, opts);
260
- this.channels.set(name, channel);
261
- return channel;
262
- }
263
- /** Every channel this client created, as supabase-js reports them. */
264
- getChannels() {
265
- return Array.from(this.channels.values());
266
- }
267
- /**
268
- * supabase-js's schema switcher.
269
- *
270
- * The Motherbase REST layer serves `public` and nothing else, so this returns
271
- * the client for `'public'` and throws for anything else rather than issuing
272
- * a request that would silently read the wrong tables.
273
- */
274
- schema(name) {
275
- if (name !== 'public') {
276
- throw new Error(`schema('${name}') is not supported: the Motherbase REST API exposes the public schema only. `
277
- + 'Expose the data through a view or an RPC in public instead.');
278
- }
279
- return this;
280
- }
281
- /** Unsubscribe and drop a channel. */
282
- async removeChannel(channel) {
283
- await channel.unsubscribe();
284
- this.channels.delete(channel.topic);
285
- return 'ok';
286
- }
287
- /** Unsubscribe and drop every channel. */
288
- async removeAllChannels() {
289
- await Promise.all(Array.from(this.channels.values()).map(c => c.unsubscribe()));
290
- this.channels.clear();
291
- return 'ok';
292
- }
293
- /** Load any persisted session before first use. Optional but recommended. */
294
- hydrate() {
295
- return this.store.hydrate();
296
- }
297
- }
298
- MotherbaseClient.warnedAboutStorage = false;
299
- /**
300
- * Create a Supabase-compatible Motherbase client.
301
- *
302
- * In a Next.js app, prefer `createBrowserClient` / `createServerClient` from
303
- * `@motherbase/ssr`: they persist the session to a cookie both halves can read.
304
- * `createClient()` on its own keeps the session in memory, which the server
305
- * cannot see, so every server-rendered `getUser()` returns null.
306
- *
307
- * @param url Backend API base URL.
308
- * @param key Anon/publishable key (optional). Sent as an `apikey` header.
309
- * @param options Session storage, fetch override, extra headers.
310
- *
311
- * @example
312
- * ```ts
313
- * import type { Database } from './database.types'
314
- * const client = createClient<Database>(url, anonKey)
315
- * ```
316
- */
317
- export function createClient(url, key, options = {}) {
318
- return new MotherbaseClient(url, key, options);
319
- }
320
- export { BackendError } from './http.js';
321
- export { memoryStorage, localStorageStorage, keyValueStorage };
322
- export { normalizeSession, normalizeUser } from './compat.js';
323
- export { cookieStorage, serverCookieStorage, SESSION_COOKIE_KEY } from './cookie.js';
324
- export { PostgrestQueryBuilder } from './postgrest.js';
325
- export { AuthClient } from './auth.js';
326
- export { MfaClient } from './mfa.js';
327
- export { AuthAdminClient } from './admin.js';
328
- export { StorageClient, StorageBucket } from './storage.js';
329
- export { FunctionsClient, FunctionsError, FunctionsHttpError, FunctionsRelayError, FunctionsFetchError } from './functions.js';
330
- export { RealtimeChannel } from './channel.js';
331
- //# sourceMappingURL=index.js.map
package/dist/index.js.map DELETED
@@ -1 +0,0 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],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L,OAAO,IAAI,CAAC,KAAK,CAAC,OAAO,EAAE,CAAC;IAC9B,CAAC;;AA9Sc,mCAAkB,GAAG,KAAK,AAAR,CAAS;AAiT5C;;;;;;;;;;;;;;;;;GAiBG;AACH,MAAM,UAAU,YAAY,CAI1B,GAAW,EAAE,GAAY,EAAE,UAAyB,EAAE;IACtD,OAAO,IAAI,gBAAgB,CAA+B,GAAG,EAAE,GAAG,EAAE,OAAO,CAAC,CAAC;AAC/E,CAAC;AAED,OAAO,EAAE,YAAY,EAAE,MAAM,WAAW,CAAC;AACzC,OAAO,EAAE,aAAa,EAAE,mBAAmB,EAAE,eAAe,EAAE,CAAC;AAC/D,OAAO,EAAE,gBAAgB,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAC9D,OAAO,EAAE,aAAa,EAAE,mBAAmB,EAAE,kBAAkB,EAAE,MAAM,aAAa,CAAC;AACrF,OAAO,EAAE,qBAAqB,EAAE,MAAM,gBAAgB,CAAC;AA8CvD,OAAO,EAAE,UAAU,EAAE,MAAM,WAAW,CAAC;AACvC,OAAO,EAAE,SAAS,EAAE,MAAM,UAAU,CAAC;AACrC,OAAO,EAAE,eAAe,EAAE,MAAM,YAAY,CAAC;AAmB7C,OAAO,EAAE,aAAa,EAAE,aAAa,EAAE,MAAM,cAAc,CAAC;AAE5D,OAAO,EAAE,eAAe,EAAE,cAAc,EAAE,kBAAkB,EAAE,mBAAmB,EAAE,mBAAmB,EAAE,MAAM,gBAAgB,CAAC;AAE/H,OAAO,EAAE,eAAe,EAAE,MAAM,cAAc,CAAC"}
package/dist/mfa.d.ts DELETED
@@ -1,109 +0,0 @@
1
- import type { HttpClient } from './http.js';
2
- import type { MotherbaseResponse } from './types.js';
3
- /**
4
- * Two-factor authentication, shaped like `supabase.auth.mfa`.
5
- *
6
- * The server has shipped TOTP with backup codes and trusted devices since the
7
- * beginning; only the client namespace was missing, which meant the product's
8
- * strongest auth feature could not be reached from the SDK that sells it.
9
- *
10
- * The mapping onto Better Auth is not one-to-one, and the differences are stated
11
- * per method rather than papered over:
12
- *
13
- * * A factor here is TOTP or nothing. Better Auth models two-factor as a
14
- * property of the user, not as a list of enrolled factors, so `listFactors`
15
- * reports the single TOTP factor rather than an arbitrary set, and there is
16
- * no phone factor to enrol.
17
- * * Enrolment needs the user's password. supabase-js does not ask for one;
18
- * Better Auth does, because enabling two-factor is a credential change.
19
- * * `challenge()` is a local no-op for TOTP: there is nothing to send, the
20
- * code is already on the user's device. It exists so the supabase-js
21
- * challenge/verify sequence compiles unchanged. For the email or SMS second
22
- * factor, `challenge()` does send a code.
23
- */
24
- export interface MfaFactor {
25
- id: string;
26
- /** Always `totp` today. */
27
- factor_type: 'totp';
28
- status: 'verified' | 'unverified';
29
- friendly_name?: string;
30
- }
31
- export interface MfaEnrollResponse {
32
- id: string;
33
- type: 'totp';
34
- totp: {
35
- /** otpauth:// URI to render as a QR code. */
36
- uri: string;
37
- /** The shared secret, for users who type it in by hand. */
38
- secret: string;
39
- };
40
- /** One-time codes to store somewhere safe. Shown only at enrolment. */
41
- backupCodes: string[];
42
- }
43
- export interface MfaChallengeResponse {
44
- id: string;
45
- expires_at: number | null;
46
- }
47
- export declare class MfaClient {
48
- private readonly http;
49
- /** Re-reads the session after a verify, so a stepped-up token is persisted. */
50
- private readonly onVerified;
51
- constructor(http: HttpClient,
52
- /** Re-reads the session after a verify, so a stepped-up token is persisted. */
53
- onVerified: () => Promise<void>);
54
- /**
55
- * Start TOTP enrolment. Returns the otpauth URI, the secret and the backup
56
- * codes. The factor is not usable until `verify()` accepts a code from it.
57
- */
58
- enroll(params: {
59
- password: string;
60
- issuer?: string;
61
- }): Promise<MotherbaseResponse<MfaEnrollResponse>>;
62
- /**
63
- * For TOTP this resolves immediately and sends nothing: the code already lives
64
- * on the user's device. Pass `channel` to send a second-factor code by email
65
- * or SMS instead, when the project has that enabled.
66
- */
67
- challenge(params?: {
68
- factorId?: string;
69
- channel?: 'email' | 'sms';
70
- }): Promise<MotherbaseResponse<MfaChallengeResponse>>;
71
- /**
72
- * Verify a code. `code` is a TOTP code by default; set `type` to `otp` for an
73
- * emailed or texted second factor, or `backup` to spend a recovery code.
74
- */
75
- verify(params: {
76
- code: string;
77
- factorId?: string;
78
- challengeId?: string;
79
- type?: 'totp' | 'otp' | 'backup';
80
- /** Remember this device for the project's configured trust window. */
81
- trustDevice?: boolean;
82
- }): Promise<MotherbaseResponse<{
83
- verified: true;
84
- }>>;
85
- /** Turn two-factor off. Requires the password, as enabling did. */
86
- unenroll(params: {
87
- password: string;
88
- factorId?: string;
89
- }): Promise<MotherbaseResponse<{
90
- id: string;
91
- }>>;
92
- /** Issue a fresh set of backup codes, invalidating the previous set. */
93
- regenerateBackupCodes(params: {
94
- password: string;
95
- }): Promise<MotherbaseResponse<{
96
- backupCodes: string[];
97
- }>>;
98
- /**
99
- * The user's factors. Reads the TOTP URI: getting one back means TOTP is
100
- * enrolled, a failure means it is not. There is no list endpoint to call
101
- * because there is no list, and inventing one client-side would be a lie about
102
- * what the server models.
103
- */
104
- listFactors(): Promise<MotherbaseResponse<{
105
- totp: MfaFactor[];
106
- all: MfaFactor[];
107
- }>>;
108
- }
109
- //# sourceMappingURL=mfa.d.ts.map
package/dist/mfa.d.ts.map DELETED
@@ -1 +0,0 @@
1
- {"version":3,"file":"mfa.d.ts","sourceRoot":"","sources":["../src/mfa.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,WAAW,CAAC;AAC5C,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,YAAY,CAAC;AAErD;;;;;;;;;;;;;;;;;;;;GAoBG;AAEH,MAAM,WAAW,SAAS;IACxB,EAAE,EAAE,MAAM,CAAC;IACX,2BAA2B;IAC3B,WAAW,EAAE,MAAM,CAAC;IACpB,MAAM,EAAE,UAAU,GAAG,YAAY,CAAC;IAClC,aAAa,CAAC,EAAE,MAAM,CAAC;CACxB;AAED,MAAM,WAAW,iBAAiB;IAChC,EAAE,EAAE,MAAM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AAmE;IAC7D,QAAQ,CAAC,MAAM,EAAE;QAAE,QAAQ,EAAE,MAAM,CAAC;QAAC,QAAQ,CAAC,EAAE,MAAM,CAAA;KAAE,GAAG,OAAO,CAAC,kBAAkB,CAAC;QAAE,EAAE,EAAE,MAAM,CAAA;KAAE,CAAC,CAAC;IAS5G,wEAAwE;IAClE,qBAAqB,CAAC,MAAM,EAAE;QAAE,QAAQ,EAAE,MAAM,CAAA;KAAE,GAAG,OAAO,CAAC,kBAAkB,CAAC;QAAE,WAAW,EAAE,MAAM,EAAE,CAAA;KAAE,CAAC,CAAC;IAajH;;;;;OAKG;IACG,WAAW,IAAI,OAAO,CAAC,kBAAkB,CAAC;QAAE,IAAI,EAAE,SAAS,EAAE,CAAC;QAAC,GAAG,EAAE,SAAS,EAAE,CAAA;KAAE,CAAC,CAAC;CAU1F"}
package/dist/mfa.js DELETED
@@ -1,134 +0,0 @@
1
- import { toError } from './http.js';
2
- const R = {
3
- enable: '/api/auth/two-factor/enable',
4
- disable: '/api/auth/two-factor/disable',
5
- totpUri: '/api/auth/two-factor/get-totp-uri',
6
- verifyTotp: '/api/auth/two-factor/verify-totp',
7
- sendOtp: '/api/auth/two-factor/send-otp',
8
- verifyOtp: '/api/auth/two-factor/verify-otp',
9
- verifyBackupCode: '/api/auth/two-factor/verify-backup-code',
10
- generateBackupCodes: '/api/auth/two-factor/generate-backup-codes',
11
- };
12
- export class MfaClient {
13
- constructor(http,
14
- /** Re-reads the session after a verify, so a stepped-up token is persisted. */
15
- onVerified) {
16
- this.http = http;
17
- this.onVerified = onVerified;
18
- }
19
- /**
20
- * Start TOTP enrolment. Returns the otpauth URI, the secret and the backup
21
- * codes. The factor is not usable until `verify()` accepts a code from it.
22
- */
23
- async enroll(params) {
24
- try {
25
- const payload = await this.http.request(R.enable, {
26
- method: 'POST',
27
- body: { password: params.password, ...(params.issuer ? { issuer: params.issuer } : {}) },
28
- raw: true,
29
- });
30
- const uri = payload.totpURI ?? payload.totpUri ?? '';
31
- return {
32
- data: {
33
- // Better Auth has no per-factor id: the user is the factor. `totp` is
34
- // used as a stable handle so unenroll/challenge/verify have something
35
- // to take, matching the supabase-js shape.
36
- id: 'totp',
37
- type: 'totp',
38
- totp: { uri, secret: secretFromUri(uri) },
39
- backupCodes: payload.backupCodes ?? [],
40
- },
41
- error: null,
42
- };
43
- }
44
- catch (err) {
45
- return { data: null, error: toError(err) };
46
- }
47
- }
48
- /**
49
- * For TOTP this resolves immediately and sends nothing: the code already lives
50
- * on the user's device. Pass `channel` to send a second-factor code by email
51
- * or SMS instead, when the project has that enabled.
52
- */
53
- async challenge(params = {}) {
54
- if (!params.channel) {
55
- return { data: { id: params.factorId ?? 'totp', expires_at: null }, error: null };
56
- }
57
- try {
58
- await this.http.request(R.sendOtp, { method: 'POST', body: {}, raw: true });
59
- return { data: { id: params.factorId ?? 'otp', expires_at: null }, error: null };
60
- }
61
- catch (err) {
62
- return { data: null, error: toError(err) };
63
- }
64
- }
65
- /**
66
- * Verify a code. `code` is a TOTP code by default; set `type` to `otp` for an
67
- * emailed or texted second factor, or `backup` to spend a recovery code.
68
- */
69
- async verify(params) {
70
- // All three routes take the code under the same key.
71
- const route = params.type === 'backup' ? R.verifyBackupCode : params.type === 'otp' ? R.verifyOtp : R.verifyTotp;
72
- try {
73
- await this.http.request(route, {
74
- method: 'POST',
75
- body: { code: params.code, ...(params.trustDevice ? { trustDevice: true } : {}) },
76
- raw: true,
77
- });
78
- // Verification can hand back a stepped-up session; adopt it before the
79
- // caller makes its next request with the old one.
80
- await this.onVerified();
81
- return { data: { verified: true }, error: null };
82
- }
83
- catch (err) {
84
- return { data: null, error: toError(err) };
85
- }
86
- }
87
- /** Turn two-factor off. Requires the password, as enabling did. */
88
- async unenroll(params) {
89
- try {
90
- await this.http.request(R.disable, { method: 'POST', body: { password: params.password }, raw: true });
91
- return { data: { id: params.factorId ?? 'totp' }, error: null };
92
- }
93
- catch (err) {
94
- return { data: null, error: toError(err) };
95
- }
96
- }
97
- /** Issue a fresh set of backup codes, invalidating the previous set. */
98
- async regenerateBackupCodes(params) {
99
- try {
100
- const payload = await this.http.request(R.generateBackupCodes, {
101
- method: 'POST',
102
- body: { password: params.password },
103
- raw: true,
104
- });
105
- return { data: { backupCodes: payload.backupCodes ?? [] }, error: null };
106
- }
107
- catch (err) {
108
- return { data: null, error: toError(err) };
109
- }
110
- }
111
- /**
112
- * The user's factors. Reads the TOTP URI: getting one back means TOTP is
113
- * enrolled, a failure means it is not. There is no list endpoint to call
114
- * because there is no list, and inventing one client-side would be a lie about
115
- * what the server models.
116
- */
117
- async listFactors() {
118
- try {
119
- await this.http.request(R.totpUri, { method: 'POST', body: {}, raw: true });
120
- const factor = { id: 'totp', factor_type: 'totp', status: 'verified', friendly_name: 'TOTP' };
121
- return { data: { totp: [factor], all: [factor] }, error: null };
122
- }
123
- catch {
124
- // Not enrolled is a normal state, not an error the caller should branch on.
125
- return { data: { totp: [], all: [] }, error: null };
126
- }
127
- }
128
- }
129
- /** Pull the `secret` query parameter out of an otpauth:// URI. */
130
- function secretFromUri(uri) {
131
- const match = /[?&]secret=([^&]+)/i.exec(uri);
132
- return match ? decodeURIComponent(match[1]) : '';
133
- }
134
- //# sourceMappingURL=mfa.js.map
package/dist/mfa.js.map DELETED
@@ -1 +0,0 @@
1
- {"version":3,"file":"mfa.js","sourceRoot":"","sources":["../src/mfa.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAoDpC,MAAM,CAAC,GAAG;IACR,MAAM,EAAE,6BAA6B;IACrC,OAAO,EAAE,8BAA8B;IACvC,OAAO,EAAE,mCAAmC;IAC5C,UAAU,EAAE,kCAAkC;IAC9C,OAAO,EAAE,+BAA+B;IACxC,SAAS,EAAE,iCAAiC;IAC5C,gBAAgB,EAAE,yCAAyC;IAC3D,mBAAmB,EAAE,4CAA4C;CACzD,CAAC;AAEX,MAAM,OAAO,SAAS;IACpB,YACmB,IAAgB;IACjC,+EAA+E;IA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