@proveanything/smartlinks 2.1.18 → 2.1.20

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 (53) hide show
  1. package/dist/adminViews.d.ts +19 -0
  2. package/dist/adminViews.js +16 -0
  3. package/dist/api/ai.d.ts +15 -5
  4. package/dist/api/ai.js +15 -9
  5. package/dist/api/aiGuide.d.ts +110 -0
  6. package/dist/api/aiGuide.js +162 -0
  7. package/dist/api/appObjects.d.ts +21 -0
  8. package/dist/api/appObjects.js +33 -1
  9. package/dist/api/authKit.d.ts +37 -1
  10. package/dist/api/authKit.js +51 -0
  11. package/dist/docs/API_SUMMARY.md +510 -40
  12. package/dist/docs/admin-lists-and-pickers.md +140 -0
  13. package/dist/docs/admin-views.md +22 -0
  14. package/dist/docs/app-data-storage.md +277 -276
  15. package/dist/docs/auth-kit.md +872 -741
  16. package/dist/docs/comms.md +686 -644
  17. package/dist/docs/customer-guide.md +70 -0
  18. package/dist/docs/headless-providers.md +112 -112
  19. package/dist/docs/server-functions.md +69 -1
  20. package/dist/docs/ui-utils.md +123 -121
  21. package/dist/docs/user-groups.md +175 -168
  22. package/dist/headless.js +38 -2
  23. package/dist/http.js +4 -0
  24. package/dist/index.d.ts +2 -2
  25. package/dist/live.d.ts +88 -0
  26. package/dist/live.js +357 -0
  27. package/dist/openapi.yaml +888 -34
  28. package/dist/testing/index.d.ts +22 -0
  29. package/dist/testing/index.js +31 -0
  30. package/dist/types/appManifest.d.ts +214 -1
  31. package/dist/types/appOptions.d.ts +32 -0
  32. package/dist/types/appOptions.js +3 -0
  33. package/dist/types/authKit.d.ts +193 -4
  34. package/dist/types/comms.d.ts +41 -2
  35. package/dist/types/headless.d.ts +49 -1
  36. package/dist/types/iframeResponder.d.ts +1 -1
  37. package/dist/types/index.d.ts +1 -0
  38. package/dist/types/index.js +1 -0
  39. package/docs/API_SUMMARY.md +510 -40
  40. package/docs/admin-lists-and-pickers.md +140 -0
  41. package/docs/admin-views.md +22 -0
  42. package/docs/app-data-storage.md +277 -276
  43. package/docs/auth-kit.md +872 -741
  44. package/docs/comms.md +686 -644
  45. package/docs/customer-guide.md +70 -0
  46. package/docs/headless-providers.md +112 -112
  47. package/docs/server-functions.md +69 -1
  48. package/docs/ui-utils.md +123 -121
  49. package/docs/user-groups.md +175 -168
  50. package/openapi.yaml +888 -34
  51. package/package.json +1 -1
  52. package/scripts/doctor.mjs +454 -428
  53. package/scripts/lib/keyed-app-data.mjs +21 -0
@@ -1,741 +1,872 @@
1
- # SmartLinks Auth Kit (`@proveanything/smartlinks` — `authKit` namespace)
2
-
3
- > End-user authentication flows for SmartLinks microapps. Covers email/password, magic links, phone OTP, Google OAuth, profile management, and password/email change flows.
4
- >
5
- > **This is part of the core SDK** — no separate install required. Import from `@proveanything/smartlinks`.
6
-
7
- ---
8
-
9
- ## What is Auth Kit for?
10
-
11
- Auth Kit is the **end-user identity layer** for microapps that need users to sign in. It is distinct from the admin/platform authentication (Bearer tokens) used to call admin endpoints.
12
-
13
- Use Auth Kit when:
14
- - Your app has a login/register screen for end users (not collection admins)
15
- - You need to gate features behind a verified user identity
16
- - You want to store user-specific data with the `userAppData` API (see [app-data-storage.md](app-data-storage.md))
17
-
18
- Do **not** use Auth Kit for:
19
- - Admin-side API calls (those use Bearer tokens set by the platform shell)
20
- - Claiming proofs (see proof claiming methods)
21
-
22
- ---
23
-
24
- ## Setup: creating an Auth Kit client
25
-
26
- Each app requires an Auth Kit configuration, created by a collection admin:
27
-
28
- ```ts
29
- // Admin setup (one-time, done in admin console)
30
- import { authKit } from '@proveanything/smartlinks';
31
-
32
- // Returns an authKitId to store in your app config
33
- const config = await authKit.create(collectionId, {
34
- name: 'My App Auth',
35
- loginMethods: ['email', 'google', 'magic_link'],
36
- redirectUrl: 'https://myapp.example.com/auth/callback',
37
- });
38
- ```
39
-
40
- ---
41
-
42
- ## Key flows
43
-
44
- ### Email / password
45
-
46
- ```ts
47
- import { authKit } from '@proveanything/smartlinks';
48
-
49
- // Register
50
- const session = await authKit.register(clientId, {
51
- email: 'user@example.com',
52
- password: 'securePassword123',
53
- displayName: 'Alice',
54
- });
55
-
56
- // Login
57
- const session = await authKit.login(clientId, 'user@example.com', 'securePassword123');
58
-
59
- // session.token — store this; pass to initializeApi for subsequent calls
60
- ```
61
-
62
- ### Magic link (passwordless email)
63
-
64
- ```ts
65
- await authKit.sendMagicLink(clientId, {
66
- email: 'user@example.com',
67
- redirectUrl: 'https://myapp.example.com/auth/verify',
68
- });
69
-
70
- // On callback page, extract token from URL and verify
71
- const session = await authKit.verifyMagicLink(clientId, tokenFromUrl);
72
- ```
73
-
74
- ### Phone OTP
75
-
76
- ```ts
77
- await authKit.sendPhoneCode(clientId, '+61400000000');
78
- const session = await authKit.verifyPhoneCode(clientId, '+61400000000', '123456');
79
- ```
80
-
81
- ### Lightweight verification (WhatsApp + SMS)
82
-
83
- Use these flows when you want low-friction verification before or without full account sign-in.
84
-
85
- WhatsApp verification is token-first. The user does not type their phone number in your app for this flow; phone ownership is proven by the inbound WhatsApp sender number.
86
-
87
- ```ts
88
- import { authKit } from '@proveanything/smartlinks';
89
-
90
- // 1) Send WhatsApp verification deep link
91
- const wa = await authKit.sendWhatsApp(clientId);
92
-
93
- // Optional: pass redirect context and/or a post-verification reply
94
- // const wa = await authKit.sendWhatsApp(clientId, {
95
- // redirectUrl: 'https://app.example.com/checkout/continue',
96
- // prefillMessage: 'Please let me bid in this auction. Code: {{token}}',
97
- // contactData: {
98
- // name: 'Jane Doe',
99
- // email: 'jane@example.com',
100
- // source: 'auction-checkout',
101
- // customFields: { agreedToTerms: true },
102
- // },
103
- // reply: {
104
- // cta: {
105
- // body: "You're verified and ready to bid.",
106
- // buttonLabel: 'Back to Auction',
107
- // buttonUrl: '{{returnUrl}}',
108
- // // mediaUrl: 'https://cdn.example.com/bid-confirmed.jpg', // optional: include to use image card template
109
- // },
110
- // text: "You're verified. Return to the app to continue.",
111
- // },
112
- // });
113
-
114
- // wa.waLink can be opened directly by the app/browser
115
- // Poll status while user switches to WhatsApp and back
116
- const status = await authKit.getWhatsAppStatus(clientId, wa.token);
117
-
118
- // Optional: exchange verified WhatsApp proof for an Auth Kit session
119
- if (status.status === 'verified' && wa.sessionKey) {
120
- const session = await authKit.exchangeWhatsAppSession(clientId, wa.token, wa.sessionKey);
121
- // session.token can be used as the authenticated bearer token
122
- }
123
-
124
- // Optional legacy fallback path if webhook confirmation is unavailable
125
- await authKit.verifyWhatsApp(clientId, wa.token, '+447911123456');
126
-
127
- // 2) Or send SMS click-to-verify link
128
- await authKit.sendSmsVerify(clientId, {
129
- phoneNumber: '+447911123456',
130
- redirectUrl: 'https://app.example.com/raffle/checkout',
131
- ctaText: 'Tap to continue',
132
- });
133
-
134
- // Optional API verification path
135
- await authKit.verifySms(clientId, '<token>', '+447911123456');
136
- ```
137
-
138
- `contactData` is optional and is useful when you collect name/email before the customer switches to WhatsApp.
139
-
140
- - Auth Kit stores `contactData` on the verification token metadata first.
141
- - Contact details are written to durable contact storage only after WhatsApp verification succeeds.
142
- - If the user abandons before verification, no contact is created.
143
- - `contactData` must not include phone; the verified inbound WhatsApp sender number is always authoritative.
144
-
145
- ### Contact bootstrap / durable identity
146
-
147
- After verification, upsert contact identity and store `contactId` on downstream records (raffle ticket, bid, claim intent).
148
-
149
- ```ts
150
- const contact = await authKit.upsertContact(clientId, {
151
- phone: '+447911123456',
152
- name: 'Jane Doe',
153
- source: 'raffle-checkout',
154
- customFields: { channelVerified: 'whatsapp' },
155
- externalIds: { raffleSessionId: 'rfl_123' },
156
- });
157
-
158
- // Persist these on your business record
159
- // contact.contactId, contact.collectionId, verified channel, verifiedAt
160
- ```
161
-
162
- Verification status values returned by `authKit.getWhatsAppStatus` are:
163
- - `pending`
164
- - `verified`
165
- - `failed`
166
- - `expired`
167
- - `unknown`
168
-
169
- #### Post-verification reply
170
-
171
- Pass a `reply` object in `sendWhatsApp` to send a message back to the user after they confirm `CONFIRM <token>`. Reply resolution order:
172
-
173
- 1. `reply.contentSid` — explicit Twilio Content SID
174
- 2. `reply.cta` — CTA shorthand:
175
- - If `cta.mediaUrl` is present (valid public `https://` URL), uses the **image card** Twilio Content template (`TWILIO_WHATSAPP_IMAGE_CTA_SID`)
176
- - Otherwise uses the **text CTA** template (`TWILIO_WHATSAPP_GENERIC_CTA_SID`)
177
- 3. `reply.text` — plain-text fallback
178
- 4. Per-client default (`authKit/{clientId}.whatsapp` config)
179
- 5. Built-in default text
180
-
181
- > **Important:** Only pass `mediaUrl` when you have a valid, publicly reachable `https://` JPEG or PNG. If the field is absent or blank, the text-only CTA template is selected automatically. Never pass an empty string — omit the field entirely to avoid Twilio rejecting the send.
182
-
183
- The following template placeholders are available in `reply.text`, `reply.cta` fields, and `reply.contentVariables` values:
184
-
185
- | Placeholder | Description |
186
- |---|---|
187
- | `{{returnUrl}}` | The resolved redirect URL |
188
- | `{{phoneNumber}}` | The verified phone number |
189
- | `{{clientId}}` | The Auth Kit client ID |
190
- | `{{token}}` | The verification token |
191
-
192
- You can also set `prefillMessage` on `sendWhatsApp` to customize the text pre-filled in the `wa.me` deep link. If `{{token}}` is not present, the token is appended to the message.
193
-
194
- #### Session exchange after verification
195
-
196
- After polling returns `status === 'verified'`, exchange the verification proof for an Auth Kit login session:
197
-
198
- ```ts
199
- const session = await authKit.exchangeWhatsAppSession(clientId, wa.token, wa.sessionKey!);
200
- // session: { success, token, user, accountData? }
201
- ```
202
-
203
- `sessionKey` is returned by `sendWhatsApp` and is used to mitigate token replay from contexts that did not initiate the browser flow.
204
-
205
- When `contactData.name` or explicit name parts were supplied on the original `sendWhatsApp` call, `session.user.displayName` and the returned bearer token claims are now seeded from the verified contact record instead of staying `null`.
206
-
207
- > **Note:** `redirectUrl` is optional. WhatsApp tokens are short hex strings (16 chars) for better UX.
208
- >
209
- > **Legacy note:** `verifyWhatsApp` is for older phone-bound token flows. Prefer inbound WhatsApp token confirmation plus status polling for new implementations.
210
-
211
- ### Google OAuth
212
-
213
- ```ts
214
- // After Google sign-in, pass the id_token to Auth Kit
215
- const session = await authKit.googleLogin(clientId, googleIdToken);
216
- ```
217
-
218
- ### Sign in with Apple
219
-
220
- Pass the Apple **identity token** (a JWT). On iOS/native it's
221
- `ASAuthorizationAppleIDCredential.identityToken` (UTF-8 decoded); on web it's
222
- `response.authorization.id_token` from Apple JS.
223
-
224
- ```ts
225
- const session = await authKit.appleLogin(clientId, appleIdentityToken, {
226
- // All optional:
227
- nonce, // raw nonce, if you used nonce binding
228
- userInfo: { name, email }, // first authorization callback ONLY — Apple never resends it
229
- trustedDeviceToken, // skip an MFA step-up challenge on a recognized device — see "Step-up MFA" below
230
- });
231
- // session.isNewUser and session.expiresAt (ms epoch) are populated by this endpoint.
232
- ```
233
-
234
- Apple returns the user's name/email **only on the very first authorization, ever**, and
235
- never inside the token. Capture it from that first callback and forward it via `userInfo`
236
- so the server can seed the display name — it's treated as untrusted and never used for identity.
237
-
238
- Apple login requires the client's AuthKit config to list allowed audiences in
239
- `appleClientIds`; until then the endpoint returns `400 APPLE_AUTH_NOT_CONFIGURED`.
240
-
241
- #### Verified-to-verified account linking (affects Google too)
242
-
243
- Both `appleLogin` and `googleLogin` now refuse to silently merge a federated login into a
244
- pre-existing account whose email is **unverified**. Instead they throw
245
- `SmartlinksApiError` with `errorCode === 'ACCOUNT_EXISTS_UNVERIFIED'` (409) and
246
- `err.details?.requiresEmailVerification === true`. Treat this as recoverable, not fatal:
247
-
248
- ```ts
249
- try {
250
- const session = await authKit.appleLogin(clientId, appleIdentityToken);
251
- } catch (err) {
252
- if (err instanceof SmartlinksApiError && err.errorCode === 'ACCOUNT_EXISTS_UNVERIFIED') {
253
- // "An account with this email exists but isn't verified. Sign in with your
254
- // password (or reset it), then link Apple/Google from settings."
255
- }
256
- }
257
- ```
258
-
259
- > ⚠️ This is a behaviour change for `googleLogin`, which previously merged silently in
260
- > this case. Handle the 409 for both methods.
261
-
262
- ### Sign in with Microsoft
263
-
264
- Work or school accounts from **any** organisation, and personal Microsoft accounts (Outlook, Hotmail,
265
- Live). Add `'microsoft'` to `enabledProviders` — that's all: SmartLinks' own Microsoft app serves every
266
- organisation, so neither you nor your users' IT registers anything.
267
-
268
- ```ts
269
- const session = await authKit.microsoftLogin(clientId, microsoftIdToken, { returnOrigin });
270
- ```
271
-
272
- - **In the SmartLinks sign-in UI** the Microsoft button opens SmartLinks' Microsoft sign-in page
273
- (`https://smartlinks.app/apps/account/stable/microsoft-proxy.html`) in a popup — the one address
274
- registered with Microsoft — which signs in and hands the session back to your site. Your site must be
275
- one of the login setup's own (its collections' domains or site addresses, or `allowedRedirectDomains`),
276
- else `MICROSOFT_ORIGIN_NOT_ALLOWED` (403).
277
- - **Your own UI:** get an ID token from Microsoft (`response_type=id_token`, scope `openid profile email`,
278
- authority `https://login.microsoftonline.com/common`) for the app in the public config's
279
- `microsoftClientId`, and pass it here.
280
- - **Some companies' IT approves new apps for their staff.** The first person from such a company sees
281
- "needs admin approval"; their IT approves SmartLinks once for the organisation and everyone can sign in.
282
- - **Your own name on Microsoft's screen (optional):** register your own *multitenant* app in Microsoft
283
- Entra (Supported account types: any organisation + personal accounts; Web redirect URI as above, with
284
- "ID tokens" ticked; token configuration: optional claim `xms_edov` on the ID token) and set its
285
- Application (client) ID as `microsoftClientId`.
286
- - A Microsoft account's email is trusted only when Microsoft vouches that its organisation owns the
287
- domain (or for personal accounts): an organisation can give its users any address. Linking to an
288
- existing account by email follows the same verified-to-verified rule as Google and Apple.
289
-
290
- ### Who can sign in (`access`)
291
-
292
- Restrict a login setup to one organisation — no keys, no IT:
293
-
294
- ```ts
295
- await authKit.update(collectionId, clientId, {
296
- access: { mode: 'organisation', domains: ['acme.com'], emails: ['contractor@gmail.com'] },
297
- });
298
- ```
299
-
300
- - Someone is from acme.com when their **verified** email is at acme.com, they're one of `emails`, or they
301
- signed in with Microsoft from acme's own Microsoft organisation (looked up from the domain when you
302
- save — `microsoftTenants` is filled in for you).
303
- - Checked on **every** sign-in method each time a session is issued: everyone else gets
304
- `NOT_IN_ORGANISATION` (403) with a message naming the domain. Tighten the rule and people already in
305
- are refused from their next sign-in.
306
- - `register` refuses outside addresses before making anything, and never signs an unverified address
307
- straight in (even in `immediate` mode) — it must be verified first.
308
- - Phone-only and WhatsApp-only accounts have no email to prove an organisation, so they can't get in.
309
- - The public config (`load`) returns `access: { mode, domains }` so your page can say who it's for; the
310
- `emails` list is never public. `{ mode: 'anyone' }` (or no `access`) lets everyone in, as before.
311
-
312
- ### Refresh tokens (native sessions)
313
-
314
- Native/Capacitor hosts can hold long-lived sessions via refresh tokens. Opt in **once**
315
- at startup so every request carries `X-Client-Platform: native`:
316
-
317
- ```ts
318
- initializeApi({ baseURL, platform: 'native' });
319
- ```
320
-
321
- With the opt-in active, the login endpoints (`login`, `register` in immediate mode,
322
- `googleLogin`, `appleLogin`, `verifyPhoneCode`, `verifyMagicLink`,
323
- `exchangeWhatsAppSession`) additionally return `refreshToken`, `refreshTokenExpiresAt`
324
- (absolute, fixed, ms epoch), and a **short-lived** access `token`. Web clients are
325
- unaffected and receive the unchanged response.
326
-
327
- ```ts
328
- // Later — exchange the refresh token for a fresh access token.
329
- const r = await authKit.refreshToken(clientId, storedRefreshToken);
330
- // r.refreshToken is ROTATED — persist it and discard the old one BEFORE the next call.
331
- // The SDK already swapped in r.token as the active bearer for you.
332
- persist(r.refreshToken, r.refreshTokenExpiresAt);
333
-
334
- // On explicit sign-out — revokes the whole device family server-side + clears the bearer.
335
- await authKit.logout(clientId, storedRefreshToken);
336
- clearPersistedTokens();
337
- ```
338
-
339
- **Rotation rules the host MUST respect:**
340
-
341
- 1. **Single-use + rotation.** Every `refreshToken()` returns a new token. Persist it and
342
- overwrite the old one *before* the next call.
343
- 2. **Serialize refreshes.** Fire a single in-flight refresh and queue callers behind it —
344
- the SDK does **not** serialize for you, and racing two refreshes spends the same token.
345
- 3. **Reuse = family death.** Replaying a consumed token throws
346
- `SmartlinksApiError` with `errorCode === 'REFRESH_TOKEN_REUSE_DETECTED'`; treat as a
347
- hard logout (clear storage, force re-login). `INVALID_REFRESH_TOKEN` (expired/revoked)
348
- is handled the same way.
349
- 4. **Absolute expiry is fixed.** `refreshTokenExpiresAt` never moves on rotation; once it
350
- passes (default 90 days) the user must log in again.
351
-
352
- > Resume-refresh scheduling and transparent refresh-on-401 are the responsibility of the
353
- > host/auth-ui layer, not this SDK — the SDK only exposes the `refreshToken()` / `logout()`
354
- > primitives and the `platform` opt-in.
355
-
356
- ---
357
-
358
- ## Step-up MFA
359
-
360
- Factors: **email code, SMS code, authenticator app (`totp`), recovery codes**. The shared login UI
361
- (`@proveanything/smartlinks-auth-ui`) has the challenge and the Settings → Security screens. WhatsApp
362
- codes and passkeys are planned; don't build against them yet.
363
-
364
- **Authenticator apps** (Google Authenticator, Microsoft Authenticator, 1Password, Authy…) are the
365
- recommended second step: nothing is sent (no SMS cost, nothing to intercept), and they are offered first
366
- when someone has one. A client can switch any factor off with `mfa.factorsEnabled` (e.g.
367
- `{ totp: false }`).
368
-
369
- The step-up gate applies to **every login method that issues a session**:
370
-
371
- | Method | Gated? |
372
- |---|---|
373
- | `login()` | ✅ |
374
- | `googleLogin()` | ✅ |
375
- | `appleLogin()` | ✅ — pass `opts.trustedDeviceToken` |
376
- | `verifyPhoneCode()` | ✅ |
377
- | `verifyMagicLink()` | ✅ |
378
- | `exchangeWhatsAppSession()` | ✅ — **this is the WhatsApp method that needs a trusted-device token, not `verifyWhatsApp()`** |
379
- | `verifyWhatsApp()` | ❌ — only confirms the code, never issues a session, so there's nothing to gate |
380
- | `register()` | ❌ — a brand-new user has no enrolled factors to challenge against |
381
- | `googleCodeLogin()` | ❌ — no `/auth/google-code` route exists server-side |
382
-
383
- All six gated methods accept an optional `trustedDeviceToken` param (the last positional
384
- argument, or `opts.trustedDeviceToken` for `appleLogin()`) — same purpose everywhere: skip
385
- the challenge on a device the user already verified.
386
-
387
- ### Handling `MFA_REQUIRED`
388
-
389
- Every gated method's return type is unchanged. When the client's MFA policy requires a
390
- step-up, the server returns 403 instead of a session, and the method throws — identically
391
- for all six:
392
-
393
- ```ts
394
- import { authKit, SmartlinksApiError } from '@proveanything/smartlinks';
395
-
396
- try {
397
- const session = await authKit.login(clientId, email, password);
398
- // logged in, no MFA required
399
- } catch (err) {
400
- if (err instanceof SmartlinksApiError && err.errorCode === 'MFA_REQUIRED') {
401
- const { mfaSessionToken, availableFactors, preferredFactor, maskedDestinations } = err.details!;
402
- // → route to a challenge UI; call authKit.mfaChallengeSend(clientId, mfaSessionToken, preferredFactor)
403
- } else {
404
- throw err;
405
- }
406
- }
407
- ```
408
-
409
- ### Completing the challenge
410
-
411
- ```ts
412
- // Send (or resend, or switch factor) a code on the same mfaSessionToken
413
- const sent = await authKit.mfaChallengeSend(clientId, mfaSessionToken, 'sms');
414
- // sent.destination is masked, e.g. "+1******1234"
415
-
416
- // Verify the code — behaves like login() on success: bearer token is adopted automatically
417
- const session = await authKit.mfaChallengeVerify(clientId, mfaSessionToken, '123456', /* trustDevice */ true, 'My Laptop');
418
-
419
- // Or finalize with a single-use recovery code instead
420
- const session = await authKit.mfaRecoveryCode(clientId, mfaSessionToken, recoveryCode);
421
- ```
422
-
423
- `mfaSessionToken` is short-lived (10 min) and single-use — burned on 5 failed attempts
424
- (`MFA_TOO_MANY_ATTEMPTS`) or on success. Once burned/expired, there's no "resend within the
425
- same session" — the caller must restart from `login()`.
426
-
427
- ### Trusted devices — "don't ask again on this device"
428
-
429
- There's no fingerprinting involved: a "recognized device" is purely "the caller presented a
430
- valid, unexpired, unrevoked `trustedDeviceToken`". Handle it like the native refresh token
431
- above — same secure storage, same persist-before-next-call discipline:
432
-
433
- ```ts
434
- // 1) Persist trustedDeviceToken from a successful challenge (trustDevice: true)
435
- persistTrustedDeviceToken(session.trustedDeviceToken, session.trustedDeviceExpiresAt);
436
-
437
- // 2) Send it on every subsequent call to ANY of the six gated methods — if still valid,
438
- // the challenge is skipped entirely. It isn't tied to which method the user challenged
439
- // through, so "remember this device" works no matter which login method they pick next.
440
- const session = await authKit.login(clientId, email, password, storedTrustedDeviceToken);
441
- const session = await authKit.googleLogin(clientId, idToken, storedTrustedDeviceToken);
442
- const session = await authKit.exchangeWhatsAppSession(clientId, waToken, sessionKey, storedTrustedDeviceToken);
443
- // ...and so on for appleLogin (via opts), verifyPhoneCode, verifyMagicLink.
444
- // If it's revoked/expired, the server silently falls back to requiring a fresh challenge —
445
- // the method just throws MFA_REQUIRED again, no special-case handling needed.
446
-
447
- // 3) Let users audit/revoke devices from a Settings screen
448
- const { devices } = await authKit.listTrustedDevices(clientId);
449
- await authKit.revokeTrustedDevice(clientId, deviceId);
450
- ```
451
-
452
- ### Factor management (Settings → Security)
453
-
454
- Authenticated (bearer token) — same `mfaSessionToken` + code mechanism as login challenges,
455
- just against a `purpose: 'enroll'` challenge instead of `'login'`.
456
-
457
- ```ts
458
- // Enroll email (uses the account's existing email)
459
- const { mfaSessionToken } = await authKit.enrollEmailMfa(clientId);
460
- await authKit.confirmEmailMfa(clientId, mfaSessionToken, code);
461
-
462
- // Enroll SMS
463
- const { mfaSessionToken: smsToken } = await authKit.enrollSmsMfa(clientId, '+61400000000');
464
- await authKit.confirmSmsMfa(clientId, smsToken, code);
465
-
466
- // Enroll an authenticator app: show otpauthUri as a QR code (and secret for typing in),
467
- // then confirm with the 6-digit code the app shows
468
- const { mfaSessionToken: appToken, otpauthUri, secret } = await authKit.enrollTotpMfa(clientId);
469
- await authKit.confirmTotpMfa(clientId, appToken, codeFromApp);
470
-
471
- // Recovery codes — plaintext, shown exactly once; nothing else in the API returns them again
472
- const { recoveryCodes } = await authKit.generateMfaRecoveryCodes(clientId, password);
473
-
474
- // Inspect / remove
475
- const factors = await authKit.getMfaFactors(clientId);
476
- // factors: { enrolledFactors: { email?, sms?, totp? }, recoveryCodesRemaining, mfaEnabledForClient }
477
- await authKit.removeMfaFactor(clientId, 'sms', password);
478
- ```
479
-
480
- At sign-in, `MFA_REQUIRED` lists `availableFactors` with `preferredFactor` (`totp`, then `sms`, then
481
- `email`). For `totp`, `mfaChallengeSend(clientId, token, 'totp')` sends nothing; it just says the code
482
- comes from the app. Then call `mfaChallengeVerify` with that code, as for the others. Each authenticator
483
- code works once. The secret is sealed on the server and never returned after `enrollTotpMfa`.
484
-
485
- > Enrollment endpoints don't currently check the client's `mfa.mode` — enrolling is possible
486
- > even when MFA is configured `'off'` for a client. Those factors simply won't be challenged
487
- > at login until an admin turns the mode on (via the existing admin AuthKit config update,
488
- > no new admin route in this pass).
489
-
490
- ### MFA error codes
491
-
492
- | `errorCode` | HTTP | Meaning / client action |
493
- |---|---|---|
494
- | `MFA_REQUIRED` | 403 | From any of the six gated login methods — see above |
495
- | `INVALID_MFA_CODE` | 401 | Wrong code — let the user retry (attempts are capped) |
496
- | `MFA_TOO_MANY_ATTEMPTS` | 429 | 5 wrong attempts — the challenge is burned; restart from `login()` |
497
- | `MFA_FACTOR_NOT_ENROLLED` | 400 | Requested factor isn't enrolled — programming error if the UI only offers `availableFactors` |
498
- | `MFA_SESSION_EXPIRED` | 401 | `mfaSessionToken` past its 10-minute TTL — restart from `login()` |
499
- | `MFA_SESSION_INVALID` | 401 | Unknown/wrong-client/already-consumed token, or (on enroll confirm) mismatched user |
500
- | `RECOVERY_CODE_INVALID` | 401 | Wrong or already-used recovery code |
501
-
502
- ---
503
-
504
- ## Profile management
505
-
506
- ```ts
507
- import { authKit } from '@proveanything/smartlinks';
508
-
509
- // Get current user's profile
510
- const profile = await authKit.getProfile(clientId);
511
-
512
- // Update profile
513
- const updatedProfile = await authKit.updateProfile(clientId, {
514
- displayName: 'Alice B.',
515
- avatarUrl: '...'
516
- });
517
-
518
- // The SDK automatically swaps in updatedProfile.token so future auth.verify()
519
- // and authenticated calls use fresh displayName/photoURL claims immediately.
520
-
521
- // Change password
522
- await authKit.changePassword(clientId, 'currentPass', 'newPass');
523
-
524
- // Change email (triggers verification)
525
- await authKit.changeEmail(clientId, 'newemail@example.com', 'password', redirectUrl);
526
-
527
- // Delete account
528
- await authKit.deleteAccount(clientId, 'password', 'DELETE');
529
- ```
530
-
531
- `updateProfile` now returns a fresh bearer token together with the updated profile fields. The SDK replaces the in-memory bearer token automatically so token-backed identity reads stay current without an extra refresh step.
532
-
533
- ---
534
-
535
- ## Email verification
536
-
537
- Auth Kit can send and verify email addresses after registration:
538
-
539
- ```ts
540
- await authKit.sendEmailVerification(clientId, {
541
- userId,
542
- email: 'user@example.com',
543
- redirectUrl: 'https://myapp.example.com/auth/verified',
544
- });
545
-
546
- // On callback page
547
- await authKit.verifyEmail(clientId, tokenFromUrl);
548
- ```
549
-
550
- ---
551
-
552
- ## Password reset
553
-
554
- ```ts
555
- await authKit.requestPasswordReset(clientId, {
556
- email: 'user@example.com',
557
- redirectUrl: 'https://myapp.example.com/auth/reset',
558
- clientName: 'My App',
559
- });
560
-
561
- // On reset page — verify token is still valid before showing the form
562
- await authKit.verifyResetToken(clientId, tokenFromUrl);
563
-
564
- // Complete reset
565
- await authKit.completePasswordReset(clientId, tokenFromUrl, 'newSecurePassword');
566
- ```
567
-
568
- ---
569
-
570
- ## Account security policy
571
-
572
- Each collection can configure account-security rules. **The API enforces all of it**; your
573
- login UI reads the policy for UX only (a live password checklist, idle sign-out). There are
574
- two sides: an **admin** writes the policy, and the **login UI** reads the public subset.
575
-
576
- **Read (login UI, public — no auth):**
577
-
578
- ```ts
579
- const config = await authKit.load(clientId);
580
- const policy = config.security?.passwordPolicy; // min length, char classes, block-common
581
- const session = config.security?.session; // inactivity + absolute timeouts, rememberMe
582
- ```
583
-
584
- `lockout` values are admin-only and never returned by `load`.
585
-
586
- **Write (admin):** set the whole `security` block with `authKit.update` (or `authKit.create`).
587
- The shape is {@link AuthKitSecurityConfig}; see {@link AuthKitConfigInput}.
588
-
589
- ```ts
590
- await authKit.update(collectionId, clientId, {
591
- security: {
592
- passwordPolicy: {
593
- minLength: 8, // hard floor enforced server-side
594
- blockCommonPasswords: true, // reject the common/breached list
595
- requireUppercase: false, requireLowercase: false,
596
- requireNumber: false, requireSymbol: false,
597
- expiryDays: 0, // 0 = never expires
598
- historyCount: 0, // 0 = reuse allowed
599
- },
600
- lockout: { // admin-only; enforced server-side
601
- enabled: true, maxFailedAttempts: 5,
602
- attemptWindowMinutes: 15, lockoutMinutes: 15,
603
- notifyUserOnLockout: true,
604
- },
605
- session: {
606
- inactivityTimeoutMinutes: 0, // 0 = disabled (client-enforced when set)
607
- inactivityWarningSeconds: 60,
608
- absoluteTimeoutHours: 0, // 0 = use token lifetime (server-enforced)
609
- rememberMe: true,
610
- },
611
- },
612
- });
613
- ```
614
-
615
- Defaults if a collection has never set a policy: 8-char minimum + block-common for everyone,
616
- lockout disabled, no expiry/history, no idle/absolute timeout. Omit any field to take its default.
617
-
618
- ### Password policy
619
-
620
- `register`, `completePasswordReset`, and `changePassword` validate the new password
621
- server-side and throw a `SmartlinksApiError` with a {@link PasswordPolicyErrorCode}:
622
-
623
- | `errorCode` (400) | Meaning |
624
- |---|---|
625
- | `PASSWORD_TOO_SHORT` | below `minLength` |
626
- | `PASSWORD_REQUIREMENTS_NOT_MET` | missing a required character class |
627
- | `PASSWORD_TOO_COMMON` | on the common/breached list |
628
- | `PASSWORD_RECENTLY_USED` | matched one of the last `historyCount` passwords |
629
-
630
- Render a live checklist from `policy` so users see the rules before submitting.
631
-
632
- ### Lockout
633
-
634
- After too many failed logins the account is temporarily locked. `login` throws:
635
-
636
- ```ts
637
- try {
638
- await authKit.login(clientId, email, password);
639
- } catch (err) {
640
- if (err.errorCode === 'ACCOUNT_TEMPORARILY_LOCKED') {
641
- const mins = Math.ceil(err.details.retryAfterSeconds / 60);
642
- show(`Too many attempts. Try again in ${mins} minute(s).`);
643
- }
644
- }
645
- ```
646
-
647
- Failed MFA challenges count toward the same lock. Locking responds identically for unknown
648
- accounts (no enumeration).
649
-
650
- ### Password expiry
651
-
652
- If a password is older than `passwordPolicy.expiryDays`, a valid login is refused with
653
- **403 `PASSWORD_EXPIRED`** carrying a short-lived `resetToken` — send the user straight into
654
- the reset form to change it in place:
655
-
656
- ```ts
657
- catch (err) {
658
- if (err.errorCode === 'PASSWORD_EXPIRED') {
659
- await authKit.completePasswordReset(clientId, err.details.resetToken, newPassword);
660
- }
661
- }
662
- ```
663
-
664
- ### Session lifetime
665
-
666
- - **Absolute timeout** (`session.absoluteTimeoutHours`) is enforced server-side on the native
667
- refresh path: once the session is too old, `refreshToken` throws **401 `SESSION_EXPIRED`**
668
- (see {@link RefreshErrorCode}) — clear storage and route to login. Web sessions use the
669
- stateless bearer token and rely on inactivity sign-out below.
670
- - **Inactivity timeout** (`session.inactivityTimeoutMinutes` / `inactivityWarningSeconds`) is
671
- **client-enforced** — sign the user out after idle, warning first. Sync across tabs.
672
- - **`session.rememberMe: false`** → don't persist tokens to durable storage; treat the session
673
- as browser-scoped.
674
-
675
- ---
676
-
677
- ## Own logins (a site's own members)
678
-
679
- By default an Auth Kit signs people in with their **SmartLinks account**: one account, the same
680
- everywhere a site uses the shared login. A site that manages its own members (a club, a league, a
681
- membership site) can instead have **its own logins**: its members are accounts of that site only. The
682
- same email can be a separate account, with a different password, on another site, and signing in on
683
- one site doesn't sign anyone in elsewhere.
684
-
685
- ```ts
686
- await authKit.setIdentity(collectionId, authKitId, { mode: 'own' })
687
- // → { identity: { mode: 'own', tenantId }, message }
688
- ```
689
-
690
- - **One way.** A site with its own members can't go back to the shared login (they would lose their
691
- accounts).
692
- - **New sign-ups** after the switch go to the site's own members. People who signed up before keep their
693
- SmartLinks account until they are moved across.
694
- - **One per collection.** Only one Auth Kit can give a collection its own logins (`MEMBER_POOL_CONFLICT`,
695
- 409, otherwise). You must administer every collection the kit serves (`PERMISSION_DENIED`, 403).
696
- - **Tokens stay on their site.** A member's session works on that site's Auth Kit and collections only.
697
- - Every flow above (password, magic link, phone, Google, Apple, LinkedIn, WhatsApp, SMS, MFA, profile,
698
- resets) works the same way; nothing changes in the login UI or your code.
699
- - `identity` is read-only on `create` / `update`; it is shown on the config (`authKit.get`).
700
-
701
- ### Invitation only
702
-
703
- A site with its own logins can let in only the people it invites:
704
-
705
- ```ts
706
- await authKit.update(collectionId, authKitId, { signUp: 'invite' }) // 'open' (default) | 'invite'
707
- await authKit.invite(collectionId, authKitId, { email: 'jo@example.com', firstName: 'Jo', customFields: { level: 'member' } })
708
- ```
709
-
710
- - **Enforced on the server, for every route.** Nobody without an account can get one: `register`,
711
- `verifyMagicLink`, `verifyPhoneCode`, Google, Apple, LinkedIn and WhatsApp answer `SIGN_UP_CLOSED`
712
- (403). `sendMagicLink` and `sendPhoneCode` answer as if sent, but send nothing to someone who isn't a
713
- member, so nobody can find out who is.
714
- - **`invite`** makes the person's account if they have none, finds or creates their contact in that
715
- collection with the fields you pass, links the two, and emails a sign-in link to the site (`redirectUrl`,
716
- default the kit's) that works once for 7 days. It lands like any magic link (`mode=magicLink&token=…`).
717
- Inviting someone again sends a fresh link. The link is never returned to the admin.
718
- - **Invited members then sign in any way the site offers.** A magic link, "forgot password" to set a
719
- password, or Google/Apple/LinkedIn with the same verified email: an invited account nobody has signed
720
- in to yet can be claimed that way.
721
- - `signUp` is on the public config (`load`): hide "Create an account" when it's `invite`. Setting it
722
- needs own logins first (`OWN_LOGINS_REQUIRED`, 409).
723
- - On any site, a member signing in with a verified email or phone is attached to the contact the
724
- collection already has for it, so fields the staff set beforehand (a level) are theirs.
725
-
726
- ## Relationship to other parts of the SDK
727
-
728
- | Concern | Where it lives |
729
- |---------|---------------|
730
- | End-user sign-in / register | `authKit` namespace (this doc) |
731
- | Admin Bearer token auth | Platform shell — not set by your app |
732
- | Per-user data storage | `userAppData` namespace — see [app-data-storage.md](app-data-storage.md) |
733
- | User identity in analytics | `userId` field on `analytics` and `interactions` calls |
734
-
735
- ---
736
-
737
- ## Further reading
738
-
739
- - [members.md](members.md) — members with a level: clubs, leagues, members-only content
740
- - [app-data-storage.md](app-data-storage.md) — storing user-specific data after login
741
- - [app-manifest.md](app-manifest.md) — `app.admin.json` setup questions for configuring `clientId`
1
+ # SmartLinks Auth Kit (`@proveanything/smartlinks` — `authKit` namespace)
2
+
3
+ > End-user authentication flows for SmartLinks microapps. Covers email/password, magic links, phone OTP, Google OAuth, profile management, and password/email change flows.
4
+ >
5
+ > **This is part of the core SDK** — no separate install required. Import from `@proveanything/smartlinks`.
6
+
7
+ ---
8
+
9
+ ## What is Auth Kit for?
10
+
11
+ Auth Kit is the **end-user identity layer** for microapps that need users to sign in. It is distinct from the admin/platform authentication (Bearer tokens) used to call admin endpoints.
12
+
13
+ Use Auth Kit when:
14
+ - Your app has a login/register screen for end users (not collection admins)
15
+ - You need to gate features behind a verified user identity
16
+ - You want to store user-specific data with the `userAppData` API (see [app-data-storage.md](app-data-storage.md))
17
+
18
+ Do **not** use Auth Kit for:
19
+ - Admin-side API calls (those use Bearer tokens set by the platform shell)
20
+ - Claiming proofs (see proof claiming methods)
21
+
22
+ ---
23
+
24
+ ## Setting up sign-in (admin) — everything by API
25
+
26
+ Every sign-in setting can be read and written through the API: nothing needs a person to click
27
+ through screens. This is the section an assistant (Juno in Studio, the Forge build agent) follows when
28
+ someone says "set up login".
29
+
30
+ A collection's sign-in is one **AuthKit config** — one shape, validated by the server on every write
31
+ (`INVALID_CONFIG` 400 lists every problem as `problems: [{ path, message }]`), with safe defaults for
32
+ everything left out. `authKit.schema(collectionId)` returns every field with its default and what reads
33
+ it (`screens` = the sign-in UI `@proveanything/smartlinks-auth-ui`, `server` = the API enforces it).
34
+
35
+ ### The calls
36
+
37
+ | Call | What it does |
38
+ |---|---|
39
+ | `authKit.setup(collectionId, { name?, ownLogins?, settings? })` | Find the collection's sign-in, or make one (email + Google; confirm the email, then signed in) and make it the collection's default. `ownLogins: true` gives it its own members (**one way**, needed for invite-only). `settings` = a first patch. Safe to repeat; `changed` says what it did. |
40
+ | `authKit.settings(collectionId, authKitId)` | What sign-in does now: `config` (stored), `effective` (defaults filled in), `secrets` (set or not, masked hint), `checks` (problems / warnings in plain words, each naming the setting to change). **Read this before and after every change.** |
41
+ | `authKit.update(collectionId, authKitId, patch)` | Change settings. Each top-level field replaces the stored one (send the whole `branding`, `emailTemplates`, `mfa`… object you want). |
42
+ | `authKit.previewEmail(collectionId, authKitId, kind, draft?)` | `{ subject, html }` of an account email as it will be sent — with draft `emailTemplates` / `emailBranding` / `branding` if given (nothing saved). |
43
+ | `authKit.secretEntryLink(collectionId, authKitId, name)` | `{ url, expiresAt }`: a SmartLinks page where the **person** types a secret. Works once, 30 minutes. Never ask anyone to paste a secret into a chat. |
44
+ | `authKit.schema(collectionId)` | The field list (paths, defaults, descriptions). |
45
+ | `authKit.invite(collectionId, authKitId, { email, firstName?, customFields? })` | Invite a member (invite-only sites). |
46
+
47
+ The collection's sign-in id: `collection.defaultAuthKitId` (`setup` returns it as `authKit.id`).
48
+
49
+ ### The settings
50
+
51
+ **Sign-in methods** — `enabledProviders`: any of `email` (email + password), `magic-link` (an emailed
52
+ sign-in link), `phone` (a text-message code), `whatsapp` (a WhatsApp code), `google`, `apple`,
53
+ `microsoft`, `linkedin`. `providerOrder`: the order they show in. `emailDisplayMode`: `form` (the email
54
+ form straight away) or `button` ("Continue with email" first).
55
+
56
+ What each provider needs from the owner:
57
+
58
+ | Method | Works with nothing else? | What only the owner can give |
59
+ |---|---|---|
60
+ | email, magic-link, phone, whatsapp | yes | — |
61
+ | google | yes (SmartLinks' Google app) | Their own Google OAuth **web client id** (`googleClientId`, public — **no secret**: sign-in verifies Google's ID token against it) and the site domains registered on it (`whitelistedGoogleDomains`). |
62
+ | microsoft | yes (SmartLinks' Microsoft app) | Only to show their own name on Microsoft's screen: `microsoftClientId` (redirect URI `https://smartlinks.app/apps/account/stable/microsoft-proxy.html`). No secret. |
63
+ | apple | **no** | Their Apple **Services ID** (and app bundle ids): `appleClientIds`. No secret. |
64
+ | linkedin | yes (SmartLinks' LinkedIn app) | Their own app: `linkedInClientId` + the client **secret** through `secretEntryLink(…, 'linkedInClientSecret')`. |
65
+
66
+ **Who may join** — `signUp`: `open` (default) or `invite` (only people invited; every sign-up route
67
+ refuses others with `SIGN_UP_CLOSED`; needs `ownLogins`). `signupProminence`: `none` (no sign-up link),
68
+ `minimal` (default), `balanced`, `emphasized`. `access`: `{ mode: 'anyone' }` or
69
+ `{ mode: 'organisation', domains: ['acme.com'], emails: [...] }` — who can sign in at all (allowed
70
+ domains). `registrationFields`: extra contact fields on the sign-up form.
71
+ `collectNameOnPasswordlessSignup` (default true).
72
+
73
+ **Email confirmation** — `emailVerificationMode`: `verify-auto-login` (default: confirm, then signed
74
+ straight in), `verify-manual-login`, `immediate`. `emailVerificationGracePeriod` (hours),
75
+ `lockUnverifiedAfterGrace`.
76
+
77
+ **Passwords** — `security.passwordPolicy` `{ minLength (8), requireUppercase, requireLowercase,
78
+ requireNumber, requireSymbol, blockCommonPasswords (true), expiryDays (0 = never), historyCount }`;
79
+ `security.lockout` `{ enabled, maxFailedAttempts, attemptWindowMinutes, lockoutMinutes,
80
+ notifyUserOnLockout }`; `security.session` `{ inactivityTimeoutMinutes, absoluteTimeoutHours,
81
+ rememberMe }`. `allowPasswordReset` (default true; `false` hides "Forgot password?" and the reset
82
+ request answers `PASSWORD_RESET_DISABLED`).
83
+
84
+ **Second step** — `mfa`: `{ mode: 'off' | 'optional' | 'risk-based' | 'always', factorsEnabled: {
85
+ email, sms, totp, recoveryCodes } }`. `optional` lets people add an authenticator app (TOTP) without
86
+ being asked; `always` asks everyone who has one at every sign-in.
87
+
88
+ **Redirects** — `redirectUrl`: the site's sign-in page (where invitations open; the default for
89
+ emailed links). `afterSignInUrl`: where the site sends people after they sign in (the screens hand the session to the
90
+ page's `onAuthSuccess`; the page reads `afterSignInUrl` from `authKit.load()` and goes there). `allowedRedirectDomains`: extra domains emailed links may return to (the collection's own domains
91
+ and `*.smartlinks.host` are always allowed).
92
+
93
+ **The screens' look** — `branding`: `title`, `subtitle`, `registerTitle`, `registerSubtitle`,
94
+ `logoUrl` (absent = SmartLinks logo, `''` = none), `primaryColor`, `secondaryColor`,
95
+ `backgroundColor`, `fontFamily`, `buttonStyle`, `theme` (`light` | `dark` | `auto`),
96
+ `inheritHostStyles` (default **true** — the host page's colours win; set `false` for your colours to
97
+ show), `minimal`, `customCss`. `termsUrl`, `privacyUrl`, `supportEmail`. **Wording** — `texts`:
98
+ `signInTitle`, `signInSubtitle`, `registerTitle`, `registerSubtitle`, `emailLabel`, `passwordLabel`,
99
+ `signInButton`, `registerButton`, `forgotPassword`, `noAccount`, `haveAccount`, `continueWithEmail`,
100
+ `continueWithGoogle`, `continueWithApple`, `continueWithMicrosoft`, `continueWithLinkedIn`,
101
+ `continueWithPhone`, `continueWithWhatsApp`, `continueWithMagicLink`, `sendMagicLink`, `magicLinkSent`, `inviteOnlyNotice` (a key
102
+ left out keeps the built-in words).
103
+
104
+ **The account emails** — `emailTemplates.<kind>`: `{ subject, header, introText, buttonText,
105
+ footerText }` for `passwordReset`, `emailVerification`, `magicLink`, `memberInvite` (site member
106
+ invitations), `invite` / `addedToCollection` (staff), `mfaCode`, `providerLinked`. `emailBranding`:
107
+ `{ logoUrl, buttonColor, footerHtml }`. The sender is the collection's email settings (its verified
108
+ domain), not set here. Plain words only — scripts and event handlers are refused.
109
+
110
+ ### Worked example: an invite-only club with magic link
111
+
112
+ ```ts
113
+ const { authKit: kit } = await authKit.setup(collectionId, {
114
+ name: 'Riverside Club sign-in',
115
+ ownLogins: true, // members are the club's own (one way) — invite-only needs it
116
+ settings: {
117
+ enabledProviders: ['magic-link'],
118
+ signUp: 'invite',
119
+ signupProminence: 'none',
120
+ redirectUrl: 'https://riverside.smartlinks.host/sign-in',
121
+ branding: { title: 'Riverside Club', subtitle: 'Members only', theme: 'dark', primaryColor: '#0f766e', inheritHostStyles: false },
122
+ texts: { signInTitle: 'Members sign in', sendMagicLink: 'Email me a sign-in link', inviteOnlyNotice: 'Members only — ask us for an invitation.' },
123
+ emailTemplates: {
124
+ magicLink: { subject: 'Your Riverside sign-in link', header: 'Welcome back', buttonText: 'Sign in to Riverside' },
125
+ memberInvite: { subject: "You're invited to Riverside Club", introText: "The committee has invited you to join. One click and you're in." },
126
+ },
127
+ emailBranding: { buttonColor: '#0f766e' },
128
+ },
129
+ })
130
+ const s = await authKit.settings(collectionId, kit.id)
131
+ // s.checks: nothing at level 'problem' → done. Show the owner the invitation:
132
+ const { subject, html } = await authKit.previewEmail(collectionId, kit.id, 'memberInvite')
133
+ await authKit.invite(collectionId, kit.id, { email: 'sam@example.com', firstName: 'Sam', customFields: { level: 'member' } })
134
+ ```
135
+
136
+ ### Worked example: Google + password with a branded reset email
137
+
138
+ ```ts
139
+ const { authKit: kit } = await authKit.setup(collectionId, { name: 'Shop sign-in' })
140
+ await authKit.update(collectionId, kit.id, {
141
+ enabledProviders: ['email', 'google'],
142
+ providerOrder: ['google', 'email'],
143
+ googleClientId: '1234-abc.apps.googleusercontent.com', // from the owner (public, no secret)
144
+ whitelistedGoogleDomains: ['shop.example.com'],
145
+ security: { passwordPolicy: { minLength: 10, requireNumber: true } },
146
+ branding: { title: 'Example Shop', logoUrl: 'https://cdn.example.com/logo.png', inheritHostStyles: false, primaryColor: '#111827' },
147
+ emailTemplates: { passwordReset: { subject: 'Reset your Example Shop password', introText: 'Tap the button to choose a new password.', buttonText: 'Choose a new password' } },
148
+ emailBranding: { logoUrl: 'https://cdn.example.com/logo.png', buttonColor: '#111827', footerHtml: 'Example Shop Ltd' },
149
+ })
150
+ const preview = await authKit.previewEmail(collectionId, kit.id, 'passwordReset')
151
+ ```
152
+
153
+ ### Worked example: their own LinkedIn app (a secret)
154
+
155
+ ```ts
156
+ await authKit.update(collectionId, kitId, { enabledProviders: ['email', 'linkedin'], linkedInClientId: '86abc123' })
157
+ const { url } = await authKit.secretEntryLink(collectionId, kitId, 'linkedInClientSecret', { label: 'LinkedIn sign-in' })
158
+ // Tell the person: "Open this link and paste your LinkedIn client secret there — it works once."
159
+ // Later: (await authKit.settings(collectionId, kitId)).secrets.linkedInClientSecret.set === true
160
+ ```
161
+
162
+ ### Rules for assistants
163
+
164
+ - Ask only for what must come from the owner (their Google client id, Apple Services ID, their own
165
+ LinkedIn app). For a **secret**, give them an entry link — never ask them to paste it to you.
166
+ - Read `settings` first; change; read `settings` again and tell the owner what sign-in now does and any
167
+ `checks` left. Preview the emails you changed.
168
+ - `ownLogins` and `signUp: 'invite'` change who can get in: say so plainly before doing it.
169
+ - On a site built in Forge, write sign-in through `cloud/sign-in.json` (the site-cloud skill), not ad-hoc calls.
170
+
171
+ ---
172
+
173
+ ## Key flows
174
+
175
+ ### Email / password
176
+
177
+ ```ts
178
+ import { authKit } from '@proveanything/smartlinks';
179
+
180
+ // Register
181
+ const session = await authKit.register(clientId, {
182
+ email: 'user@example.com',
183
+ password: 'securePassword123',
184
+ displayName: 'Alice',
185
+ });
186
+
187
+ // Login
188
+ const session = await authKit.login(clientId, 'user@example.com', 'securePassword123');
189
+
190
+ // session.token — store this; pass to initializeApi for subsequent calls
191
+ ```
192
+
193
+ ### Magic link (passwordless email)
194
+
195
+ ```ts
196
+ await authKit.sendMagicLink(clientId, {
197
+ email: 'user@example.com',
198
+ redirectUrl: 'https://myapp.example.com/auth/verify',
199
+ });
200
+
201
+ // On callback page, extract token from URL and verify
202
+ const session = await authKit.verifyMagicLink(clientId, tokenFromUrl);
203
+ ```
204
+
205
+ ### Phone OTP
206
+
207
+ ```ts
208
+ await authKit.sendPhoneCode(clientId, '+61400000000');
209
+ const session = await authKit.verifyPhoneCode(clientId, '+61400000000', '123456');
210
+ ```
211
+
212
+ ### Lightweight verification (WhatsApp + SMS)
213
+
214
+ Use these flows when you want low-friction verification before or without full account sign-in.
215
+
216
+ WhatsApp verification is token-first. The user does not type their phone number in your app for this flow; phone ownership is proven by the inbound WhatsApp sender number.
217
+
218
+ ```ts
219
+ import { authKit } from '@proveanything/smartlinks';
220
+
221
+ // 1) Send WhatsApp verification deep link
222
+ const wa = await authKit.sendWhatsApp(clientId);
223
+
224
+ // Optional: pass redirect context and/or a post-verification reply
225
+ // const wa = await authKit.sendWhatsApp(clientId, {
226
+ // redirectUrl: 'https://app.example.com/checkout/continue',
227
+ // prefillMessage: 'Please let me bid in this auction. Code: {{token}}',
228
+ // contactData: {
229
+ // name: 'Jane Doe',
230
+ // email: 'jane@example.com',
231
+ // source: 'auction-checkout',
232
+ // customFields: { agreedToTerms: true },
233
+ // },
234
+ // reply: {
235
+ // cta: {
236
+ // body: "You're verified and ready to bid.",
237
+ // buttonLabel: 'Back to Auction',
238
+ // buttonUrl: '{{returnUrl}}',
239
+ // // mediaUrl: 'https://cdn.example.com/bid-confirmed.jpg', // optional: include to use image card template
240
+ // },
241
+ // text: "You're verified. Return to the app to continue.",
242
+ // },
243
+ // });
244
+
245
+ // wa.waLink can be opened directly by the app/browser
246
+ // Poll status while user switches to WhatsApp and back
247
+ const status = await authKit.getWhatsAppStatus(clientId, wa.token);
248
+
249
+ // Optional: exchange verified WhatsApp proof for an Auth Kit session
250
+ if (status.status === 'verified' && wa.sessionKey) {
251
+ const session = await authKit.exchangeWhatsAppSession(clientId, wa.token, wa.sessionKey);
252
+ // session.token can be used as the authenticated bearer token
253
+ }
254
+
255
+ // Optional legacy fallback path if webhook confirmation is unavailable
256
+ await authKit.verifyWhatsApp(clientId, wa.token, '+447911123456');
257
+
258
+ // 2) Or send SMS click-to-verify link
259
+ await authKit.sendSmsVerify(clientId, {
260
+ phoneNumber: '+447911123456',
261
+ redirectUrl: 'https://app.example.com/raffle/checkout',
262
+ ctaText: 'Tap to continue',
263
+ });
264
+
265
+ // Optional API verification path
266
+ await authKit.verifySms(clientId, '<token>', '+447911123456');
267
+ ```
268
+
269
+ `contactData` is optional and is useful when you collect name/email before the customer switches to WhatsApp.
270
+
271
+ - Auth Kit stores `contactData` on the verification token metadata first.
272
+ - Contact details are written to durable contact storage only after WhatsApp verification succeeds.
273
+ - If the user abandons before verification, no contact is created.
274
+ - `contactData` must not include phone; the verified inbound WhatsApp sender number is always authoritative.
275
+
276
+ ### Contact bootstrap / durable identity
277
+
278
+ After verification, upsert contact identity and store `contactId` on downstream records (raffle ticket, bid, claim intent).
279
+
280
+ ```ts
281
+ const contact = await authKit.upsertContact(clientId, {
282
+ phone: '+447911123456',
283
+ name: 'Jane Doe',
284
+ source: 'raffle-checkout',
285
+ customFields: { channelVerified: 'whatsapp' },
286
+ externalIds: { raffleSessionId: 'rfl_123' },
287
+ });
288
+
289
+ // Persist these on your business record
290
+ // contact.contactId, contact.collectionId, verified channel, verifiedAt
291
+ ```
292
+
293
+ Verification status values returned by `authKit.getWhatsAppStatus` are:
294
+ - `pending`
295
+ - `verified`
296
+ - `failed`
297
+ - `expired`
298
+ - `unknown`
299
+
300
+ #### Post-verification reply
301
+
302
+ Pass a `reply` object in `sendWhatsApp` to send a message back to the user after they confirm `CONFIRM <token>`. Reply resolution order:
303
+
304
+ 1. `reply.contentSid` — explicit Twilio Content SID
305
+ 2. `reply.cta` — CTA shorthand:
306
+ - If `cta.mediaUrl` is present (valid public `https://` URL), uses the **image card** Twilio Content template (`TWILIO_WHATSAPP_IMAGE_CTA_SID`)
307
+ - Otherwise uses the **text CTA** template (`TWILIO_WHATSAPP_GENERIC_CTA_SID`)
308
+ 3. `reply.text` — plain-text fallback
309
+ 4. Per-client default (`authKit/{clientId}.whatsapp` config)
310
+ 5. Built-in default text
311
+
312
+ > **Important:** Only pass `mediaUrl` when you have a valid, publicly reachable `https://` JPEG or PNG. If the field is absent or blank, the text-only CTA template is selected automatically. Never pass an empty string — omit the field entirely to avoid Twilio rejecting the send.
313
+
314
+ The following template placeholders are available in `reply.text`, `reply.cta` fields, and `reply.contentVariables` values:
315
+
316
+ | Placeholder | Description |
317
+ |---|---|
318
+ | `{{returnUrl}}` | The resolved redirect URL |
319
+ | `{{phoneNumber}}` | The verified phone number |
320
+ | `{{clientId}}` | The Auth Kit client ID |
321
+ | `{{token}}` | The verification token |
322
+
323
+ You can also set `prefillMessage` on `sendWhatsApp` to customize the text pre-filled in the `wa.me` deep link. If `{{token}}` is not present, the token is appended to the message.
324
+
325
+ #### Session exchange after verification
326
+
327
+ After polling returns `status === 'verified'`, exchange the verification proof for an Auth Kit login session:
328
+
329
+ ```ts
330
+ const session = await authKit.exchangeWhatsAppSession(clientId, wa.token, wa.sessionKey!);
331
+ // session: { success, token, user, accountData? }
332
+ ```
333
+
334
+ `sessionKey` is returned by `sendWhatsApp` and is used to mitigate token replay from contexts that did not initiate the browser flow.
335
+
336
+ When `contactData.name` or explicit name parts were supplied on the original `sendWhatsApp` call, `session.user.displayName` and the returned bearer token claims are now seeded from the verified contact record instead of staying `null`.
337
+
338
+ > **Note:** `redirectUrl` is optional. WhatsApp tokens are short hex strings (16 chars) for better UX.
339
+ >
340
+ > **Legacy note:** `verifyWhatsApp` is for older phone-bound token flows. Prefer inbound WhatsApp token confirmation plus status polling for new implementations.
341
+
342
+ ### Google OAuth
343
+
344
+ ```ts
345
+ // After Google sign-in, pass the id_token to Auth Kit
346
+ const session = await authKit.googleLogin(clientId, googleIdToken);
347
+ ```
348
+
349
+ ### Sign in with Apple
350
+
351
+ Pass the Apple **identity token** (a JWT). On iOS/native it's
352
+ `ASAuthorizationAppleIDCredential.identityToken` (UTF-8 decoded); on web it's
353
+ `response.authorization.id_token` from Apple JS.
354
+
355
+ ```ts
356
+ const session = await authKit.appleLogin(clientId, appleIdentityToken, {
357
+ // All optional:
358
+ nonce, // raw nonce, if you used nonce binding
359
+ userInfo: { name, email }, // first authorization callback ONLY — Apple never resends it
360
+ trustedDeviceToken, // skip an MFA step-up challenge on a recognized device — see "Step-up MFA" below
361
+ });
362
+ // session.isNewUser and session.expiresAt (ms epoch) are populated by this endpoint.
363
+ ```
364
+
365
+ Apple returns the user's name/email **only on the very first authorization, ever**, and
366
+ never inside the token. Capture it from that first callback and forward it via `userInfo`
367
+ so the server can seed the display name — it's treated as untrusted and never used for identity.
368
+
369
+ Apple login requires the client's AuthKit config to list allowed audiences in
370
+ `appleClientIds`; until then the endpoint returns `400 APPLE_AUTH_NOT_CONFIGURED`.
371
+
372
+ #### Verified-to-verified account linking (affects Google too)
373
+
374
+ Both `appleLogin` and `googleLogin` now refuse to silently merge a federated login into a
375
+ pre-existing account whose email is **unverified**. Instead they throw
376
+ `SmartlinksApiError` with `errorCode === 'ACCOUNT_EXISTS_UNVERIFIED'` (409) and
377
+ `err.details?.requiresEmailVerification === true`. Treat this as recoverable, not fatal:
378
+
379
+ ```ts
380
+ try {
381
+ const session = await authKit.appleLogin(clientId, appleIdentityToken);
382
+ } catch (err) {
383
+ if (err instanceof SmartlinksApiError && err.errorCode === 'ACCOUNT_EXISTS_UNVERIFIED') {
384
+ // "An account with this email exists but isn't verified. Sign in with your
385
+ // password (or reset it), then link Apple/Google from settings."
386
+ }
387
+ }
388
+ ```
389
+
390
+ > ⚠️ This is a behaviour change for `googleLogin`, which previously merged silently in
391
+ > this case. Handle the 409 for both methods.
392
+
393
+ ### Sign in with Microsoft
394
+
395
+ Work or school accounts from **any** organisation, and personal Microsoft accounts (Outlook, Hotmail,
396
+ Live). Add `'microsoft'` to `enabledProviders` — that's all: SmartLinks' own Microsoft app serves every
397
+ organisation, so neither you nor your users' IT registers anything.
398
+
399
+ ```ts
400
+ const session = await authKit.microsoftLogin(clientId, microsoftIdToken, { returnOrigin });
401
+ ```
402
+
403
+ - **In the SmartLinks sign-in UI** the Microsoft button opens SmartLinks' Microsoft sign-in page
404
+ (`https://smartlinks.app/apps/account/stable/microsoft-proxy.html`) in a popup — the one address
405
+ registered with Microsoft — which signs in and hands the session back to your site. Your site must be
406
+ one of the login setup's own (its collections' domains or site addresses, or `allowedRedirectDomains`),
407
+ else `MICROSOFT_ORIGIN_NOT_ALLOWED` (403).
408
+ - **Your own UI:** get an ID token from Microsoft (`response_type=id_token`, scope `openid profile email`,
409
+ authority `https://login.microsoftonline.com/common`) for the app in the public config's
410
+ `microsoftClientId`, and pass it here.
411
+ - **Some companies' IT approves new apps for their staff.** The first person from such a company sees
412
+ "needs admin approval"; their IT approves SmartLinks once for the organisation and everyone can sign in.
413
+ - **Your own name on Microsoft's screen (optional):** register your own *multitenant* app in Microsoft
414
+ Entra (Supported account types: any organisation + personal accounts; Web redirect URI as above, with
415
+ "ID tokens" ticked; token configuration: optional claim `xms_edov` on the ID token) and set its
416
+ Application (client) ID as `microsoftClientId`.
417
+ - A Microsoft account's email is trusted only when Microsoft vouches that its organisation owns the
418
+ domain (or for personal accounts): an organisation can give its users any address. Linking to an
419
+ existing account by email follows the same verified-to-verified rule as Google and Apple.
420
+
421
+ ### Who can sign in (`access`)
422
+
423
+ Restrict a login setup to one organisation — no keys, no IT:
424
+
425
+ ```ts
426
+ await authKit.update(collectionId, clientId, {
427
+ access: { mode: 'organisation', domains: ['acme.com'], emails: ['contractor@gmail.com'] },
428
+ });
429
+ ```
430
+
431
+ - Someone is from acme.com when their **verified** email is at acme.com, they're one of `emails`, or they
432
+ signed in with Microsoft from acme's own Microsoft organisation (looked up from the domain when you
433
+ save — `microsoftTenants` is filled in for you).
434
+ - Checked on **every** sign-in method each time a session is issued: everyone else gets
435
+ `NOT_IN_ORGANISATION` (403) with a message naming the domain. Tighten the rule and people already in
436
+ are refused from their next sign-in.
437
+ - `register` refuses outside addresses before making anything, and never signs an unverified address
438
+ straight in (even in `immediate` mode) — it must be verified first.
439
+ - Phone-only and WhatsApp-only accounts have no email to prove an organisation, so they can't get in.
440
+ - The public config (`load`) returns `access: { mode, domains }` so your page can say who it's for; the
441
+ `emails` list is never public. `{ mode: 'anyone' }` (or no `access`) lets everyone in, as before.
442
+
443
+ ### Refresh tokens (native sessions)
444
+
445
+ Native/Capacitor hosts can hold long-lived sessions via refresh tokens. Opt in **once**
446
+ at startup so every request carries `X-Client-Platform: native`:
447
+
448
+ ```ts
449
+ initializeApi({ baseURL, platform: 'native' });
450
+ ```
451
+
452
+ With the opt-in active, the login endpoints (`login`, `register` in immediate mode,
453
+ `googleLogin`, `appleLogin`, `verifyPhoneCode`, `verifyMagicLink`,
454
+ `exchangeWhatsAppSession`) additionally return `refreshToken`, `refreshTokenExpiresAt`
455
+ (absolute, fixed, ms epoch), and a **short-lived** access `token`. Web clients are
456
+ unaffected and receive the unchanged response.
457
+
458
+ ```ts
459
+ // Later — exchange the refresh token for a fresh access token.
460
+ const r = await authKit.refreshToken(clientId, storedRefreshToken);
461
+ // r.refreshToken is ROTATED — persist it and discard the old one BEFORE the next call.
462
+ // The SDK already swapped in r.token as the active bearer for you.
463
+ persist(r.refreshToken, r.refreshTokenExpiresAt);
464
+
465
+ // On explicit sign-out — revokes the whole device family server-side + clears the bearer.
466
+ await authKit.logout(clientId, storedRefreshToken);
467
+ clearPersistedTokens();
468
+ ```
469
+
470
+ **Rotation rules the host MUST respect:**
471
+
472
+ 1. **Single-use + rotation.** Every `refreshToken()` returns a new token. Persist it and
473
+ overwrite the old one *before* the next call.
474
+ 2. **Serialize refreshes.** Fire a single in-flight refresh and queue callers behind it —
475
+ the SDK does **not** serialize for you, and racing two refreshes spends the same token.
476
+ 3. **Reuse = family death.** Replaying a consumed token throws
477
+ `SmartlinksApiError` with `errorCode === 'REFRESH_TOKEN_REUSE_DETECTED'`; treat as a
478
+ hard logout (clear storage, force re-login). `INVALID_REFRESH_TOKEN` (expired/revoked)
479
+ is handled the same way.
480
+ 4. **Absolute expiry is fixed.** `refreshTokenExpiresAt` never moves on rotation; once it
481
+ passes (default 90 days) the user must log in again.
482
+
483
+ > Resume-refresh scheduling and transparent refresh-on-401 are the responsibility of the
484
+ > host/auth-ui layer, not this SDK — the SDK only exposes the `refreshToken()` / `logout()`
485
+ > primitives and the `platform` opt-in.
486
+
487
+ ---
488
+
489
+ ## Step-up MFA
490
+
491
+ Factors: **email code, SMS code, authenticator app (`totp`), recovery codes**. The shared login UI
492
+ (`@proveanything/smartlinks-auth-ui`) has the challenge and the Settings → Security screens. WhatsApp
493
+ codes and passkeys are planned; don't build against them yet.
494
+
495
+ **Authenticator apps** (Google Authenticator, Microsoft Authenticator, 1Password, Authy…) are the
496
+ recommended second step: nothing is sent (no SMS cost, nothing to intercept), and they are offered first
497
+ when someone has one. A client can switch any factor off with `mfa.factorsEnabled` (e.g.
498
+ `{ totp: false }`).
499
+
500
+ The step-up gate applies to **every login method that issues a session**:
501
+
502
+ | Method | Gated? |
503
+ |---|---|
504
+ | `login()` | ✅ |
505
+ | `googleLogin()` | ✅ |
506
+ | `appleLogin()` | ✅ — pass `opts.trustedDeviceToken` |
507
+ | `verifyPhoneCode()` | ✅ |
508
+ | `verifyMagicLink()` | ✅ |
509
+ | `exchangeWhatsAppSession()` | ✅ — **this is the WhatsApp method that needs a trusted-device token, not `verifyWhatsApp()`** |
510
+ | `verifyWhatsApp()` | ❌ — only confirms the code, never issues a session, so there's nothing to gate |
511
+ | `register()` | ❌ — a brand-new user has no enrolled factors to challenge against |
512
+ | `googleCodeLogin()` | ❌ — no `/auth/google-code` route exists server-side |
513
+
514
+ All six gated methods accept an optional `trustedDeviceToken` param (the last positional
515
+ argument, or `opts.trustedDeviceToken` for `appleLogin()`) — same purpose everywhere: skip
516
+ the challenge on a device the user already verified.
517
+
518
+ ### Handling `MFA_REQUIRED`
519
+
520
+ Every gated method's return type is unchanged. When the client's MFA policy requires a
521
+ step-up, the server returns 403 instead of a session, and the method throws — identically
522
+ for all six:
523
+
524
+ ```ts
525
+ import { authKit, SmartlinksApiError } from '@proveanything/smartlinks';
526
+
527
+ try {
528
+ const session = await authKit.login(clientId, email, password);
529
+ // logged in, no MFA required
530
+ } catch (err) {
531
+ if (err instanceof SmartlinksApiError && err.errorCode === 'MFA_REQUIRED') {
532
+ const { mfaSessionToken, availableFactors, preferredFactor, maskedDestinations } = err.details!;
533
+ // → route to a challenge UI; call authKit.mfaChallengeSend(clientId, mfaSessionToken, preferredFactor)
534
+ } else {
535
+ throw err;
536
+ }
537
+ }
538
+ ```
539
+
540
+ ### Completing the challenge
541
+
542
+ ```ts
543
+ // Send (or resend, or switch factor) a code on the same mfaSessionToken
544
+ const sent = await authKit.mfaChallengeSend(clientId, mfaSessionToken, 'sms');
545
+ // sent.destination is masked, e.g. "+1******1234"
546
+
547
+ // Verify the code — behaves like login() on success: bearer token is adopted automatically
548
+ const session = await authKit.mfaChallengeVerify(clientId, mfaSessionToken, '123456', /* trustDevice */ true, 'My Laptop');
549
+
550
+ // Or finalize with a single-use recovery code instead
551
+ const session = await authKit.mfaRecoveryCode(clientId, mfaSessionToken, recoveryCode);
552
+ ```
553
+
554
+ `mfaSessionToken` is short-lived (10 min) and single-use — burned on 5 failed attempts
555
+ (`MFA_TOO_MANY_ATTEMPTS`) or on success. Once burned/expired, there's no "resend within the
556
+ same session" — the caller must restart from `login()`.
557
+
558
+ ### Trusted devices — "don't ask again on this device"
559
+
560
+ There's no fingerprinting involved: a "recognized device" is purely "the caller presented a
561
+ valid, unexpired, unrevoked `trustedDeviceToken`". Handle it like the native refresh token
562
+ above — same secure storage, same persist-before-next-call discipline:
563
+
564
+ ```ts
565
+ // 1) Persist trustedDeviceToken from a successful challenge (trustDevice: true)
566
+ persistTrustedDeviceToken(session.trustedDeviceToken, session.trustedDeviceExpiresAt);
567
+
568
+ // 2) Send it on every subsequent call to ANY of the six gated methods — if still valid,
569
+ // the challenge is skipped entirely. It isn't tied to which method the user challenged
570
+ // through, so "remember this device" works no matter which login method they pick next.
571
+ const session = await authKit.login(clientId, email, password, storedTrustedDeviceToken);
572
+ const session = await authKit.googleLogin(clientId, idToken, storedTrustedDeviceToken);
573
+ const session = await authKit.exchangeWhatsAppSession(clientId, waToken, sessionKey, storedTrustedDeviceToken);
574
+ // ...and so on for appleLogin (via opts), verifyPhoneCode, verifyMagicLink.
575
+ // If it's revoked/expired, the server silently falls back to requiring a fresh challenge —
576
+ // the method just throws MFA_REQUIRED again, no special-case handling needed.
577
+
578
+ // 3) Let users audit/revoke devices from a Settings screen
579
+ const { devices } = await authKit.listTrustedDevices(clientId);
580
+ await authKit.revokeTrustedDevice(clientId, deviceId);
581
+ ```
582
+
583
+ ### Factor management (Settings → Security)
584
+
585
+ Authenticated (bearer token) — same `mfaSessionToken` + code mechanism as login challenges,
586
+ just against a `purpose: 'enroll'` challenge instead of `'login'`.
587
+
588
+ ```ts
589
+ // Enroll email (uses the account's existing email)
590
+ const { mfaSessionToken } = await authKit.enrollEmailMfa(clientId);
591
+ await authKit.confirmEmailMfa(clientId, mfaSessionToken, code);
592
+
593
+ // Enroll SMS
594
+ const { mfaSessionToken: smsToken } = await authKit.enrollSmsMfa(clientId, '+61400000000');
595
+ await authKit.confirmSmsMfa(clientId, smsToken, code);
596
+
597
+ // Enroll an authenticator app: show otpauthUri as a QR code (and secret for typing in),
598
+ // then confirm with the 6-digit code the app shows
599
+ const { mfaSessionToken: appToken, otpauthUri, secret } = await authKit.enrollTotpMfa(clientId);
600
+ await authKit.confirmTotpMfa(clientId, appToken, codeFromApp);
601
+
602
+ // Recovery codes — plaintext, shown exactly once; nothing else in the API returns them again
603
+ const { recoveryCodes } = await authKit.generateMfaRecoveryCodes(clientId, password);
604
+
605
+ // Inspect / remove
606
+ const factors = await authKit.getMfaFactors(clientId);
607
+ // factors: { enrolledFactors: { email?, sms?, totp? }, recoveryCodesRemaining, mfaEnabledForClient }
608
+ await authKit.removeMfaFactor(clientId, 'sms', password);
609
+ ```
610
+
611
+ At sign-in, `MFA_REQUIRED` lists `availableFactors` with `preferredFactor` (`totp`, then `sms`, then
612
+ `email`). For `totp`, `mfaChallengeSend(clientId, token, 'totp')` sends nothing; it just says the code
613
+ comes from the app. Then call `mfaChallengeVerify` with that code, as for the others. Each authenticator
614
+ code works once. The secret is sealed on the server and never returned after `enrollTotpMfa`.
615
+
616
+ > Enrollment endpoints don't currently check the client's `mfa.mode` — enrolling is possible
617
+ > even when MFA is configured `'off'` for a client. Those factors simply won't be challenged
618
+ > at login until an admin turns the mode on (via the existing admin AuthKit config update,
619
+ > no new admin route in this pass).
620
+
621
+ ### MFA error codes
622
+
623
+ | `errorCode` | HTTP | Meaning / client action |
624
+ |---|---|---|
625
+ | `MFA_REQUIRED` | 403 | From any of the six gated login methods — see above |
626
+ | `INVALID_MFA_CODE` | 401 | Wrong code — let the user retry (attempts are capped) |
627
+ | `MFA_TOO_MANY_ATTEMPTS` | 429 | 5 wrong attempts — the challenge is burned; restart from `login()` |
628
+ | `MFA_FACTOR_NOT_ENROLLED` | 400 | Requested factor isn't enrolled — programming error if the UI only offers `availableFactors` |
629
+ | `MFA_SESSION_EXPIRED` | 401 | `mfaSessionToken` past its 10-minute TTL — restart from `login()` |
630
+ | `MFA_SESSION_INVALID` | 401 | Unknown/wrong-client/already-consumed token, or (on enroll confirm) mismatched user |
631
+ | `RECOVERY_CODE_INVALID` | 401 | Wrong or already-used recovery code |
632
+
633
+ ---
634
+
635
+ ## Profile management
636
+
637
+ ```ts
638
+ import { authKit } from '@proveanything/smartlinks';
639
+
640
+ // Get current user's profile
641
+ const profile = await authKit.getProfile(clientId);
642
+
643
+ // Update profile
644
+ const updatedProfile = await authKit.updateProfile(clientId, {
645
+ displayName: 'Alice B.',
646
+ avatarUrl: '...'
647
+ });
648
+
649
+ // The SDK automatically swaps in updatedProfile.token so future auth.verify()
650
+ // and authenticated calls use fresh displayName/photoURL claims immediately.
651
+
652
+ // Change password
653
+ await authKit.changePassword(clientId, 'currentPass', 'newPass');
654
+
655
+ // Change email (triggers verification)
656
+ await authKit.changeEmail(clientId, 'newemail@example.com', 'password', redirectUrl);
657
+
658
+ // Delete account
659
+ await authKit.deleteAccount(clientId, 'password', 'DELETE');
660
+ ```
661
+
662
+ `updateProfile` now returns a fresh bearer token together with the updated profile fields. The SDK replaces the in-memory bearer token automatically so token-backed identity reads stay current without an extra refresh step.
663
+
664
+ ---
665
+
666
+ ## Email verification
667
+
668
+ Auth Kit can send and verify email addresses after registration:
669
+
670
+ ```ts
671
+ await authKit.sendEmailVerification(clientId, {
672
+ userId,
673
+ email: 'user@example.com',
674
+ redirectUrl: 'https://myapp.example.com/auth/verified',
675
+ });
676
+
677
+ // On callback page
678
+ await authKit.verifyEmail(clientId, tokenFromUrl);
679
+ ```
680
+
681
+ ---
682
+
683
+ ## Password reset
684
+
685
+ ```ts
686
+ await authKit.requestPasswordReset(clientId, {
687
+ email: 'user@example.com',
688
+ redirectUrl: 'https://myapp.example.com/auth/reset',
689
+ clientName: 'My App',
690
+ });
691
+
692
+ // On reset page — verify token is still valid before showing the form
693
+ await authKit.verifyResetToken(clientId, tokenFromUrl);
694
+
695
+ // Complete reset
696
+ await authKit.completePasswordReset(clientId, tokenFromUrl, 'newSecurePassword');
697
+ ```
698
+
699
+ ---
700
+
701
+ ## Account security policy
702
+
703
+ Each collection can configure account-security rules. **The API enforces all of it**; your
704
+ login UI reads the policy for UX only (a live password checklist, idle sign-out). There are
705
+ two sides: an **admin** writes the policy, and the **login UI** reads the public subset.
706
+
707
+ **Read (login UI, public — no auth):**
708
+
709
+ ```ts
710
+ const config = await authKit.load(clientId);
711
+ const policy = config.security?.passwordPolicy; // min length, char classes, block-common
712
+ const session = config.security?.session; // inactivity + absolute timeouts, rememberMe
713
+ ```
714
+
715
+ `lockout` values are admin-only and never returned by `load`.
716
+
717
+ **Write (admin):** set the whole `security` block with `authKit.update` (or `authKit.create`).
718
+ The shape is {@link AuthKitSecurityConfig}; see {@link AuthKitConfigInput}.
719
+
720
+ ```ts
721
+ await authKit.update(collectionId, clientId, {
722
+ security: {
723
+ passwordPolicy: {
724
+ minLength: 8, // hard floor enforced server-side
725
+ blockCommonPasswords: true, // reject the common/breached list
726
+ requireUppercase: false, requireLowercase: false,
727
+ requireNumber: false, requireSymbol: false,
728
+ expiryDays: 0, // 0 = never expires
729
+ historyCount: 0, // 0 = reuse allowed
730
+ },
731
+ lockout: { // admin-only; enforced server-side
732
+ enabled: true, maxFailedAttempts: 5,
733
+ attemptWindowMinutes: 15, lockoutMinutes: 15,
734
+ notifyUserOnLockout: true,
735
+ },
736
+ session: {
737
+ inactivityTimeoutMinutes: 0, // 0 = disabled (client-enforced when set)
738
+ inactivityWarningSeconds: 60,
739
+ absoluteTimeoutHours: 0, // 0 = use token lifetime (server-enforced)
740
+ rememberMe: true,
741
+ },
742
+ },
743
+ });
744
+ ```
745
+
746
+ Defaults if a collection has never set a policy: 8-char minimum + block-common for everyone,
747
+ lockout disabled, no expiry/history, no idle/absolute timeout. Omit any field to take its default.
748
+
749
+ ### Password policy
750
+
751
+ `register`, `completePasswordReset`, and `changePassword` validate the new password
752
+ server-side and throw a `SmartlinksApiError` with a {@link PasswordPolicyErrorCode}:
753
+
754
+ | `errorCode` (400) | Meaning |
755
+ |---|---|
756
+ | `PASSWORD_TOO_SHORT` | below `minLength` |
757
+ | `PASSWORD_REQUIREMENTS_NOT_MET` | missing a required character class |
758
+ | `PASSWORD_TOO_COMMON` | on the common/breached list |
759
+ | `PASSWORD_RECENTLY_USED` | matched one of the last `historyCount` passwords |
760
+
761
+ Render a live checklist from `policy` so users see the rules before submitting.
762
+
763
+ ### Lockout
764
+
765
+ After too many failed logins the account is temporarily locked. `login` throws:
766
+
767
+ ```ts
768
+ try {
769
+ await authKit.login(clientId, email, password);
770
+ } catch (err) {
771
+ if (err.errorCode === 'ACCOUNT_TEMPORARILY_LOCKED') {
772
+ const mins = Math.ceil(err.details.retryAfterSeconds / 60);
773
+ show(`Too many attempts. Try again in ${mins} minute(s).`);
774
+ }
775
+ }
776
+ ```
777
+
778
+ Failed MFA challenges count toward the same lock. Locking responds identically for unknown
779
+ accounts (no enumeration).
780
+
781
+ ### Password expiry
782
+
783
+ If a password is older than `passwordPolicy.expiryDays`, a valid login is refused with
784
+ **403 `PASSWORD_EXPIRED`** carrying a short-lived `resetToken` — send the user straight into
785
+ the reset form to change it in place:
786
+
787
+ ```ts
788
+ catch (err) {
789
+ if (err.errorCode === 'PASSWORD_EXPIRED') {
790
+ await authKit.completePasswordReset(clientId, err.details.resetToken, newPassword);
791
+ }
792
+ }
793
+ ```
794
+
795
+ ### Session lifetime
796
+
797
+ - **Absolute timeout** (`session.absoluteTimeoutHours`) is enforced server-side on the native
798
+ refresh path: once the session is too old, `refreshToken` throws **401 `SESSION_EXPIRED`**
799
+ (see {@link RefreshErrorCode}) — clear storage and route to login. Web sessions use the
800
+ stateless bearer token and rely on inactivity sign-out below.
801
+ - **Inactivity timeout** (`session.inactivityTimeoutMinutes` / `inactivityWarningSeconds`) is
802
+ **client-enforced** — sign the user out after idle, warning first. Sync across tabs.
803
+ - **`session.rememberMe: false`** → don't persist tokens to durable storage; treat the session
804
+ as browser-scoped.
805
+
806
+ ---
807
+
808
+ ## Own logins (a site's own members)
809
+
810
+ By default an Auth Kit signs people in with their **SmartLinks account**: one account, the same
811
+ everywhere a site uses the shared login. A site that manages its own members (a club, a league, a
812
+ membership site) can instead have **its own logins**: its members are accounts of that site only. The
813
+ same email can be a separate account, with a different password, on another site, and signing in on
814
+ one site doesn't sign anyone in elsewhere.
815
+
816
+ ```ts
817
+ await authKit.setIdentity(collectionId, authKitId, { mode: 'own' })
818
+ // → { identity: { mode: 'own', tenantId }, message }
819
+ ```
820
+
821
+ - **One way.** A site with its own members can't go back to the shared login (they would lose their
822
+ accounts).
823
+ - **New sign-ups** after the switch go to the site's own members. People who signed up before keep their
824
+ SmartLinks account until they are moved across.
825
+ - **One per collection.** Only one Auth Kit can give a collection its own logins (`MEMBER_POOL_CONFLICT`,
826
+ 409, otherwise). You must administer every collection the kit serves (`PERMISSION_DENIED`, 403).
827
+ - **Tokens stay on their site.** A member's session works on that site's Auth Kit and collections only.
828
+ - Every flow above (password, magic link, phone, Google, Apple, LinkedIn, WhatsApp, SMS, MFA, profile,
829
+ resets) works the same way; nothing changes in the login UI or your code.
830
+ - `identity` is read-only on `create` / `update`; it is shown on the config (`authKit.get`).
831
+
832
+ ### Invitation only
833
+
834
+ A site with its own logins can let in only the people it invites:
835
+
836
+ ```ts
837
+ await authKit.update(collectionId, authKitId, { signUp: 'invite' }) // 'open' (default) | 'invite'
838
+ await authKit.invite(collectionId, authKitId, { email: 'jo@example.com', firstName: 'Jo', customFields: { level: 'member' } })
839
+ ```
840
+
841
+ - **Enforced on the server, for every route.** Nobody without an account can get one: `register`,
842
+ `verifyMagicLink`, `verifyPhoneCode`, Google, Apple, LinkedIn and WhatsApp answer `SIGN_UP_CLOSED`
843
+ (403). `sendMagicLink` and `sendPhoneCode` answer as if sent, but send nothing to someone who isn't a
844
+ member, so nobody can find out who is.
845
+ - **`invite`** makes the person's account if they have none, finds or creates their contact in that
846
+ collection with the fields you pass, links the two, and emails a sign-in link to the site (`redirectUrl`,
847
+ default the kit's) that works once for 7 days. It lands like any magic link (`mode=magicLink&token=…`).
848
+ Inviting someone again sends a fresh link. The link is never returned to the admin.
849
+ - **Invited members then sign in any way the site offers.** A magic link, "forgot password" to set a
850
+ password, or Google/Apple/LinkedIn with the same verified email: an invited account nobody has signed
851
+ in to yet can be claimed that way.
852
+ - `signUp` is on the public config (`load`): hide "Create an account" when it's `invite`. Setting it
853
+ needs own logins first (`OWN_LOGINS_REQUIRED`, 409).
854
+ - On any site, a member signing in with a verified email or phone is attached to the contact the
855
+ collection already has for it, so fields the staff set beforehand (a level) are theirs.
856
+
857
+ ## Relationship to other parts of the SDK
858
+
859
+ | Concern | Where it lives |
860
+ |---------|---------------|
861
+ | End-user sign-in / register | `authKit` namespace (this doc) |
862
+ | Admin Bearer token auth | Platform shell — not set by your app |
863
+ | Per-user data storage | `userAppData` namespace — see [app-data-storage.md](app-data-storage.md) |
864
+ | User identity in analytics | `userId` field on `analytics` and `interactions` calls |
865
+
866
+ ---
867
+
868
+ ## Further reading
869
+
870
+ - [members.md](members.md) — members with a level: clubs, leagues, members-only content
871
+ - [app-data-storage.md](app-data-storage.md) — storing user-specific data after login
872
+ - [app-manifest.md](app-manifest.md) — `app.admin.json` setup questions for configuring `clientId`