diff --git a/.llms-snapshots/llms-full.txt b/.llms-snapshots/llms-full.txt index 6bc09120..e8aacd9c 100644 --- a/.llms-snapshots/llms-full.txt +++ b/.llms-snapshots/llms-full.txt @@ -733,121 +733,218 @@ Here are some customization options to tailor your sign-in flow and handle sessi --- -## Sign-In Providers +## Sign Context -Juno supports Internet Identity and NFID, which also offers additional authentication methods like Google and email. +Some options apply to both sign-up and sign-in flows. -**Note:** - -You can implement the `signIn` function in your application as many times as you wish, with various configurations. It is also perfectly acceptable to use both Internet Identity and NFID within the same project. +| Option | Type | Default | Description | +| --- | --- | --- | --- | +| `windowGuard` | `boolean` | `true` | Prevents the user from closing the current window/tab while the flow is in progress. Disabling it is discouraged. | --- -### Internet Identity +## Session Expiration -Internet Identity is available at two different URLs: `internetcomputer.org` and `ic0.app`. +To proactively detect when a session duration expires, you can use the pre-bundled Web Worker provided by Juno's SDK. -By default, the SDK uses `internetcomputer.org`. +To do so, you can follow these steps: + +1. Copy the worker file provided by Juno's SDK to your app's static folder. For example, to your `public` folder with a NPM `postinstall` script: + +``` +{ "scripts": { "postinstall": "node -e \"require('fs').cpSync('node_modules/@junobuild/core/dist/workers/', './static/workers', {recursive: true});\"" }} +``` + +Once configured, run `npm run postinstall` manually to trigger the initial copy. Every time you run `npm ci`, the post-install target will execute, ensuring the worker is copied. + +2. Enable the option when you initialize Juno: + +``` +import { initSatellite } from "@junobuild/core";await initSatellite({ workers: { auth: true }}); +``` + +The `auth` option can accept either `true`, which will default to using a worker located at [https://yourapp/workers/auth.worker.js](https://yourapp/workers/auth.worker.js), or a custom `string` to provide your own URL. + +When the session expires, it will automatically be terminated with a standard [sign-out](/docs/build/authentication/development.md#sign-out). Additionally, an event called `junoSignOutAuthTimer` will be thrown at the `document` level. This event can be used, for example, to display a warning to your users or if you wish to reload the window. ``` -import { signIn, InternetIdentityProvider } from "@junobuild/core";// Default domain is 'internetcomputer.org'await signIn({ provider: new InternetIdentityProvider({})}); +document.addEventListener( "junoSignOutAuthTimer", () => { // Display an information to your users }, { passive: true }); ``` -You can switch to `ic0.app` by setting the domain option accordingly. +The worker also emits an event named `junoDelegationRemainingTime`, which provides the remaining duration in milliseconds of the authentication delegation. This can be useful if you want to display to your users how much time remains in their active session. ``` -import { signIn, InternetIdentityProvider } from "@junobuild/core";await signIn({ provider: new InternetIdentityProvider({ domain: "ic0.app" })}); +document.addEventListener( "junoDelegationRemainingTime", ({ detail: remainingTime }) => { // Display the remaining session duration to your users }, { passive: true }); ``` -We use the former by default because we believe it offers a better user experience and branding. +# Development + +This page provides an overview of how to integrate authentication features with the Juno SDK, including sign-in, sign-out, and user session subscription within your app. **Note:** -It is worth mentioning that your users will be able to sign in to your app with Internet Identity, regardless of which of those two domains they originally created their identity on. +The Juno SDK must be [installed](/docs/setup-the-sdk.md) and initialized in your app to use the authentication features. --- -### NFID +## Sign-up + +If your app provides features that require authentication, your users need to sign up to create an identity that grants them access to your application. + +### Passkeys -To set up NFID, you need to configure the corresponding provider and provide your application name and a link to your logo. +With Passkeys, sign-up creates a digital key that lives on the user's device — for example in the browser, iCloud Keychain, Google Password Manager, etc. + +During sign-up, the user will be asked to use their authenticator twice: once to generate the passkey, and once more to sign their new identity which is then used to interact securely with your satellite. ``` -import { signIn, NFIDProvider } from "@junobuild/core";await signIn({ provider: new NFIDProvider({ appName: "Your app name", logoUrl: "https://somewhere.com/your_logo.png" })}); +import { signUp } from "@junobuild/core";await signUp({ webauthn: {}}); ``` ---- +**Note:** -## Session Expiration +Returning users don't need to go through sign-up again. They can simply use ([sign-in](#passkeys-1)) with their existing passkey to authenticate. -To proactively detect when a session duration expires, you can use the pre-bundled Web Worker provided by Juno's SDK. +#### Options -To do so, you can follow these steps: +Passkey sign-up can be customized with a handful of options. These let you control how long a session lasts, how the passkey is displayed to the user, and whether you want to track progress in your own UI. -1. Copy the worker file provided by Juno's SDK to your app's static folder. For example, to your `public` folder with a NPM `postinstall` script: +| Option | Type | Default | Description | +| --- | --- | --- | --- | +| `maxTimeToLiveInMilliseconds` | `number` | **4 hours** | Maximum lifetime of the user's session in **milliseconds**. Once expired, the session cannot be extended. | +| `onProgress` | `(progress) => void` | | Callback fired at each step of the sign-up flow (e.g., creating credential, validating, signing). Useful if you want to show progress indicators in your UI. | +| `passkey` | `CreatePasskeyOptions` | | Options for how the passkey should be created. | + +The `passkey` option accepts the following fields: + +| Option | Type | Default | Description | +| --- | --- | --- | --- | +| `appId.id` | `string` | Current URL `hostname` | Domain your passkeys are tied to (e.g., `example.com` or `login.example.com`). Subdomains are supported. | +| `user.displayName` | `string` | `document.title` | Friendly name for the account (e.g., `"Maria Sanchez"`). Helps the user recognize which passkey belongs to them. | +| `user.name` | `string` | `displayName` | User-recognizable account identifier (e.g., email, username, or phone number). Distinguishes between accounts. | + +Example with options: ``` -{ "scripts": { "postinstall": "node -e \"require('fs').cpSync('node_modules/@junobuild/core/dist/workers/', './static/workers', {recursive: true});\"" }} +import { signUp } from "@junobuild/core";await signUp({ webauthn: { options: { maxTimeToLiveInMilliseconds: 1000 * 60 * 60, // 1 hour onProgress: ({ step, state }) => { console.log("Step:", step, "State:", state); }, passkey: { displayName: "My Cool App" // or user input } } }}); ``` -Once configured, run `npm run postinstall` manually to trigger the initial copy. Every time you run `npm ci`, the post-install target will execute, ensuring the worker is copied. +**Tip:** -2. Enable the option when you initialize Juno: +It's common to let the user choose a nickname during sign-up. + +This nickname can be passed as the `displayName` in the `passkey` option so the passkey is easy to recognize the next time they sign in (e.g. in iCloud Keychain or Google Password Manager). + +#### Checking Availability + +Not every browser or device supports Passkeys. You can check availability before showing a sign-up button with: ``` -import { initSatellite } from "@junobuild/core";await initSatellite({ workers: { auth: true }}); +import { isWebAuthnAvailable } from "@junobuild/core";if (await isWebAuthnAvailable()) { // Show Passkey sign-up option} ``` -The `auth` option can accept either `true`, which will default to using a worker located at [https://yourapp/workers/auth.worker.js](https://yourapp/workers/auth.worker.js), or a custom `string` to provide your own URL. +### Internet Identity / NFID -When the session expires, it will automatically be terminated with a standard [sign-out](/docs/build/authentication/development.md#sign-out). Additionally, an event called `junoSignOutAuthTimer` will be thrown at the `document` level. This event can be used, for example, to display a warning to your users or if you wish to reload the window. +With Internet Identity and NFID there is no separate sign-up step. Users always go through sign-in, and if it's their first time, that flow will automatically create their identity. + +In practice, your UI could simply show a button like "Continue with Internet Identity" or "Continue with NFID". + +--- + +## Sign-in + +If your app provides features that require authentication, your users need to sign in to access their identity and continue using your application securely. + +### Passkeys + +With Passkeys, returning users sign in using the digital key previously created on their device — for example in the browser, iCloud Keychain, Google Password Manager, etc. + +The user will be asked to use their authenticator to prove possession of the passkey and re-establish a valid session with your satellite. ``` -document.addEventListener( "junoSignOutAuthTimer", () => { // Display an information to your users }, { passive: true }); +import { signIn } from "@junobuild/core";await signIn({ webauthn: {}}); ``` -The worker also emits an event named `junoDelegationRemainingTime`, which provides the remaining duration in milliseconds of the authentication delegation. This can be useful if you want to display to your users how much time remains in their active session. +**Note:** + +New users must first go through ([sign-up](#passkeys)) to create a passkey before they can sign in. + +#### Options + +Passkey sign-in can also be customized with options similar to sign-up. These let you control how long a session lasts and whether you want to track progress in your own UI. + +| Option | Type | Default | Description | +| --- | --- | --- | --- | +| `maxTimeToLiveInMilliseconds` | `number` | **4 hours** | Maximum lifetime of the user's session in **milliseconds**. Once expired, the session cannot be extended. | +| `onProgress` | `(progress) => void` | | Callback fired at each step of the sign-up flow (e.g., fetching credential, validating, signing). Useful to customize your UI. | + +Example with options: ``` -document.addEventListener( "junoDelegationRemainingTime", ({ detail: remainingTime }) => { // Display the remaining session duration to your users }, { passive: true }); +import { signIn } from "@junobuild/core";await signIn({ webauthn: { options: { maxTimeToLiveInMilliseconds: 1000 * 60 * 60, // 1 hour onProgress: ({ step, state }) => { console.log("Step:", step, "State:", state); } } }}); ``` -# Development +### Internet Identity -This page provides an overview of how to integrate authentication features with the Juno SDK, including sign-in, sign-out, and user session subscription within your app. +When a user signs in with Internet Identity, they log in with the provider to confirm their identity. If successful, a session is created and the user can interact with your satellite. There's no separate sign-up step — the account in your satellite is created automatically the first time they sign in, so the user can access your services right away. -**Note:** +``` +import { signIn } from "@junobuild/core";await signIn({ ii: {}}); +``` -The Juno SDK must be [installed](/docs/setup-the-sdk.md) and initialized in your app to use the authentication features. +#### Options ---- +Internet Identity sign-in can be customized with options that let you control session lifetime, provider configuration, or track progress during the flow. -## Sign-in +| Option | Type | Default | Description | +| --- | --- | --- | --- | +| `maxTimeToLiveInNanoseconds` | `BigInt(4 * 60 * 60 * 1000 * 1000 * 1000)` | **4 hours** | Maximum lifetime of the user's session in **nanoseconds**. Once expired, the session cannot be extended. | +| `windowed` | `boolean` | `true` | By default, the authentication flow is presented in a popup window on desktop that is automatically centered on the browser. This behavior can be turned off by setting the option to `false`, causing the authentication flow to happen in a separate tab instead. | +| `derivationOrigin` | `string` or `URL` | | The main domain to be used to ensure your users are identified with the same public ID, regardless of which of your satellite's URLs they use to access your application. | +| `onProgress` | `(progress) => void` | | Callback for provider sign-in and user creation/loading. | +| `domain` | `internetcomputer.org` or `ic0.app` | `internetcomputer.org` | The domain on which to open Internet Identity. | -You can authorize an existing or new user with the identity provider using `signIn`. +Example with options: ``` -import { signIn } from "@junobuild/core";await signIn(); +await signIn({ ii: { options: { maxTimeToLiveInNanoseconds: BigInt(24 * 60 * 60 * 1000 * 1000 * 1000), // 1 day onProgress: ({ step, state }) => { console.log("Step:", step, "State:", state); }, derivationOrigin: "https://myapp.com" } }}); ``` -The sign-in feature supports following customization options: +#### Handling Errors -| Option | Default Value | Description | -| --- | --- | --- | -| `maxTimeToLive` | `BigInt(4 * 60 * 60 * 1000 * 1000 * 1000)` | Specifies the duration for the session (defaults to **4 hours**). It's **important** to note that this duration remains constant, whether the users are active or inactive. | -| `windowed` | `true` | By default, the authentication flow is presented in a popup window on desktop that is automatically centered on the browser. This behavior can be turned off by setting the option to `false`, causing the authentication flow to happen in a separate tab instead. | -| `derivationOrigin` | — | The main domain to be used to ensure your users are identified with the same public ID, regardless of which of your satellite’s URLs they use to access your application. | -| `allowPin` | `false` | We consider the specific PIN authentication method of [Internet Identity](https://internetcomputer.org/docs/current/references/ii-spec#client-authentication-protocol) as "insecure" because users can easily lose their login information if they do not register a passphrase, particularly as Safari clears the browser cache every two weeks in cases of inactivity. This is why we **disable** it by default. | +If the sign-in flow encounters an error, an exception will be thrown. -You can configure the default sign-in flow that uses Internet Identity. You can also set NFID as a provider. Check out the [advanced Sign-in guidelines](/docs/build/authentication/customization.md#sign-in-providers) for more details. +When a user cancels sign-in with Internet Identity (e.g., by closing the modal), the library throws a `SignInUserInterruptError`. This error indicates that the user intentionally interrupted the sign-in process, and it's generally best practice to ignore it rather than showing an error message. -### Handling Errors +``` +import { signIn } from "@junobuild/core";try { await signIn({ ii: {} });} catch (error: unknown) { if (error instanceof SignInUserInterruptError) { // User canceled sign-in, no need to show an error return; } // Handle other errors console.error("Sign-in failed:", error);} +``` -If the sign-in flow encounters an error, an exception will be thrown. +### NFID + +NFID flows follow a similar pattern to authentication with Internet Identity. The user signs in with the provider, and if successful, a session is created so they can interact with your satellite. If it's their first time, the account in your satellite is created automatically. + +``` +import { signIn } from "@junobuild/core";await signIn({ nfid: {}}); +``` + +#### Options + +NFID sign-in can be customized with following options: + +| Option | Default Value | Default | Description | +| --- | --- | --- | --- | +| `maxTimeToLiveInNanoseconds` | `BigInt(4 * 60 * 60 * 1000 * 1000 * 1000)` | **4 hours** | Maximum lifetime of the user's session in **nanoseconds**. Once expired, the session cannot be extended. | +| `windowed` | `boolean` | `true` | By default, the authentication flow is presented in a popup window on desktop that is automatically centered on the browser. This behavior can be turned off by setting the option to `false`, causing the authentication flow to happen in a separate tab instead. | +| `derivationOrigin` | `string` or `URL` | | The main domain to be used to ensure your users are identified with the same public ID, regardless of which of your satellite's URLs they use to access your application. | +| `onProgress` | `(progress) => void` | | Callback for provider sign-in and user creation/loading. | +| `appName` | `string` | | The name of your application, shown to the user during sign-in. | +| `logoUrl` | `string` | | URL of your application's logo, shown to the user during sign-in. | -When a user cancels sign-in (e.g., by closing the modal), the library throws a `SignInUserInterruptError`. This error indicates that the user intentionally interrupted the sign-in process, and it's generally best practice to ignore it rather than showing an error message. +Example with options: ``` -import { signIn } from "@junobuild/core";try { await signIn();} catch (error: unknown) { if (error instanceof SignInUserInterruptError) { // User canceled sign-in, no need to show an error return; } // Handle other errors console.error("Sign-in failed:", error);} +import { signIn } from "@junobuild/core";await signIn({ nfid: { options: { maxTimeToLiveInNanoseconds: BigInt(24 * 60 * 60 * 1000 * 1000 * 1000), // 1 day onProgress: ({ step, state }) => { console.log("Step:", step, "State:", state); }, appName: "My Cool App", logoUrl: "https://myapp.com/logo.png" } }}); ``` --- diff --git a/docs/build/authentication/customization.md b/docs/build/authentication/customization.md index 8966ecac..52b72067 100644 --- a/docs/build/authentication/customization.md +++ b/docs/build/authentication/customization.md @@ -4,69 +4,13 @@ Here are some customization options to tailor your sign-in flow and handle sessi --- -## Sign-In Providers +## Sign Context -Juno supports Internet Identity and NFID, which also offers additional authentication methods like Google and email. +Some options apply to both sign-up and sign-in flows. -:::note - -You can implement the `signIn` function in your application as many times as you wish, with various configurations. It is also perfectly acceptable to use both Internet Identity and NFID within the same project. - -::: - ---- - -### Internet Identity - -Internet Identity is available at two different URLs: `internetcomputer.org` and `ic0.app`. - -By default, the SDK uses `internetcomputer.org`. - -```typescript -import { signIn, InternetIdentityProvider } from "@junobuild/core"; - -// Default domain is 'internetcomputer.org' -await signIn({ - provider: new InternetIdentityProvider({}) -}); -``` - -You can switch to `ic0.app` by setting the domain option accordingly. - -```typescript -import { signIn, InternetIdentityProvider } from "@junobuild/core"; - -await signIn({ - provider: new InternetIdentityProvider({ - domain: "ic0.app" - }) -}); -``` - -We use the former by default because we believe it offers a better user experience and branding. - -:::note - -It is worth mentioning that your users will be able to sign in to your app with Internet Identity, regardless of which of those two domains they originally created their identity on. - -::: - ---- - -### NFID - -To set up NFID, you need to configure the corresponding provider and provide your application name and a link to your logo. - -```typescript -import { signIn, NFIDProvider } from "@junobuild/core"; - -await signIn({ - provider: new NFIDProvider({ - appName: "Your app name", - logoUrl: "https://somewhere.com/your_logo.png" - }) -}); -``` +| Option | Type | Default | Description | +| ------------- | --------- | ------- | ----------------------------------------------------------------------------------------------------------------- | +| `windowGuard` | `boolean` | `true` | Prevents the user from closing the current window/tab while the flow is in progress. Disabling it is discouraged. | --- diff --git a/docs/build/authentication/development.md b/docs/build/authentication/development.md index bd1c3276..55680dcf 100644 --- a/docs/build/authentication/development.md +++ b/docs/build/authentication/development.md @@ -10,38 +10,199 @@ The Juno SDK must be [installed](../../setup-the-sdk.mdx) and initialized in you --- +## Sign-up + +If your app provides features that require authentication, your users need to sign up to create an identity that grants them access to your application. + +### Passkeys + +With Passkeys, sign-up creates a digital key that lives on the user's device — for example in the browser, iCloud Keychain, Google Password Manager, etc. + +During sign-up, the user will be asked to use their authenticator twice: once to generate the passkey, and once more to sign their new identity which is then used to interact securely with your satellite. + +```typescript +import { signUp } from "@junobuild/core"; + +await signUp({ + webauthn: {} +}); +``` + +:::note + +Returning users don't need to go through sign-up again. They can simply use [sign-in](#passkeys-1) with their existing passkey to authenticate. + +::: + +#### Options + +Passkey sign-up can be customized with a handful of options. These let you control how long a session lasts, how the passkey is displayed to the user, and whether you want to track progress in your own UI. + +| Option | Type | Default | Description | +| ----------------------------- | ---------------------- | ----------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| `maxTimeToLiveInMilliseconds` | `number` | **4 hours** | Maximum lifetime of the user's session in **milliseconds**. Once expired, the session cannot be extended. | +| `onProgress` | `(progress) => void` | | Callback fired at each step of the sign-up flow (e.g., creating credential, validating, signing). Useful if you want to show progress indicators in your UI. | +| `passkey` | `CreatePasskeyOptions` | | Options for how the passkey should be created. | + +The `passkey` option accepts the following fields: + +| Option | Type | Default | Description | +| ------------------ | -------- | ---------------------- | ---------------------------------------------------------------------------------------------------------------- | +| `appId.id` | `string` | Current URL `hostname` | Domain your passkeys are tied to (e.g., `example.com` or `login.example.com`). Subdomains are supported. | +| `user.displayName` | `string` | `document.title` | Friendly name for the account (e.g., `"Maria Sanchez"`). Helps the user recognize which passkey belongs to them. | +| `user.name` | `string` | `displayName` | User-recognizable account identifier (e.g., email, username, or phone number). Distinguishes between accounts. | + +Example with options: + +```typescript +import { signUp } from "@junobuild/core"; + +await signUp({ + webauthn: { + options: { + maxTimeToLiveInMilliseconds: 1000 * 60 * 60, // 1 hour + onProgress: ({ step, state }) => { + console.log("Step:", step, "State:", state); + }, + passkey: { + displayName: "My Cool App" // or user input + } + } + } +}); +``` + +:::tip + +It's common to let the user choose a nickname during sign-up. + +This nickname can be passed as the `displayName` in the `passkey` option so the passkey is easy to recognize the next time they sign in (e.g. in iCloud Keychain or Google Password Manager). + +::: + +#### Checking Availability + +Not every browser or device supports Passkeys. You can check availability before showing a sign-up button with: + +```typescript +import { isWebAuthnAvailable } from "@junobuild/core"; + +if (await isWebAuthnAvailable()) { + // Show Passkey sign-up option +} +``` + +### Internet Identity / NFID + +With Internet Identity and NFID there is no separate sign-up step. Users always go through sign-in, and if it's their first time, that flow will automatically create their identity. + +In practice, your UI could simply show a button like "Continue with Internet Identity" or "Continue with NFID". + +--- + ## Sign-in -You can authorize an existing or new user with the identity provider using `signIn`. +If your app provides features that require authentication, your users need to sign in to access their identity and continue using your application securely. + +### Passkeys + +With Passkeys, returning users sign in using the digital key previously created on their device — for example in the browser, iCloud Keychain, Google Password Manager, etc. + +The user will be asked to use their authenticator to prove possession of the passkey and re-establish a valid session with your satellite. + +```typescript +import { signIn } from "@junobuild/core"; + +await signIn({ + webauthn: {} +}); +``` + +:::note + +New users must first go through [sign-up](#passkeys) to create a passkey before they can sign in. + +::: + +#### Options + +Passkey sign-in can also be customized with options similar to sign-up. These let you control how long a session lasts and whether you want to track progress in your own UI. + +| Option | Type | Default | Description | +| ----------------------------- | -------------------- | ----------- | ------------------------------------------------------------------------------------------------------------------------------ | +| `maxTimeToLiveInMilliseconds` | `number` | **4 hours** | Maximum lifetime of the user's session in **milliseconds**. Once expired, the session cannot be extended. | +| `onProgress` | `(progress) => void` | | Callback fired at each step of the sign-up flow (e.g., fetching credential, validating, signing). Useful to customize your UI. | + +Example with options: + +```typescript +import { signIn } from "@junobuild/core"; + +await signIn({ + webauthn: { + options: { + maxTimeToLiveInMilliseconds: 1000 * 60 * 60, // 1 hour + onProgress: ({ step, state }) => { + console.log("Step:", step, "State:", state); + } + } + } +}); +``` + +### Internet Identity + +When a user signs in with Internet Identity, they log in with the provider to confirm their identity. If successful, a session is created and the user can interact with your satellite. There's no separate sign-up step — the account in your satellite is created automatically the first time they sign in, so the user can access your services right away. ```typescript import { signIn } from "@junobuild/core"; -await signIn(); +await signIn({ + ii: {} +}); ``` -The sign-in feature supports following customization options: +#### Options + +Internet Identity sign-in can be customized with options that let you control session lifetime, provider configuration, or track progress during the flow. -| Option | Default Value | Description | -| ------------------ | ------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -| `maxTimeToLive` | `BigInt(4 * 60 * 60 * 1000 * 1000 * 1000)` | Specifies the duration for the session (defaults to **4 hours**). It's **important** to note that this duration remains constant, whether the users are active or inactive. | -| `windowed` | `true` | By default, the authentication flow is presented in a popup window on desktop that is automatically centered on the browser. This behavior can be turned off by setting the option to `false`, causing the authentication flow to happen in a separate tab instead. | -| `derivationOrigin` | — | The main domain to be used to ensure your users are identified with the same public ID, regardless of which of your satellite’s URLs they use to access your application. | -| `allowPin` | `false` | We consider the specific PIN authentication method of [Internet Identity](https://internetcomputer.org/docs/current/references/ii-spec#client-authentication-protocol) as "insecure" because users can easily lose their login information if they do not register a passphrase, particularly as Safari clears the browser cache every two weeks in cases of inactivity. This is why we **disable** it by default. | +| Option | Type | Default | Description | +| ---------------------------- | ------------------------------------------ | ---------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `maxTimeToLiveInNanoseconds` | `BigInt(4 * 60 * 60 * 1000 * 1000 * 1000)` | **4 hours** | Maximum lifetime of the user's session in **nanoseconds**. Once expired, the session cannot be extended. | +| `windowed` | `boolean` | `true` | By default, the authentication flow is presented in a popup window on desktop that is automatically centered on the browser. This behavior can be turned off by setting the option to `false`, causing the authentication flow to happen in a separate tab instead. | +| `derivationOrigin` | `string` or `URL` | | The main domain to be used to ensure your users are identified with the same public ID, regardless of which of your satellite's URLs they use to access your application. | +| `onProgress` | `(progress) => void` | | Callback for provider sign-in and user creation/loading. | +| `domain` | `internetcomputer.org` or `ic0.app` | `internetcomputer.org` | The domain on which to open Internet Identity. | -You can configure the default sign-in flow that uses Internet Identity. You can also set NFID as a provider. Check out the [advanced Sign-in guidelines](./customization.md#sign-in-providers) for more details. +Example with options: -### Handling Errors +```typescript +await signIn({ + ii: { + options: { + maxTimeToLiveInNanoseconds: BigInt(24 * 60 * 60 * 1000 * 1000 * 1000), // 1 day + onProgress: ({ step, state }) => { + console.log("Step:", step, "State:", state); + }, + derivationOrigin: "https://myapp.com" + } + } +}); +``` + +#### Handling Errors If the sign-in flow encounters an error, an exception will be thrown. -When a user cancels sign-in (e.g., by closing the modal), the library throws a `SignInUserInterruptError`. This error indicates that the user intentionally interrupted the sign-in process, and it's generally best practice to ignore it rather than showing an error message. +When a user cancels sign-in with Internet Identity (e.g., by closing the modal), the library throws a `SignInUserInterruptError`. This error indicates that the user intentionally interrupted the sign-in process, and it's generally best practice to ignore it rather than showing an error message. ```typescript import { signIn } from "@junobuild/core"; try { - await signIn(); + await signIn({ + ii: {} + }); } catch (error: unknown) { if (error instanceof SignInUserInterruptError) { // User canceled sign-in, no need to show an error @@ -53,6 +214,50 @@ try { } ``` +### NFID + +NFID flows follow a similar pattern to authentication with Internet Identity. The user signs in with the provider, and if successful, a session is created so they can interact with your satellite. If it's their first time, the account in your satellite is created automatically. + +```typescript +import { signIn } from "@junobuild/core"; + +await signIn({ + nfid: {} +}); +``` + +#### Options + +NFID sign-in can be customized with following options: + +| Option | Default Value | Default | Description | +| ---------------------------- | ------------------------------------------ | ----------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `maxTimeToLiveInNanoseconds` | `BigInt(4 * 60 * 60 * 1000 * 1000 * 1000)` | **4 hours** | Maximum lifetime of the user's session in **nanoseconds**. Once expired, the session cannot be extended. | +| `windowed` | `boolean` | `true` | By default, the authentication flow is presented in a popup window on desktop that is automatically centered on the browser. This behavior can be turned off by setting the option to `false`, causing the authentication flow to happen in a separate tab instead. | +| `derivationOrigin` | `string` or `URL` | | The main domain to be used to ensure your users are identified with the same public ID, regardless of which of your satellite's URLs they use to access your application. | +| `onProgress` | `(progress) => void` | | Callback for provider sign-in and user creation/loading. | +| `appName` | `string` | | The name of your application, shown to the user during sign-in. | +| `logoUrl` | `string` | | URL of your application's logo, shown to the user during sign-in. | + +Example with options: + +```typescript +import { signIn } from "@junobuild/core"; + +await signIn({ + nfid: { + options: { + maxTimeToLiveInNanoseconds: BigInt(24 * 60 * 60 * 1000 * 1000 * 1000), // 1 day + onProgress: ({ step, state }) => { + console.log("Step:", step, "State:", state); + }, + appName: "My Cool App", + logoUrl: "https://myapp.com/logo.png" + } + } +}); +``` + --- ## Sign-out diff --git a/docs/build/authentication/index.md b/docs/build/authentication/index.md index a1361648..c41b12cd 100644 --- a/docs/build/authentication/index.md +++ b/docs/build/authentication/index.md @@ -6,41 +6,62 @@ keywords: secure user identification, user identity, Internet Identity, - NFID + NFID, + Passkey, + WebAuthn ] --- # Authentication -Juno allows you to securely identify users **anonymously**. +Juno allows you to securely identify users anonymously, without passwords and without tracking. -Our easy-to-use SDKs support authentication through [Internet Identity] and [NFID]. +You can choose between [Passkeys](development.md#passkeys) for built-in authentication method, or integrate third-party providers like [Internet Identity](development.md#internet-identity) or [NFID](development.md#nfid). -Juno Authentication integrates tightly with other Juno services like [datastore](../datastore/index.mdx) and [storage](../storage/index.mdx). +Authentication works hand-in-hand with other Juno services like [Datastore](../datastore/index.mdx) and [Storage](../storage/index.mdx). -You can manage your users in the [authentication](https://console.juno.build/authentication) view in Juno's console. A new entry is created when a user successfully signs in. +You can see and manage your users anytime in the [authentication](https://console.juno.build/authentication) view of the Console. ![An overview of the anonymous display of the users in Juno Console](../../img/satellite/authentication.webp) --- -## Domain-Based User Identity +## User Identity -For privacy reasons and to prevent tracking across sites, Juno's authentication is tied to the domain your app uses. +When someone signs in to your app, they get an identity. -This means that if a user signs in on both the default domain (`icp0.io`) and a custom domain, they will be treated as two separate users by default. +That identity is what ties them to the data they create and the actions they take. -The same applies to subdomains: signing in on `hello.com` and `www.hello.com` will result in two separate user identities. +Identities are: -That's why, when setting up a domain in the Console, you're prompted to choose a **primary domain**. This domain is used to consistently identify users, regardless of whether they sign in via the default or a custom domain. +- **Anonymous**: they don't expose personal info. +- **Scoped**: they are unique to the domain (or subdomain) where the user signs in. -:::important +Together, this makes authentication privacy-friendly by default and predictable for developers. -- It is strongly recommended to set up such a primary domain only once per project and preferably before going live. +--- + +## Domain-Based Identity + +For privacy reasons and to prevent tracking across sites, a user's identity is tied to the domain where they sign in. + +### Passkeys + +With Passkeys, the identity is linked to the hostname the user signs in on. It works for that domain and its subdomains. + +For example, a passkey created on `hello.com` will also work on `www.hello.com`, but not on a different domain like `world.com`. + +You can change this in the sign-up options if you want it to cover a different domain than the one read from the browser's URL. For example, you may want to use the top-level domain when signing in on a subdomain. You cannot specify a totally different domain. + +### Internet Identity -- In addition to configuring settings, you must also instruct your application to use the main domain you have selected by setting the `derivationOrigin` parameter to the sign-in options. +With Internet Identity, a user's identity is created separately for each domain. -::: +If a user signs in on two different domains, they will be treated as two separate users by default. The same applies to subdomains: signing in on `hello.com` and `www.hello.com` creates two different identities unless you configure a primary domain. + +The first custom domain you add in the Console is automatically set as the primary domain. You can change this setting later in Authentication, but we don't recommend it once users have already registered, since their identities are not migrated when the configuration changes. + +To let users keep the same identity across domains, you must also configure your frontend app to specify the main domain at sign-in. This is known as the "derivation origin" (or "alternative origins"). ### Recommendation @@ -55,9 +76,33 @@ If you're unsure which domain to use as the primary domain, here are two common Choosing the right derivation origin early helps avoid identity issues later, but both approaches are valid depending on your goals. -### More Information +--- + +## Choosing a Provider + +Each authentication method has its strengths. The right choice depends not only on your app's technical needs, but also on what your users expect and feel comfortable with. + +- **Passkeys**: + - ✅ Best for mainstream users who expect a familiar, frictionless login with Face ID, Touch ID, or device unlock. + - ✅ Great when you want a Web2-like UX but with stronger security. + - 🤔 Users must explicitly choose between sign-up and sign-in, which can add friction if not guided. + - ❌ Without syncing to iCloud or Google Password Manager, a passkey stored only in the browser can be lost if the browser is reset or uninstalled. + - ❌ When using a manager, users must trust Apple/Google and other big tech for privacy preservation and safekeeping of their passkey. + +- **Internet Identity**: + - ✅ Best if you want users to authenticate with a fully decentralized and privacy-preserving identity. + - ✅ Provides strong guarantees against tracking between domains. + - 🤔 Requires context switching to an external window. + - ❌ Limited awareness among mainstream users beyond the Internet Computer community. + - ❌ Domain scoping can be confusing if misconfigured. + +- **NFID**: + - ✅ Good for users already onboarded with a NFID Wallet. + - ✅ Offers an alternative on the Internet Computer. + - 🤔 Requires context switching to an external window. + - ❌ Limited awareness among mainstream users beyond the Internet Computer community. + - ❌ Smaller user base compared to Passkeys or Internet Identity. -This mechanism is called the "derivation origin" (or "alternative origins"). See the [documentation](https://internetcomputer.org/docs/current/developer-docs/integrations/internet-identity/alternative-origins/) for more details about the specification. +In practice, we expect many developers will implement both Passkeys and Internet Identity side by side. This approach gives users the choice between a device-native login flow and an Internet Computer–native identity, covering a wider range of expectations. -[Internet Identity]: ../../terminology.md#internet-identity -[NFID]: ../../terminology.md#nfid +Ultimately, the choice should be guided by the audience you're targeting and how strongly you weigh the considerations outlined above.