@veroxm/sdk 1.2.0 → 1.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,9 +1,25 @@
1
1
  # Changelog
2
2
 
3
+ ## 1.3.0
4
+
5
+ - Two-step sign-in (public API 2.5). A sign-in throws `VeroXMTwoStepRequiredError` (a `VeroXMApiError`, code
6
+ `two_step_required`) with a `ticket` and `methods` when the person has it on: finish with
7
+ `auth.completeTwoStep(ticket, { code })` (or `{ recoveryCode }`) or `auth.completeTwoStepWithPasskey(ticket)`. When the
8
+ project requires it and the person has nothing set up, `setupRequired` is true: set up with
9
+ `auth.setUpAuthenticator({ ticket })` and `auth.confirmAuthenticator(code, { ticket })`, or `auth.addPasskey({ ticket })`.
10
+ - The signed-in person's own: `auth.twoStep()`, `setUpAuthenticator()`, `confirmAuthenticator(code)`,
11
+ `removeAuthenticator()`, `newRecoveryCodes()`, `addPasskey({ name })` and `removePasskey(id)`. Setting up or removing
12
+ a way needs a sign-in in the last 15 minutes (else code `reauthenticate`).
13
+ - Passkeys: `auth.signInWithPasskey()`. In a browser they use `navigator.credentials`; elsewhere (React Native) pass
14
+ your own with `auth.usePasskeyProvider()`. `creationOptionsFromJSON`, `requestOptionsFromJSON` and
15
+ `credentialToJSON` convert WebAuthn's JSON forms.
16
+
3
17
  ## 1.2.0
4
18
 
5
19
  - `Schemas['ProcessRunDetail']` has `branches`: while a run is on a parallel step, where each branch stands
6
20
  (public API 2.3). `processes.run(id)` returns them.
21
+ - `Schemas` has the promote-content shapes (`PromoteContentRequest`, `ContentPromotionPreview`, `ContentPromotionResult`)
22
+ and `ApiPaths` their routes (public API 2.4), used by `@veroxm/cli`.
7
23
 
8
24
  ## 1.1.0
9
25
 
package/README.md CHANGED
@@ -187,6 +187,41 @@ redirect address, check the `state` and call
187
187
  `exchangeSocialCode(code, codeVerifier)`. React Native needs a Web Crypto
188
188
  polyfill (such as `react-native-quick-crypto`) for the PKCE challenge.
189
189
 
190
+ ### Two-step sign-in and passkeys
191
+
192
+ When someone has two-step sign-in on, signing in throws
193
+ `VeroXMTwoStepRequiredError` with a ticket. Ask for the code from their
194
+ authenticator app (or a recovery code, or their passkey) and finish:
195
+
196
+ ```ts
197
+ import { VeroXMTwoStepRequiredError } from '@veroxm/sdk';
198
+
199
+ try {
200
+ await app.auth.signInWithEmail(email, password);
201
+ } catch (e) {
202
+ if (!(e instanceof VeroXMTwoStepRequiredError)) throw e;
203
+ if (e.setupRequired) {
204
+ // The project requires two-step sign-in and this person has nothing set up yet.
205
+ const { otpauthUrl } = await app.auth.setUpAuthenticator({ ticket: e.ticket }); // show as a QR code
206
+ const { recoveryCodes } = await app.auth.confirmAuthenticator(code, { ticket: e.ticket }); // signs in
207
+ } else {
208
+ await app.auth.completeTwoStep(e.ticket, { code }); // or { recoveryCode }, or completeTwoStepWithPasskey(e.ticket)
209
+ }
210
+ }
211
+
212
+ // Signed in: set up, see and remove ways of signing in (within 15 minutes of signing in)
213
+ const { secret, otpauthUrl } = await app.auth.setUpAuthenticator();
214
+ const { recoveryCodes } = await app.auth.confirmAuthenticator(code); // show the codes once
215
+ await app.auth.twoStep(); // { enabled, methods, recoveryCodesLeft, passkeys, ... }
216
+ await app.auth.addPasskey({ name: 'Work laptop' });
217
+
218
+ // Passkeys: no password, and no second step (the device checks it's them)
219
+ await app.auth.signInWithPasskey();
220
+ ```
221
+
222
+ Passkeys use the browser's `navigator.credentials`. In React Native, pass a
223
+ provider that calls the platform's passkey API with `auth.usePasskeyProvider()`.
224
+
190
225
  ## Visitor tracking (Experience OS)
191
226
 
192
227
  Record page views and actions, the visitor's consent, and who they are, so
package/dist/auth.d.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  import type { AuthUser, TokenStorage } from './token-storage.js';
2
2
  import type { Schemas } from './schemas.js';
3
+ import { type PasskeyProvider } from './passkeys.js';
3
4
  /** A code from an email, with the address; or the token from the email's link. */
4
5
  export type EmailCode = {
5
6
  email: string;
@@ -14,6 +15,22 @@ export type EmailCode = {
14
15
  export type Account = Schemas['Account'];
15
16
  /** A social sign-in option to show a button for. */
16
17
  export type SocialProvider = Schemas['SocialProvider'];
18
+ /** The signed-in person's two-step sign-in and passkeys, from `twoStep()`. */
19
+ export type TwoStepStatus = Schemas['TwoStepStatus'];
20
+ /** A passkey on the person's account. */
21
+ export type Passkey = Schemas['Passkey'];
22
+ /** What `setUpAuthenticator` returns: show `otpauthUrl` as a QR code, and `secret` for typing in by hand. */
23
+ export type AuthenticatorSetup = Schemas['TotpSetup'];
24
+ /** A second step: a code from the authenticator app, or a recovery code. */
25
+ export type SecondStep = {
26
+ code: string;
27
+ } | {
28
+ recoveryCode: string;
29
+ };
30
+ /** A setup ticket (from a VeroXMTwoStepRequiredError with `setupRequired`), when the project requires two-step sign-in. */
31
+ export interface WithTicket {
32
+ ticket?: string;
33
+ }
17
34
  /** What `startSocialSignIn` returns: send the person to `url`, keep the rest until they come back. */
18
35
  export interface SocialSignInStart {
19
36
  url: string;
@@ -52,12 +69,16 @@ export declare class VeroXMAuth {
52
69
  private refreshInFlight;
53
70
  private readonly listeners;
54
71
  private readonly userListeners;
72
+ private passkeyProvider;
55
73
  constructor(apiBase: string, storage: TokenStorage, pending?: PendingStore);
56
74
  /** Static-key mode: no login round-trip, no expiry, no refresh token. */
57
75
  signInWithApiKey(apiKey: string): void;
58
76
  /** Username/password mode -- exchanges credentials for an access+refresh token pair and persists it via the configured TokenStorage. */
59
77
  signInWithCredentials(username: string, password: string): Promise<AuthUser | null>;
60
- /** Signs in a built-in account with its email and password. Throws VeroXMApiError with code `email_not_verified` until the email is confirmed. */
78
+ /**
79
+ * Signs in a built-in account with its email and password. Throws VeroXMApiError with code `email_not_verified` until
80
+ * the email is confirmed, and VeroXMTwoStepRequiredError when the person has two-step sign-in on.
81
+ */
61
82
  signInWithEmail(email: string, password: string): Promise<AuthUser | null>;
62
83
  /** Signs out here: the refresh token is revoked on the server too (best effort), and the stored session cleared. */
63
84
  signOut(): Promise<void>;
@@ -110,6 +131,51 @@ export declare class VeroXMAuth {
110
131
  deleteAccount(input?: {
111
132
  password?: string;
112
133
  }): Promise<void>;
134
+ /**
135
+ * Finishes a sign-in that threw VeroXMTwoStepRequiredError: with a code from the person's authenticator app, or one
136
+ * of their recovery codes (each works once).
137
+ */
138
+ completeTwoStep(ticket: string, step: SecondStep): Promise<AuthUser | null>;
139
+ /** Finishes a sign-in that threw VeroXMTwoStepRequiredError with one of the person's passkeys. */
140
+ completeTwoStepWithPasskey(ticket: string): Promise<AuthUser | null>;
141
+ /** Signs in with a passkey: the device offers the person theirs and checks it's them, so there's no second step. */
142
+ signInWithPasskey(): Promise<AuthUser | null>;
143
+ /** The signed-in person's two-step sign-in: whether it's on, how, recovery codes left, and their passkeys. */
144
+ twoStep(): Promise<TwoStepStatus>;
145
+ /**
146
+ * Starts setting up an authenticator app. Show `otpauthUrl` as a QR code (and `secret` to type in), then call
147
+ * `confirmAuthenticator` with a code from the app. Signed in, this needs a sign-in in the last 15 minutes (else
148
+ * VeroXMApiError `reauthenticate`); with a setup ticket, it's for the person signing in.
149
+ */
150
+ setUpAuthenticator(options?: WithTicket): Promise<AuthenticatorSetup>;
151
+ /**
152
+ * Confirms the authenticator app with a code from it. Resolves the recovery codes when it's the first way set up
153
+ * (show them once), else null. With a setup ticket, this also finishes signing in.
154
+ */
155
+ confirmAuthenticator(code: string, options?: WithTicket): Promise<{
156
+ recoveryCodes: string[] | null;
157
+ }>;
158
+ /** Removes the authenticator app (needs a recent sign-in). */
159
+ removeAuthenticator(): Promise<void>;
160
+ /** New recovery codes, replacing the old ones (needs a recent sign-in). */
161
+ newRecoveryCodes(): Promise<string[]>;
162
+ /**
163
+ * Adds a passkey on this device (needs a recent sign-in). `name` tells passkeys apart ("Work laptop"). Resolves the
164
+ * recovery codes when it's the first way set up for two-step sign-in. With a setup ticket, also finishes signing in.
165
+ */
166
+ addPasskey(options?: WithTicket & {
167
+ name?: string;
168
+ }): Promise<{
169
+ passkey: Passkey;
170
+ recoveryCodes: string[] | null;
171
+ }>;
172
+ /** Removes one of the person's passkeys (needs a recent sign-in). */
173
+ removePasskey(id: number): Promise<void>;
174
+ /**
175
+ * Where passkeys are made and used: the browser's navigator.credentials unless you pass another (React Native, or
176
+ * tests). It takes and returns WebAuthn's JSON forms.
177
+ */
178
+ usePasskeyProvider(provider: PasskeyProvider): void;
113
179
  /** The social sign-in options the project has turned on, for your buttons. */
114
180
  socialProviders(): Promise<SocialProvider[]>;
115
181
  /**
package/dist/auth.js CHANGED
@@ -1,6 +1,7 @@
1
1
  import { rawRequest } from './http.js';
2
2
  import { VeroXMNotAuthenticatedError } from './errors.js';
3
3
  import { createPkce, randomString } from './pkce.js';
4
+ import { browserPasskeys } from './passkeys.js';
4
5
  function defaultPendingStore() {
5
6
  try {
6
7
  if (typeof window !== 'undefined' && window.sessionStorage) {
@@ -46,6 +47,7 @@ export class VeroXMAuth {
46
47
  this.refreshInFlight = null;
47
48
  this.listeners = new Set();
48
49
  this.userListeners = new Set();
50
+ this.passkeyProvider = browserPasskeys;
49
51
  }
50
52
  /** Static-key mode: no login round-trip, no expiry, no refresh token. */
51
53
  signInWithApiKey(apiKey) {
@@ -65,7 +67,10 @@ export class VeroXMAuth {
65
67
  await this.persistSession(data);
66
68
  return this.currentUser();
67
69
  }
68
- /** Signs in a built-in account with its email and password. Throws VeroXMApiError with code `email_not_verified` until the email is confirmed. */
70
+ /**
71
+ * Signs in a built-in account with its email and password. Throws VeroXMApiError with code `email_not_verified` until
72
+ * the email is confirmed, and VeroXMTwoStepRequiredError when the person has two-step sign-in on.
73
+ */
69
74
  async signInWithEmail(email, password) {
70
75
  await this.signInWithCredentials(email, password);
71
76
  return this.currentUser();
@@ -157,6 +162,89 @@ export class VeroXMAuth {
157
162
  await this.storage.clear();
158
163
  this.notify(null);
159
164
  }
165
+ // ------------------------------------------------------------------ two-step sign-in and passkeys
166
+ /**
167
+ * Finishes a sign-in that threw VeroXMTwoStepRequiredError: with a code from the person's authenticator app, or one
168
+ * of their recovery codes (each works once).
169
+ */
170
+ async completeTwoStep(ticket, step) {
171
+ return this.signInWith('/auth/two-step', { ticket, ...step });
172
+ }
173
+ /** Finishes a sign-in that threw VeroXMTwoStepRequiredError with one of the person's passkeys. */
174
+ async completeTwoStepWithPasskey(ticket) {
175
+ const options = (await this.post('/auth/two-step/passkey/options', { ticket }));
176
+ const passkey = await this.passkeyProvider.get(options);
177
+ return this.signInWith('/auth/two-step', { ticket, passkey });
178
+ }
179
+ /** Signs in with a passkey: the device offers the person theirs and checks it's them, so there's no second step. */
180
+ async signInWithPasskey() {
181
+ const options = (await this.post('/auth/passkey/options', {}));
182
+ const response = await this.passkeyProvider.get(options);
183
+ return this.signInWith('/auth/passkey', { response });
184
+ }
185
+ /** The signed-in person's two-step sign-in: whether it's on, how, recovery codes left, and their passkeys. */
186
+ async twoStep() {
187
+ return (await this.authed('GET', '/auth/me/two-step'));
188
+ }
189
+ /**
190
+ * Starts setting up an authenticator app. Show `otpauthUrl` as a QR code (and `secret` to type in), then call
191
+ * `confirmAuthenticator` with a code from the app. Signed in, this needs a sign-in in the last 15 minutes (else
192
+ * VeroXMApiError `reauthenticate`); with a setup ticket, it's for the person signing in.
193
+ */
194
+ async setUpAuthenticator(options = {}) {
195
+ if (options.ticket)
196
+ return (await this.post('/auth/two-step/setup/totp', { ticket: options.ticket }));
197
+ return (await this.authed('POST', '/auth/me/two-step/totp'));
198
+ }
199
+ /**
200
+ * Confirms the authenticator app with a code from it. Resolves the recovery codes when it's the first way set up
201
+ * (show them once), else null. With a setup ticket, this also finishes signing in.
202
+ */
203
+ async confirmAuthenticator(code, options = {}) {
204
+ if (options.ticket) {
205
+ const data = (await this.post('/auth/two-step/setup/totp/confirm', { ticket: options.ticket, code }));
206
+ this.apiKey = null;
207
+ await this.persistSession(data);
208
+ return { recoveryCodes: data.recoveryCodes };
209
+ }
210
+ return (await this.authed('POST', '/auth/me/two-step/totp/confirm', { code }));
211
+ }
212
+ /** Removes the authenticator app (needs a recent sign-in). */
213
+ async removeAuthenticator() {
214
+ await this.authed('DELETE', '/auth/me/two-step/totp');
215
+ }
216
+ /** New recovery codes, replacing the old ones (needs a recent sign-in). */
217
+ async newRecoveryCodes() {
218
+ return (await this.authed('POST', '/auth/me/two-step/recovery-codes')).recoveryCodes;
219
+ }
220
+ /**
221
+ * Adds a passkey on this device (needs a recent sign-in). `name` tells passkeys apart ("Work laptop"). Resolves the
222
+ * recovery codes when it's the first way set up for two-step sign-in. With a setup ticket, also finishes signing in.
223
+ */
224
+ async addPasskey(options = {}) {
225
+ if (options.ticket) {
226
+ const creation = (await this.post('/auth/two-step/setup/passkey/options', { ticket: options.ticket }));
227
+ const response = await this.passkeyProvider.create(creation);
228
+ const data = (await this.post('/auth/two-step/setup/passkey', { ticket: options.ticket, response, name: options.name }));
229
+ this.apiKey = null;
230
+ await this.persistSession(data);
231
+ return { passkey: data.passkey, recoveryCodes: data.recoveryCodes };
232
+ }
233
+ const creation = (await this.authed('POST', '/auth/me/passkeys/options'));
234
+ const response = await this.passkeyProvider.create(creation);
235
+ return (await this.authed('POST', '/auth/me/passkeys', { response, ...(options.name ? { name: options.name } : {}) }));
236
+ }
237
+ /** Removes one of the person's passkeys (needs a recent sign-in). */
238
+ async removePasskey(id) {
239
+ await this.authed('DELETE', `/auth/me/passkeys/${encodeURIComponent(String(id))}`);
240
+ }
241
+ /**
242
+ * Where passkeys are made and used: the browser's navigator.credentials unless you pass another (React Native, or
243
+ * tests). It takes and returns WebAuthn's JSON forms.
244
+ */
245
+ usePasskeyProvider(provider) {
246
+ this.passkeyProvider = provider;
247
+ }
160
248
  // ------------------------------------------------------------------ social sign-in
161
249
  /** The social sign-in options the project has turned on, for your buttons. */
162
250
  async socialProviders() {
package/dist/errors.d.ts CHANGED
@@ -18,6 +18,26 @@ export declare class VeroXMApiError extends Error {
18
18
  constructor(status: number, body: unknown);
19
19
  private static messageFrom;
20
20
  }
21
+ /** The ways of taking the second step of a sign-in. */
22
+ export type TwoStepMethod = 'totp' | 'passkey' | 'recovery_code';
23
+ /**
24
+ * Thrown by a sign-in when the person has two-step sign-in on (`code` is `two_step_required`): finish with
25
+ * `auth.completeTwoStep(error.ticket, ...)`. Or, when the project requires two-step sign-in and the person has nothing
26
+ * set up yet (`setupRequired`, code `two_step_setup_required`): set it up with the ticket
27
+ * (`auth.setUpAuthenticator({ ticket })` or `auth.addPasskey({ ticket })`). The ticket lasts 10 minutes.
28
+ */
29
+ export declare class VeroXMTwoStepRequiredError extends VeroXMApiError {
30
+ readonly ticket: string;
31
+ readonly methods: TwoStepMethod[];
32
+ readonly setupRequired: boolean;
33
+ constructor(status: number, body: {
34
+ ticket: string;
35
+ methods?: unknown;
36
+ code?: string;
37
+ });
38
+ }
39
+ /** The error for an API answer: a two-step sign-in challenge, or a plain VeroXMApiError. */
40
+ export declare function apiError(status: number, body: unknown): VeroXMApiError;
21
41
  /** Thrown when a request needs an authenticated client but no credentials have been provided yet. */
22
42
  export declare class VeroXMNotAuthenticatedError extends Error {
23
43
  constructor();
package/dist/errors.js CHANGED
@@ -37,6 +37,29 @@ export class VeroXMApiError extends Error {
37
37
  return `Request failed with status ${status}`;
38
38
  }
39
39
  }
40
+ /**
41
+ * Thrown by a sign-in when the person has two-step sign-in on (`code` is `two_step_required`): finish with
42
+ * `auth.completeTwoStep(error.ticket, ...)`. Or, when the project requires two-step sign-in and the person has nothing
43
+ * set up yet (`setupRequired`, code `two_step_setup_required`): set it up with the ticket
44
+ * (`auth.setUpAuthenticator({ ticket })` or `auth.addPasskey({ ticket })`). The ticket lasts 10 minutes.
45
+ */
46
+ export class VeroXMTwoStepRequiredError extends VeroXMApiError {
47
+ constructor(status, body) {
48
+ super(status, body);
49
+ this.name = 'VeroXMTwoStepRequiredError';
50
+ this.ticket = body.ticket;
51
+ this.methods = Array.isArray(body.methods) ? body.methods.filter((m) => typeof m === 'string') : [];
52
+ this.setupRequired = body.code === 'two_step_setup_required';
53
+ }
54
+ }
55
+ /** The error for an API answer: a two-step sign-in challenge, or a plain VeroXMApiError. */
56
+ export function apiError(status, body) {
57
+ const b = body && typeof body === 'object' ? body : null;
58
+ if (status === 401 && b && (b.code === 'two_step_required' || b.code === 'two_step_setup_required') && typeof b.ticket === 'string') {
59
+ return new VeroXMTwoStepRequiredError(status, b);
60
+ }
61
+ return new VeroXMApiError(status, body);
62
+ }
40
63
  /** Thrown when a request needs an authenticated client but no credentials have been provided yet. */
41
64
  export class VeroXMNotAuthenticatedError extends Error {
42
65
  constructor() {