@motherbase/client 1.5.0 → 1.5.1

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 (93) hide show
  1. package/dist/admin.d.ts +131 -0
  2. package/dist/admin.d.ts.map +1 -0
  3. package/dist/admin.js +121 -0
  4. package/dist/admin.js.map +1 -0
  5. package/dist/auth.d.ts +459 -0
  6. package/dist/auth.d.ts.map +1 -0
  7. package/dist/auth.js +861 -0
  8. package/dist/auth.js.map +1 -0
  9. package/dist/channel.d.ts +129 -0
  10. package/dist/channel.d.ts.map +1 -0
  11. package/dist/channel.js +215 -0
  12. package/dist/channel.js.map +1 -0
  13. package/dist/compat.d.ts +40 -0
  14. package/dist/compat.d.ts.map +1 -0
  15. package/dist/compat.js +100 -0
  16. package/dist/compat.js.map +1 -0
  17. package/dist/cookie.d.ts +68 -0
  18. package/dist/cookie.d.ts.map +1 -0
  19. package/dist/cookie.js +152 -0
  20. package/dist/cookie.js.map +1 -0
  21. package/dist/database.d.ts +188 -0
  22. package/dist/database.d.ts.map +1 -0
  23. package/dist/database.js +2 -0
  24. package/dist/database.js.map +1 -0
  25. package/dist/functions.d.ts +60 -0
  26. package/dist/functions.d.ts.map +1 -0
  27. package/dist/functions.js +75 -0
  28. package/dist/functions.js.map +1 -0
  29. package/dist/http.d.ts +122 -0
  30. package/dist/http.d.ts.map +1 -0
  31. package/dist/http.js +206 -0
  32. package/dist/http.js.map +1 -0
  33. package/dist/index.d.ts +215 -0
  34. package/dist/index.d.ts.map +1 -0
  35. package/dist/index.js +365 -0
  36. package/dist/index.js.map +1 -0
  37. package/dist/mfa.d.ts +126 -0
  38. package/dist/mfa.d.ts.map +1 -0
  39. package/dist/mfa.js +156 -0
  40. package/dist/mfa.js.map +1 -0
  41. package/dist/organization.d.ts +234 -0
  42. package/dist/organization.d.ts.map +1 -0
  43. package/dist/organization.js +157 -0
  44. package/dist/organization.js.map +1 -0
  45. package/dist/passkey.d.ts +59 -0
  46. package/dist/passkey.d.ts.map +1 -0
  47. package/dist/passkey.js +87 -0
  48. package/dist/passkey.js.map +1 -0
  49. package/dist/pkce.d.ts +13 -0
  50. package/dist/pkce.d.ts.map +1 -0
  51. package/dist/pkce.js +52 -0
  52. package/dist/pkce.js.map +1 -0
  53. package/dist/plugin-endpoint.d.ts +20 -0
  54. package/dist/plugin-endpoint.d.ts.map +1 -0
  55. package/dist/plugin-endpoint.js +24 -0
  56. package/dist/plugin-endpoint.js.map +1 -0
  57. package/dist/postgrest.d.ts +326 -0
  58. package/dist/postgrest.d.ts.map +1 -0
  59. package/dist/postgrest.js +625 -0
  60. package/dist/postgrest.js.map +1 -0
  61. package/dist/query.d.ts +97 -0
  62. package/dist/query.d.ts.map +1 -0
  63. package/dist/query.js +94 -0
  64. package/dist/query.js.map +1 -0
  65. package/dist/realtime.d.ts +114 -0
  66. package/dist/realtime.d.ts.map +1 -0
  67. package/dist/realtime.js +376 -0
  68. package/dist/realtime.js.map +1 -0
  69. package/dist/session.d.ts +47 -0
  70. package/dist/session.d.ts.map +1 -0
  71. package/dist/session.js +136 -0
  72. package/dist/session.js.map +1 -0
  73. package/dist/sso.d.ts +147 -0
  74. package/dist/sso.d.ts.map +1 -0
  75. package/dist/sso.js +35 -0
  76. package/dist/sso.js.map +1 -0
  77. package/dist/storage.d.ts +268 -0
  78. package/dist/storage.d.ts.map +1 -0
  79. package/dist/storage.js +441 -0
  80. package/dist/storage.js.map +1 -0
  81. package/dist/testing.d.ts +38 -0
  82. package/dist/testing.d.ts.map +1 -0
  83. package/dist/testing.js +50 -0
  84. package/dist/testing.js.map +1 -0
  85. package/dist/types.d.ts +348 -0
  86. package/dist/types.d.ts.map +1 -0
  87. package/dist/types.js +2 -0
  88. package/dist/types.js.map +1 -0
  89. package/dist/warn.d.ts +2 -0
  90. package/dist/warn.d.ts.map +1 -0
  91. package/dist/warn.js +23 -0
  92. package/dist/warn.js.map +1 -0
  93. package/package.json +4 -2
package/dist/index.js ADDED
@@ -0,0 +1,365 @@
1
+ import { HttpClient, toError } from './http.js';
2
+ import { contractPath } from '@motherbase/contracts';
3
+ import { SessionStore, memoryStorage, localStorageStorage, keyValueStorage, isKeyValueStorage, SESSION_COOKIE_KEY, } from './session.js';
4
+ import { AuthClient } from './auth.js';
5
+ import { verifierStore } from './pkce.js';
6
+ import { StorageClient } from './storage.js';
7
+ import { FunctionsClient } from './functions.js';
8
+ import { RealtimeModule } from './realtime.js';
9
+ import { RealtimeChannel } from './channel.js';
10
+ import { PostgrestQueryBuilder } from './postgrest.js';
11
+ import { isProduction } from './cookie.js';
12
+ /**
13
+ * Pick the session storage from either options shape.
14
+ *
15
+ * Precedence: the native `storage` (explicit and already the right shape), then
16
+ * supabase-js's `auth.storage` (wrapped if it is a key/value store), then
17
+ * `auth.persistSession` on its own, which in supabase-js means localStorage.
18
+ * Returns `undefined` when nothing was asked for, so the caller can tell "no
19
+ * choice made" from "memory was chosen" and warn accordingly.
20
+ */
21
+ function resolveStorage(options) {
22
+ if (options.storage)
23
+ return options.storage;
24
+ const key = options.auth?.storageKey;
25
+ const provided = options.auth?.storage;
26
+ if (provided) {
27
+ return isKeyValueStorage(provided) ? keyValueStorage(provided, key) : provided;
28
+ }
29
+ if (options.auth?.persistSession === true)
30
+ return localStorageStorage(key);
31
+ if (options.auth?.persistSession === false)
32
+ return memoryStorage();
33
+ return undefined;
34
+ }
35
+ /**
36
+ * Supabase-js-compatible client for a Motherbase backend.
37
+ *
38
+ * Drop-in shaped: `client.from(table).select()…`, `client.auth.signInWithPassword()`,
39
+ * `client.storage.from(bucket)`, `client.channel(name)`, `client.functions.invoke()`.
40
+ *
41
+ * Pass the type generated by `motherbase gen types typescript` to get real
42
+ * inference: `createClient<Database>(url, key)` then types every row, rejects
43
+ * unknown columns in `.select()`, checks `.insert()` payloads against the
44
+ * Insert shape and types `.rpc()` from `Functions`. Without it the client
45
+ * behaves exactly as it did before generics existed.
46
+ */
47
+ export class MotherbaseClient {
48
+ constructor(url,
49
+ /** Accepted for supabase-js signature parity; sent as an `apikey` header when set. */
50
+ key, options = {}) {
51
+ this.url = url;
52
+ this.key = key;
53
+ this.channels = new Map();
54
+ this.requestObservers = new Set();
55
+ // `globalThis.fetch` is a native function that requires `this === window`
56
+ // (or an equivalent global) when invoked: copying the reference without
57
+ // binding it throws "Illegal invocation" the moment it's called as
58
+ // `this.opts.fetch(...)` inside HttpClient. Bind it once here.
59
+ const fetchImpl = options.fetch ?? options.global?.fetch ?? globalThis.fetch?.bind(globalThis);
60
+ if (!fetchImpl) {
61
+ throw new Error('No fetch implementation found. Pass `fetch` in options for this runtime.');
62
+ }
63
+ const autoRefresh = options.autoRefresh ?? options.auth?.autoRefreshToken ?? true;
64
+ const headers = { ...options.global?.headers, ...options.headers };
65
+ if (key)
66
+ headers['apikey'] = key;
67
+ this.compat = options.compat === 'supabase';
68
+ // Tables are served from `public` only. A ported app that made another
69
+ // schema its default would otherwise read `public` under a different name
70
+ // and find the wrong rows (or none), which is far harder to diagnose than
71
+ // the error it gets here. Functions in an exposed schema stay reachable
72
+ // through `client.schema(name).rpc()`.
73
+ const schema = options.db?.schema;
74
+ if (schema && schema !== 'public') {
75
+ throw new Error(`db.schema: '${schema}' is not exposed as the default schema. The Motherbase REST API serves tables from `
76
+ + `public only. Call functions in another schema with client.schema('${schema}').rpc().`);
77
+ }
78
+ // A secret key runs every request as service_role, which bypasses row level
79
+ // security. In a browser it is readable by anyone who opens devtools, so it
80
+ // is not "a key that leaked", it is the whole database published. Warn
81
+ // rather than throw: a legitimate caller may run in a runtime that defines
82
+ // `window` (a test harness, an Electron main process), and refusing to
83
+ // construct would break them for a heuristic.
84
+ if (key?.startsWith('mb_secret_') && typeof window !== 'undefined') {
85
+ console.warn('[motherbase] A secret API key was passed to createClient in a browser context. '
86
+ + 'Secret keys bypass row level security and must stay server side. '
87
+ + 'Use the publishable key here.');
88
+ }
89
+ const storageAdapter = resolveStorage(options);
90
+ // The default adapter keeps the session in memory only: it does not survive
91
+ // a reload, and the server never sees it. That is the right default for a
92
+ // script or a test, and a bug in a browser app, and it presents as
93
+ // "getUser() returns null everywhere", which reads like an auth problem
94
+ // rather than a storage one. Point at the fix once, in development.
95
+ if (!storageAdapter && typeof window !== 'undefined' && !MotherbaseClient.warnedAboutStorage) {
96
+ MotherbaseClient.warnedAboutStorage = true;
97
+ if (!isProduction()) {
98
+ console.warn('[motherbase] createClient() was called in a browser without a `storage` adapter, so the '
99
+ + 'session lives in memory and is lost on reload. Pass `storage: cookieStorage()` (or '
100
+ + '`localStorageStorage()`), or use `createBrowserClient` from `@motherbase/ssr`, which '
101
+ + 'writes the cookie the server needs to read.');
102
+ }
103
+ }
104
+ this.store = new SessionStore(storageAdapter ?? memoryStorage());
105
+ // auth needs the http client, and http needs auth._refresh for the 401 path,
106
+ // so wire them in two steps with a late-bound refresh callback.
107
+ // prefer-const cannot see the closure above: `auth` is read by the refresh
108
+ // callback before this line's assignment happens, so it has to be a `let`.
109
+ // eslint-disable-next-line prefer-const
110
+ let auth;
111
+ this.http = new HttpClient(url, this.store, { autoRefresh, fetch: fetchImpl, headers }, () => auth._refresh());
112
+ const flowType = options.auth?.flowType ?? 'implicit';
113
+ const keyValue = options.auth?.storage && isKeyValueStorage(options.auth.storage) ? options.auth.storage : undefined;
114
+ auth = new AuthClient(this.http, this.store, {
115
+ flowType,
116
+ verifiers: verifierStore(options.auth?.storageKey ?? SESSION_COOKIE_KEY, keyValue),
117
+ });
118
+ this.auth = auth;
119
+ this.storage = new StorageClient(this.http, url, fetchImpl);
120
+ this.functions = new FunctionsClient(this.http);
121
+ this.realtime = new RealtimeModule(url, this.store, fetchImpl, options.realtimeIoFactory);
122
+ // supabase-js finishes an OAuth redirect on its own (detectSessionInUrl
123
+ // defaults to true), so ported code never calls anything after the provider
124
+ // sends the browser back. Do the same, and only when there is actually a
125
+ // token in the fragment: on every other page load this is a no-op with no
126
+ // network call. Opt out with `auth: { detectSessionInUrl: false }`.
127
+ if (options.auth?.detectSessionInUrl !== false
128
+ && typeof window !== 'undefined'
129
+ && window.location?.hash?.includes('access_token=')) {
130
+ void this.auth.getSessionFromUrl();
131
+ }
132
+ // The PKCE equivalent: a `?code=` on the page the provider sent us back to.
133
+ // Stripped from the address bar first, so a reload cannot replay it.
134
+ if (options.auth?.detectSessionInUrl !== false && flowType === 'pkce' && typeof window !== 'undefined') {
135
+ const url = new URL(window.location.href);
136
+ const code = url.searchParams.get('code');
137
+ if (code) {
138
+ url.searchParams.delete('code');
139
+ window.history?.replaceState?.(window.history.state, '', url.href);
140
+ void this.auth.exchangeCodeForSession(code);
141
+ }
142
+ }
143
+ }
144
+ from(table) {
145
+ return new PostgrestQueryBuilder(this.http, table, this.compat);
146
+ }
147
+ /**
148
+ * Call a database function, typed from the generated `Functions` map.
149
+ *
150
+ * The transport is `POST /rest/v1/rpc/<fn>`, which the REST layer gains in
151
+ * Phase 2.8. The typing is independent of that work: it reads only the
152
+ * generated `Database`, so it is correct the moment the route exists.
153
+ *
154
+ * `get` and `head` switch to the read-only forms, which carry their arguments
155
+ * as query parameters rather than as a body, exactly as supabase-js does.
156
+ */
157
+ async rpc(fn, args, options = {}) {
158
+ return this.callRpc('public', fn, args, options);
159
+ }
160
+ /**
161
+ * The one `/rpc/` transport, for `rpc()` and for every `schema(name).rpc()`.
162
+ *
163
+ * A schema other than `public` rides in the profile header PostgREST defines:
164
+ * `Content-Profile` when there is a body, `Accept-Profile` on GET and HEAD.
165
+ * The server serves only the schemas a feature has exposed and answers any
166
+ * other with PGRST106, so nothing here needs to know which ones those are.
167
+ */
168
+ async callRpc(schema, fn, args, options) {
169
+ try {
170
+ const method = options.head ? 'HEAD' : options.get ? 'GET' : 'POST';
171
+ const params = new URLSearchParams();
172
+ if (method !== 'POST') {
173
+ for (const [name, value] of Object.entries((args ?? {}))) {
174
+ if (value === undefined)
175
+ continue;
176
+ params.append(name, Array.isArray(value) ? `{${value.join(',')}}` : String(value));
177
+ }
178
+ }
179
+ const query = params.toString();
180
+ const path = `${contractPath.rest('rpc')}/${encodeURIComponent(fn)}${query ? `?${query}` : ''}`;
181
+ const headers = {};
182
+ if (options.count)
183
+ headers.Prefer = `count=${options.count}`;
184
+ if (schema !== 'public')
185
+ headers[method === 'POST' ? 'Content-Profile' : 'Accept-Profile'] = schema;
186
+ const result = await this.http.requestWithHeaders(path, {
187
+ method,
188
+ body: method === 'POST' ? (args ?? {}) : undefined,
189
+ headers,
190
+ });
191
+ const range = result.headers.get('content-range');
192
+ const total = range?.split('/')[1];
193
+ const count = total && total !== '*' && Number.isFinite(Number(total)) ? Number(total) : null;
194
+ return { data: options.head ? null : result.data, error: null, count };
195
+ }
196
+ catch (err) {
197
+ return { data: null, error: toError(err), count: null };
198
+ }
199
+ }
200
+ /**
201
+ * Watch every HTTP request this client makes.
202
+ *
203
+ * One event per round trip, with method, path, status, duration and the
204
+ * `x-request-id` the server logged it under. That id is the whole point: it
205
+ * is what turns "a query was slow for a user yesterday" into a line in the
206
+ * project's logs.
207
+ *
208
+ * ```ts
209
+ * client.on('request', e => console.log(e.method, e.path, e.status, e.durationMs))
210
+ * ```
211
+ *
212
+ * Returns the unsubscribe function. An observer that throws is ignored: it is
213
+ * a spectator, and a broken logger must not fail the request it was logging.
214
+ */
215
+ on(event, listener) {
216
+ if (event !== 'request')
217
+ throw new Error(`Unknown client event '${String(event)}'. Only 'request' exists.`);
218
+ this.requestObservers.add(listener);
219
+ this.syncRequestObserver();
220
+ return () => {
221
+ this.requestObservers.delete(listener);
222
+ this.syncRequestObserver();
223
+ };
224
+ }
225
+ syncRequestObserver() {
226
+ this.http.setRequestObserver(this.requestObservers.size
227
+ ? (event) => {
228
+ for (const listener of this.requestObservers)
229
+ listener(event);
230
+ }
231
+ : undefined);
232
+ }
233
+ /**
234
+ * Several writes, applied in one database transaction, all or nothing.
235
+ *
236
+ * supabase-js has no equivalent. What people write instead is a sequence of
237
+ * awaited writes inside a `try`, which is not a rollback: whatever already
238
+ * committed stays committed, and the catch block is left holding half a
239
+ * change it cannot undo.
240
+ *
241
+ * The callback does not await anything. It DESCRIBES the writes; they are
242
+ * sent together and applied together:
243
+ *
244
+ * ```ts
245
+ * const { data, error } = await client.transaction(tx => {
246
+ * tx.from('orders').insert({ id, total })
247
+ * tx.from('stock').update({ count: 4 }).eq('sku', sku)
248
+ * })
249
+ * ```
250
+ *
251
+ * `data` is one result array per operation, in the order they were declared.
252
+ * Reads are refused: a batch exists to make writes atomic, and a read in the
253
+ * middle of one invites expectations about ordering that nothing guarantees.
254
+ */
255
+ async transaction(build) {
256
+ const recorded = [];
257
+ const tx = {
258
+ from: ((table) => {
259
+ const builder = new PostgrestQueryBuilder(this.http, table, this.compat);
260
+ recorded.push(builder);
261
+ return builder;
262
+ }),
263
+ };
264
+ try {
265
+ build(tx);
266
+ const operations = recorded.map(builder => {
267
+ const request = builder.toRequest();
268
+ if (request.method === 'GET' || request.method === 'HEAD') {
269
+ throw new Error(`transaction(): '${request.model}' was read, not written. A transaction takes writes only `
270
+ + '(insert, upsert, update, delete).');
271
+ }
272
+ return request;
273
+ });
274
+ if (!operations.length) {
275
+ throw new Error('transaction(): the callback declared no writes.');
276
+ }
277
+ const result = await this.http.request(`${contractPath.rest('batch')}`, {
278
+ method: 'POST',
279
+ body: { operations },
280
+ });
281
+ return { data: result.results, error: null, count: null };
282
+ }
283
+ catch (err) {
284
+ return { data: null, error: toError(err), count: null };
285
+ }
286
+ }
287
+ /** Create (or reuse) a realtime channel. */
288
+ channel(name, opts = {}) {
289
+ const existing = this.channels.get(name);
290
+ if (existing)
291
+ return existing;
292
+ const channel = new RealtimeChannel(name, this.realtime, opts);
293
+ this.channels.set(name, channel);
294
+ return channel;
295
+ }
296
+ /** Every channel this client created, as supabase-js reports them. */
297
+ getChannels() {
298
+ return Array.from(this.channels.values());
299
+ }
300
+ schema(name) {
301
+ if (name === 'public')
302
+ return this;
303
+ const scoped = {
304
+ rpc: (fn, args, options = {}) => this.callRpc(name, fn, args, options),
305
+ from: table => {
306
+ throw new Error(`schema('${name}').from('${table}') is not supported: the Motherbase REST API serves tables from the `
307
+ + `public schema only. Functions in '${name}' can be called with schema('${name}').rpc().`);
308
+ },
309
+ };
310
+ return scoped;
311
+ }
312
+ /** Unsubscribe and drop a channel. */
313
+ async removeChannel(channel) {
314
+ await channel.unsubscribe();
315
+ this.channels.delete(channel.topic);
316
+ return 'ok';
317
+ }
318
+ /** Unsubscribe and drop every channel. */
319
+ async removeAllChannels() {
320
+ await Promise.all(Array.from(this.channels.values()).map(c => c.unsubscribe()));
321
+ this.channels.clear();
322
+ return 'ok';
323
+ }
324
+ /** Load any persisted session before first use. Optional but recommended. */
325
+ hydrate() {
326
+ return this.store.hydrate();
327
+ }
328
+ }
329
+ MotherbaseClient.warnedAboutStorage = false;
330
+ /**
331
+ * Create a Supabase-compatible Motherbase client.
332
+ *
333
+ * In a Next.js app, prefer `createBrowserClient` / `createServerClient` from
334
+ * `@motherbase/ssr`: they persist the session to a cookie both halves can read.
335
+ * `createClient()` on its own keeps the session in memory, which the server
336
+ * cannot see, so every server-rendered `getUser()` returns null.
337
+ *
338
+ * @param url Backend API base URL.
339
+ * @param key Anon/publishable key (optional). Sent as an `apikey` header.
340
+ * @param options Session storage, fetch override, extra headers.
341
+ *
342
+ * @example
343
+ * ```ts
344
+ * import type { Database } from './database.types'
345
+ * const client = createClient<Database>(url, anonKey)
346
+ * ```
347
+ */
348
+ export function createClient(url, key, options = {}) {
349
+ return new MotherbaseClient(url, key, options);
350
+ }
351
+ export { BackendError } from './http.js';
352
+ export { memoryStorage, localStorageStorage, keyValueStorage };
353
+ export { normalizeSession, normalizeUser } from './compat.js';
354
+ export { cookieStorage, serverCookieStorage, SESSION_COOKIE_KEY } from './cookie.js';
355
+ export { PostgrestQueryBuilder } from './postgrest.js';
356
+ export { AuthClient } from './auth.js';
357
+ export { MfaClient } from './mfa.js';
358
+ export { AuthAdminClient } from './admin.js';
359
+ export { OrganizationClient } from './organization.js';
360
+ export { PasskeyClient } from './passkey.js';
361
+ export { SsoClient } from './sso.js';
362
+ export { StorageClient, StorageBucket } from './storage.js';
363
+ export { FunctionsClient, FunctionsError, FunctionsHttpError, FunctionsRelayError, FunctionsFetchError } from './functions.js';
364
+ export { RealtimeChannel } from './channel.js';
365
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAEhD,OAAO,EAAE,YAAY,EAAE,MAAM,uBAAuB,CAAC;AACrD,OAAO,EACL,YAAY,EACZ,aAAa,EACb,mBAAmB,EACnB,eAAe,EACf,iBAAiB,EACjB,kBAAkB,GACnB,MAAM,cAAc,CAAC;AACtB,OAAO,EAAE,UAAU,EAAE,MAAM,WAAW,CAAC;AACvC,OAAO,EAAE,aAAa,EAAE,MAAM,WAAW,CAAC;AAC1C,OAAO,EAAE,aAAa,EAAE,MAAM,cAAc,CAAC;AAC7C,OAAO,EAAE,eAAe,EAAE,MAAM,gBAAgB,CAAC;AACjD,OAAO,EAAE,cAAc,EAAE,MAAM,eAAe,CAAC;AAC/C,OAAO,EAAE,eAAe,EAA+B,MAAM,cAAc,CAAC;AAC5E,OAAO,EAAE,qBAAqB,EAAE,MAAM,gBAAgB,CAAC;AAGvD,OAAO,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AA0D3C;;;;;;;;GAQG;AACH,SAAS,cAAc,CAAC,OAAsB;IAC5C,IAAI,OAAO,CAAC,OAAO;QAAE,OAAO,OAAO,CAAC,OAAO,CAAC;IAE5C,MAAM,GAAG,GAAG,OAAO,CAAC,IAAI,EAAE,UAAU,CAAC;IACrC,MAAM,QAAQ,GAAG,OAAO,CAAC,IAAI,EAAE,OAAO,CAAC;IACvC,IAAI,QAAQ,EAAE,CAAC;QACb,OAAO,iBAAiB,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC,eAAe,CAAC,QAAQ,EAAE,GAAG,CAAC,C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AAC;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;AAY7C,OAAO,EAAE,kBAAkB,EAAE,MAAM,mBAAmB,CAAC;AAYvD,OAAO,EAAE,aAAa,EAAE,MAAM,cAAc,CAAC;AAE7C,OAAO,EAAE,SAAS,EAAE,MAAM,UAAU,CAAC;AAsBrC,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 ADDED
@@ -0,0 +1,126 @@
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 type AuthenticatorAssuranceLevel = 'aal1' | 'aal2';
44
+ export interface MfaChallengeResponse {
45
+ id: string;
46
+ expires_at: number | null;
47
+ }
48
+ export declare class MfaClient {
49
+ private readonly http;
50
+ /** Re-reads the session after a verify, so a stepped-up token is persisted. */
51
+ private readonly onVerified;
52
+ constructor(http: HttpClient,
53
+ /** Re-reads the session after a verify, so a stepped-up token is persisted. */
54
+ onVerified: () => Promise<void>);
55
+ /**
56
+ * Start TOTP enrolment. Returns the otpauth URI, the secret and the backup
57
+ * codes. The factor is not usable until `verify()` accepts a code from it.
58
+ */
59
+ enroll(params: {
60
+ password: string;
61
+ issuer?: string;
62
+ }): Promise<MotherbaseResponse<MfaEnrollResponse>>;
63
+ /**
64
+ * For TOTP this resolves immediately and sends nothing: the code already lives
65
+ * on the user's device. Pass `channel` to send a second-factor code by email
66
+ * or SMS instead, when the project has that enabled.
67
+ */
68
+ challenge(params?: {
69
+ factorId?: string;
70
+ channel?: 'email' | 'sms';
71
+ }): Promise<MotherbaseResponse<MfaChallengeResponse>>;
72
+ /**
73
+ * Verify a code. `code` is a TOTP code by default; set `type` to `otp` for an
74
+ * emailed or texted second factor, or `backup` to spend a recovery code.
75
+ */
76
+ verify(params: {
77
+ code: string;
78
+ factorId?: string;
79
+ challengeId?: string;
80
+ type?: 'totp' | 'otp' | 'backup';
81
+ /** Remember this device for the project's configured trust window. */
82
+ trustDevice?: boolean;
83
+ }): Promise<MotherbaseResponse<{
84
+ verified: true;
85
+ }>>;
86
+ /** Turn two-factor off. Requires the password, as enabling did. */
87
+ unenroll(params: {
88
+ password: string;
89
+ factorId?: string;
90
+ }): Promise<MotherbaseResponse<{
91
+ id: string;
92
+ }>>;
93
+ /** Issue a fresh set of backup codes, invalidating the previous set. */
94
+ regenerateBackupCodes(params: {
95
+ password: string;
96
+ }): Promise<MotherbaseResponse<{
97
+ backupCodes: string[];
98
+ }>>;
99
+ /**
100
+ * Where this session stands, supabase-js style. `currentLevel` is `aal2`
101
+ * once the session passed a second factor (the server marks it then);
102
+ * `nextLevel` is `aal2` when the user has one to pass. `currentLevel` below
103
+ * `nextLevel` means: ask for the code before anything sensitive.
104
+ * `currentAuthenticationMethods` is always empty: sessions do not record
105
+ * which methods produced them.
106
+ */
107
+ getAuthenticatorAssuranceLevel(): Promise<MotherbaseResponse<{
108
+ currentLevel: AuthenticatorAssuranceLevel | null;
109
+ nextLevel: AuthenticatorAssuranceLevel | null;
110
+ currentAuthenticationMethods: Array<{
111
+ method: string;
112
+ timestamp: number;
113
+ }>;
114
+ }>>;
115
+ /**
116
+ * The user's factors. Reads the TOTP URI: getting one back means TOTP is
117
+ * enrolled, a failure means it is not. There is no list endpoint to call
118
+ * because there is no list, and inventing one client-side would be a lie about
119
+ * what the server models.
120
+ */
121
+ listFactors(): Promise<MotherbaseResponse<{
122
+ totp: MfaFactor[];
123
+ all: MfaFactor[];
124
+ }>>;
125
+ }
126
+ //# sourceMappingURL=mfa.d.ts.map
@@ -0,0 +1 @@
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;IAC3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