Modular logistics and supply chain operating system (LSOS)
JavaScript driver-appfleet-managementfreight-managementinfrastructureinventory-managementlast-mile-deliverylogisticsondemandopen-sourceorder-managementroute-optimizationsupply-chain-managementtracking-and-monitoringtransport-management-systemtransportationwarehouse-management
feat(oauth): sign in with a provider from the console
Ronald A. Richardson2fb65594796c
diff --git a/console/app/controllers/auth/login.js b/console/app/controllers/auth/login.jsindex c8dce299..c9eefbea 100644--- a/console/app/controllers/auth/login.js+++ b/console/app/controllers/auth/login.js@@ -12,6 +12,7 @@ export default class AuthLoginController extends Controller {@service router;@service intl;@service fetch;+ @service oauth;/*** Whether or not to remember the users session@@ -150,6 +151,34 @@ export default class AuthLoginController extends Controller {}}+ /**+ * Begin an OAuth sign-in.+ *+ * Deliberately does not reuse login(): that unconditionally checks two-factor+ * status for a typed identity first, and here there is no identity to check —+ * the provider has not told us who this is yet. Two-factor is still enforced,+ * by the server, when the handshake comes back.+ *+ * @param {Object} provider+ * @return {void}+ */+ @action continueWithProvider(provider) {+ if (this.isLoading || !provider?.id) {+ return;+ }++ this.set('isLoading', true);++ // The server validates this path and echoes it back through the callback; it+ // never reaches the redirect host.+ const shift = this.urlSearchParams.get('shift');++ this.oauth.startAuthorization(provider.id, {+ intent: 'login',+ returnTo: shift && shift.startsWith('/') ? shift : null,+ });+ }+/*** Transition user to onboarding screen*/diff --git a/console/app/controllers/auth/oauth-callback.js b/console/app/controllers/auth/oauth-callback.jsnew file mode 100644index 00000000..00536e7c--- /dev/null+++ b/console/app/controllers/auth/oauth-callback.js@@ -0,0 +1,164 @@+import Controller from '@ember/controller';+import { inject as service } from '@ember/service';+import { tracked } from '@glimmer/tracking';+import { action } from '@ember/object';+import pathToRoute from '@fleetbase/ember-core/utils/path-to-route';++/**+ * Error codes the API can put in the callback fragment, or return from the exchange,+ * mapped to translation keys. Anything unrecognised falls back to a generic message —+ * the console never renders a raw server string here.+ */+const ERROR_KEYS = {+ access_denied: 'auth.login.oauth.errors.access-denied',+ provider_error: 'auth.login.oauth.errors.provider-error',+ provider_disabled: 'auth.login.oauth.errors.provider-disabled',+ invalid_state: 'auth.login.oauth.errors.invalid-state',+ missing_code: 'auth.login.oauth.errors.invalid-state',+ exchange_failed: 'auth.login.oauth.errors.exchange-failed',+ invalid_exchange_code: 'auth.login.oauth.errors.expired',+ hosted_domain_mismatch: 'auth.login.oauth.errors.hosted-domain',+ registration_disabled: 'auth.login.oauth.errors.registration-disabled',+ link_required: 'auth.login.oauth.errors.link-required',+ customer_login_not_allowed: 'auth.login.oauth.errors.customer-account',+ not_verified: 'auth.login.oauth.errors.not-verified',+ rate_limited: 'auth.login.oauth.errors.rate-limited',+};++export default class AuthOauthCallbackController extends Controller {+ @service session;+ @service router;+ @service fetch;+ @service intl;+ @service notifications;+ @service oauth;++ /**+ * Shown in place of the spinner when the handshake could not be completed.+ *+ * @var {String|null}+ */+ @tracked error = null;++ @tracked isExchanging = true;++ /**+ * Redeem the handoff code and route the user onward.+ *+ * @param {Object} payload+ * @return {Promise<void>}+ */+ async start(payload = {}) {+ const { handoff, error, returnTo } = payload;++ if (error) {+ return this.fail(error);+ }++ if (!handoff) {+ return this.fail('invalid_state');+ }++ let response;++ try {+ // rawError: without it the fetch service unwraps the body to+ // `new Error(errors[0])` and discards `code`, leaving nothing to map to+ // copy. The installation service reads server codes the same way.+ response = await this.fetch.post('auth/oauth/exchange', { code: handoff }, { rawError: true });+ } catch (serverError) {+ return this.fail(this.codeFrom(serverError));+ }++ return this.handle(response, returnTo);+ }++ /**+ * Route on one of the exchange's outcomes.+ *+ * @param {Object} response+ * @param {String|null} returnTo+ * @return {Promise<void>}+ */+ async handle(response = {}, returnTo = null) {+ // 2FA is not waived for a provider sign-in — the server issues no token until+ // the second factor is satisfied.+ if (response.isEnabled === true && response.twoFaSession) {+ this.isExchanging = false;+ return this.router.transitionTo('auth.two-fa', { queryParams: { token: response.twoFaSession } });+ }++ if (response.status === 'registration_required') {+ this.oauth.setRegistration({ intent: response.intent, prefill: response.prefill ?? {} });+ this.isExchanging = false;+ this.notifications.info(this.intl.t('auth.login.oauth.finish-signup'));++ return this.router.transitionTo('onboard');+ }++ if (response.token) {+ this.setRedirect(returnTo);++ // Establishes the session and, through the session service's+ // handleAuthentication(), performs the transition itself.+ return this.session.manuallyAuthenticate(response.token);+ }++ return this.fail('exchange_failed');+ }++ /**+ * Point the post-authentication transition at the originally requested page.+ *+ * The path was validated server side before it was ever echoed back, and is+ * converted to a route name the same way the password login path does it.+ *+ * @param {String|null} returnTo+ * @return {void}+ */+ setRedirect(returnTo) {+ if (!returnTo || typeof returnTo !== 'string' || !returnTo.startsWith('/')) {+ return;+ }++ const route = pathToRoute(returnTo);++ if (route) {+ this.session.setRedirect(route);+ }+ }++ /**+ * Render a message and send the user back to sign in.+ *+ * @param {String} code+ * @return {Promise<void>}+ */+ @action fail(code) {+ const key = ERROR_KEYS[code] ?? 'auth.login.oauth.errors.generic';++ this.error = this.intl.t(key);+ this.isExchanging = false;+ this.notifications.error(this.error);++ return this.router.transitionTo('auth.login');+ }++ /**+ * Pull the machine code out of an API error, ignoring any human-readable text.+ *+ * @param {Object|Error} error+ * @return {String}+ */+ codeFrom(error) {+ if (!error) {+ return 'exchange_failed';+ }++ // With rawError the rejection IS the parsed body, so `code` is at the top+ // level. The fallbacks cover a non-raw rejection slipping through.+ const code = error.code ?? error?.payload?.code ?? error?.json?.code;++ return typeof code === 'string' ? code : 'exchange_failed';+ }+}diff --git a/console/app/router.js b/console/app/router.jsindex 53ee0fc5..19113ecf 100644--- a/console/app/router.js+++ b/console/app/router.js@@ -1,3 +1,21 @@+/**+ * ███████╗██╗ ███████╗███████╗████████╗██████╗ █████╗ ███████╗███████╗+ * ██╔════╝██║ ██╔════╝██╔════╝╚══██╔══╝██╔══██╗██╔══██╗██╔════╝██╔════╝+ * █████╗ ██║ █████╗ █████╗ ██║ ██████╔╝███████║███████╗█████╗+ * ██╔══╝ ██║ ██╔══╝ ██╔══╝ ██║ ██╔══██╗██╔══██║╚════██║██╔══╝+ * ██║ ███████╗███████╗███████╗ ██║ ██████╔╝██║ ██║███████║███████╗+ * ╚═╝ ╚══════╝╚══════╝╚══════╝ ╚═╝ ╚═════╝ ╚═╝ ╚═╝╚══════╝╚══════╝+ *+ * AUTO-GENERATED FILE - DO NOT EDIT+ *+ * This file is automatically generated by the Fleetbase extension build system.+ * Any manual changes will be overwritten on the next build.+ *+ * @generated+ * @copyright © 2026 Fleetbase Pte Ltd. All rights reserved.+ * @license AGPL-3.0-or-later+ */+import EmberRouter from '@ember/routing/router';import config from '@fleetbase/console/config/environment';@@ -51,16 +69,74 @@ Router.map(function () {});this.route('branding');this.route('two-fa-settings');+ this.route('platform-api-token');this.route('virtual', { path: '/:slug' });this.route('organizations', function () {- this.route('index', { path: '/' }, function () {- this.route('users', { path: '/:public_id/users' });+ this.route('index', { path: '/' });+ this.route('details', { path: '/:public_id' }, function () {+ this.route('index', { path: '/' });+ this.route('users');+ this.route('extensions');+ this.route('activity');+ this.route('settings');+ this.route('extensions-tab', { path: '/extensions/:slug' });});});this.route('schedule-monitor', function () {this.route('logs', { path: '/:id/logs' });});});++ this.mount('@fleetbase/ai-engine', {+ as: 'ai',+ path: 'ai'+ });++ this.mount('@fleetbase/dev-engine', {+ as: 'developers',+ path: 'developers'+ });++ this.mount('@fleetbase/fleetops-engine', {+ as: 'fleet-ops',+ path: 'fleet-ops'+ });++ this.mount('@fleetbase/iam-engine', {+ as: 'iam',+ path: 'iam'+ });++ this.mount('@fleetbase/ledger-engine', {+ as: 'ledger',+ path: 'ledger'+ });++ this.mount('@fleetbase/registry-bridge-engine', {+ as: 'extensions',+ path: 'extensions'+ });++ this.mount('@fleetbase/storefront-engine', {+ as: 'storefront',+ path: 'storefront'+ });++ this.mount('@fleetbase/valhalla-engine', {+ as: 'valhalla',+ path: 'valhalla'+ });++ this.mount('@fleetbase/vroom-engine', {+ as: 'vroom',+ path: 'vroom'+ });});++ this.mount('@fleetbase/customer-portal-engine', {+ as: 'customer-portal',+ path: 'customer-portal'+ });+this.route('catch', { path: '/*' });});diff --git a/console/app/routes/auth/login.js b/console/app/routes/auth/login.jsindex a6a8dd88..f2776c9d 100644--- a/console/app/routes/auth/login.js+++ b/console/app/routes/auth/login.js@@ -8,6 +8,7 @@ export default class AuthLoginRoute extends Route {@service universe;@service installation;@service router;+ @service oauth;@action activate() {removeBootLoader();@@ -31,6 +32,13 @@ export default class AuthLoginRoute extends Route {}this.session.prohibitAuthentication('console');++ // Which providers to offer is a server-side decision an administrator makes at+ // runtime, so it cannot come from the build-time config. Not awaited as a+ // blocking step of sign-in: a failure here leaves the list empty and the form+ // renders email/password exactly as it did before OAuth existed.+ this.oauth.loadProviders();+return this.universe.virtualRouteRedirect(transition, 'auth:login', 'virtual', { restoreQueryParams: true });}}diff --git a/console/app/routes/auth/oauth-callback.js b/console/app/routes/auth/oauth-callback.jsnew file mode 100644index 00000000..d290f3d4--- /dev/null+++ b/console/app/routes/auth/oauth-callback.js@@ -0,0 +1,84 @@+import Route from '@ember/routing/route';+import { inject as service } from '@ember/service';+import window from 'ember-window-mock';+import removeBootLoader from '../../utils/remove-boot-loader';++/**+ * Where the API returns the browser after a provider handshake.+ *+ * The API puts the one-time handoff code in the URL FRAGMENT rather than the query+ * string, so it is never sent to the console's web server and cannot land in an+ * access log or a Referer header. This route reads it, clears it out of the address+ * bar before anything else happens, and hands it to the controller to redeem.+ */+export default class AuthOauthCallbackRoute extends Route {+ @service session;+ @service oauth;++ beforeModel() {+ removeBootLoader();++ // Do not prohibitAuthentication() here: an already-signed-in user landing on+ // this route should be let through to the controller, which redirects them+ // rather than erroring.+ }++ model() {+ return this.readFragment();+ }++ setupController(controller, model) {+ super.setupController(controller, model);++ // Not awaited: the template renders its spinner immediately and the+ // controller updates it when the exchange settles.+ controller.start(model);+ }++ /**+ * Read and immediately clear the fragment.+ *+ * Clearing it first means a reload, a bookmark or a shared URL cannot replay the+ * code — and the code is single-use server side regardless.+ *+ * @return {Object}+ */+ readFragment() {+ const hash = String(window.location.hash ?? '').replace(/^#/, '');+ const params = new URLSearchParams(hash);++ const payload = {+ handoff: params.get('handoff'),+ error: params.get('error'),+ returnTo: params.get('return_to'),+ };++ if (hash) {+ this.clearFragment();+ }++ return payload;+ }++ /**+ * @return {void}+ */+ clearFragment() {+ // replaceState is preferred: it drops the fragment without leaving a bare '#'+ // behind and without adding a history entry.+ try {+ const { pathname, search } = window.location;+ window.history.replaceState(null, '', `${pathname}${search}`);+ } catch (error) {+ // Can throw in some embedding contexts; the fallback below still runs.+ }++ // replaceState does not always take effect — notably it does not touch+ // ember-window-mock's mocked location. Assigning is the reliable floor, and in+ // a real browser the check above has already cleared the hash so this is a+ // no-op rather than a second history entry.+ if (String(window.location.hash ?? '').replace(/^#/, '') !== '') {+ window.location.hash = '';+ }+ }+}diff --git a/console/app/services/oauth.js b/console/app/services/oauth.jsnew file mode 100644index 00000000..0017ebd4--- /dev/null+++ b/console/app/services/oauth.js@@ -0,0 +1,143 @@+import Service from '@ember/service';+import { inject as service } from '@ember/service';+import { tracked } from '@glimmer/tracking';+import window from 'ember-window-mock';+import config from '@fleetbase/console/config/environment';++/**+ * Discovery and kickoff for OAuth sign-in.+ *+ * The server owns the whole handshake, so this service does almost nothing: it asks+ * the API which providers an administrator has enabled, and it navigates the browser+ * to the API's redirect endpoint. No provider SDK is ever loaded, and no client id or+ * secret is ever present in the console bundle.+ */+export default class OauthService extends Service {+ @service fetch;++ /**+ * Providers the API reports as enabled: [{ id, label, icon }].+ *+ * @var {Array}+ */+ @tracked providers = [];++ @tracked isLoading = false;++ /**+ * A registration intent handed back by the exchange when the provider identity+ * is not linked to any Fleetbase account.+ *+ * Deliberately in memory only. It is a bearer credential, and it is single-use+ * and short-lived, so persisting it would add real risk to buy very little —+ * a reload simply means running the provider handshake again.+ *+ * @var {Object|null}+ */+ @tracked registration = null;++ /**+ * Whether there is anything to render on the sign-in form.+ */+ get isEnabled() {+ return this.providers.length > 0;+ }++ /**+ * Ask the API which providers are enabled.+ *+ * Unauthenticated, and safe to call before a session exists — which is the point,+ * since it decides what the login form shows. Failure is never fatal: a console+ * that cannot reach this endpoint simply renders email/password sign-in, exactly+ * as it did before OAuth existed.+ *+ * @return {Promise<Array>}+ */+ async loadProviders() {+ if (this.isLoading) {+ return this.providers;+ }++ this.isLoading = true;++ try {+ const { providers } = await this.fetch.get('auth/oauth/providers');+ this.providers = Array.isArray(providers) ? providers : [];+ } catch (error) {+ this.providers = [];+ } finally {+ this.isLoading = false;+ }++ return this.providers;+ }++ /**+ * Begin the handshake by navigating to the API.+ *+ * A top-level navigation, not an XHR: the endpoint answers with a 302 to the+ * identity provider, and fetch() would follow that redirect cross-origin and fail+ * CORS rather than moving the browser.+ *+ * @param {String} providerId+ * @param {Object} options+ * @return {void}+ */+ startAuthorization(providerId, { intent = 'login', returnTo = null } = {}) {+ window.location.assign(this.authorizationUrl(providerId, { intent, returnTo }));+ }++ /**+ * The API URL that starts the handshake.+ *+ * @param {String} providerId+ * @param {Object} options+ * @return {String}+ */+ authorizationUrl(providerId, { intent = 'login', returnTo = null } = {}) {+ const base = [this.apiHost, config.API.namespace, `auth/oauth/${encodeURIComponent(providerId)}/redirect`].filter(Boolean).join('/');+ const params = new URLSearchParams({ intent });++ if (returnTo) {+ params.append('return_to', returnTo);+ }++ return `${base}?${params.toString()}`;+ }++ /**+ * The API origin.+ *+ * Mirrors the fallback in @fleetbase/ember-core's fetch service, which patches a+ * blank config.API.host at module load. Repeating it here rather than relying on+ * that side effect keeps this service independent of module load order.+ *+ * @return {String}+ */+ get apiHost() {+ const host = config.API.host;++ if (host) {+ return host;+ }++ return `${window.location.protocol}//${window.location.host}`;+ }++ /**+ * Remember a registration intent for the onboarding flow to pick up.+ *+ * @param {Object} registration+ * @return {void}+ */+ setRegistration(registration) {+ this.registration = registration ?? null;+ }++ /**+ * @return {void}+ */+ clearRegistration() {+ this.registration = null;+ }+}diff --git a/console/app/templates/auth/login.hbs b/console/app/templates/auth/login.hbsindex bbc3fe8e..741fcb7f 100644--- a/console/app/templates/auth/login.hbs+++ b/console/app/templates/auth/login.hbs@@ -91,6 +91,27 @@@onClick={{this.login}}/><Button @text={{t "auth.login.form.create-account-button"}} @icon="briefcase" @wrapperClass="btn-block" @disabled={{this.isLoading}} @onClick={{fn (transition-to "onboard")}} />++ {{!-- Provider buttons. Rendered only for providers the API reports as enabled,+ so an install with no OAuth configured sees the form exactly as before. --}}+ {{#if this.oauth.isEnabled}}+ <div class="flex items-center py-2">+ <div class="flex-grow border-t border-gray-300 dark:border-gray-700"></div>+ <span class="px-3 text-xs font-medium text-gray-500 uppercase dark:text-gray-400">{{t "auth.login.oauth.divider"}}</span>+ <div class="flex-grow border-t border-gray-300 dark:border-gray-700"></div>+ </div>++ {{#each this.oauth.providers as |provider|}}+ <Button+ @text={{t "auth.login.oauth.continue-with" provider=provider.label}}+ @icon={{provider.icon}}+ @iconPrefix="fab"+ @wrapperClass="btn-block"+ @disabled={{this.isLoading}}+ @onClick={{fn this.continueWithProvider provider}}+ />+ {{/each}}+ {{/if}}<RegistryYield @type="menu" @registry="auth:login" as |menuItem|><Button@text={{menuItem.title}}diff --git a/console/app/templates/auth/oauth-callback.hbs b/console/app/templates/auth/oauth-callback.hbsnew file mode 100644index 00000000..cb045b6a--- /dev/null+++ b/console/app/templates/auth/oauth-callback.hbs@@ -0,0 +1,8 @@+{{page-title (t "auth.login.oauth.signing-in")}}+<div class="flex flex-col items-center justify-center py-12 space-y-4">+ {{#if this.isExchanging}}+ <Spinner @loadingMessage={{t "auth.login.oauth.signing-in"}} @wrapperClass="flex flex-row items-center" @iconClass="mr-2" />+ {{else if this.error}}+ <InfoBlock @type="error" @icon="triangle-exclamation" @text={{this.error}} />+ {{/if}}+</div>diff --git a/console/tests/unit/controllers/auth/login-test.js b/console/tests/unit/controllers/auth/login-test.jsindex adbbd640..68c33559 100644--- a/console/tests/unit/controllers/auth/login-test.js+++ b/console/tests/unit/controllers/auth/login-test.js@@ -254,4 +254,56 @@ module('Unit | Controller | auth/login', function (hooks) {controller.reset('anything-else');assert.strictEqual(controller.password, 'b', 'an unknown outcome leaves the form alone');});++ test('continuing with a provider starts the server-side handshake', async function (assert) {+ const controller = this.owner.lookup('controller:auth/login');+ const started = [];++ controller.oauth.startAuthorization = (id, options) => started.push([id, options]);++ controller.continueWithProvider({ id: 'google', label: 'Google' });++ assert.deepEqual(started, [['google', { intent: 'login', returnTo: null }]]);+ // Unlike login(), no two-factor pre-check is issued: there is no identity to+ // check yet, and the server enforces 2FA when the handshake returns.+ assert.deepEqual(this.posted, []);+ assert.deepEqual(this.authenticateCalls, []);+ });++ test('it carries an intended destination into the handshake', async function (assert) {+ const controller = this.owner.lookup('controller:auth/login');+ const started = [];++ controller.oauth.startAuthorization = (id, options) => started.push([id, options]);+ controller.urlSearchParams.get = (key) => (key === 'shift' ? '/console/orders' : null);++ controller.continueWithProvider({ id: 'google' });++ assert.deepEqual(started, [['google', { intent: 'login', returnTo: '/console/orders' }]]);+ });++ test('it refuses to forward a destination that is not console-relative', async function (assert) {+ const controller = this.owner.lookup('controller:auth/login');+ const started = [];++ controller.oauth.startAuthorization = (id, options) => started.push([id, options]);+ controller.urlSearchParams.get = (key) => (key === 'shift' ? 'https://evil.tld/x' : null);++ controller.continueWithProvider({ id: 'google' });++ assert.deepEqual(started, [['google', { intent: 'login', returnTo: null }]]);+ });++ test('it ignores a provider click while a sign-in is already running', async function (assert) {+ const controller = this.owner.lookup('controller:auth/login');+ const started = [];++ controller.oauth.startAuthorization = (id, options) => started.push([id, options]);+ controller.set('isLoading', true);++ controller.continueWithProvider({ id: 'google' });+ controller.continueWithProvider({});++ assert.deepEqual(started, [], 'no handshake is started');+ });});diff --git a/console/tests/unit/controllers/auth/oauth-callback-test.js b/console/tests/unit/controllers/auth/oauth-callback-test.jsnew file mode 100644index 00000000..03e62dc8--- /dev/null+++ b/console/tests/unit/controllers/auth/oauth-callback-test.js@@ -0,0 +1,181 @@+import { module, test } from 'qunit';+import { setupTest } from '@fleetbase/console/tests/helpers';+import Service from '@ember/service';++module('Unit | Controller | auth/oauth-callback', function (hooks) {+ setupTest(hooks);++ hooks.beforeEach(function () {+ const self = this;+ this.posted = [];+ this.transitions = [];+ this.manualTokens = [];+ this.redirects = [];+ this.notified = { errors: [], info: [] };+ this.exchangeResult = () => Promise.resolve({ token: 'sanctum-token', type: 'user' });++ class FetchStub extends Service {+ post(path, body, options) {+ self.posted.push({ path, body, options });+ return self.exchangeResult();+ }+ }++ class SessionStub extends Service {+ manuallyAuthenticate(token) {+ self.manualTokens.push(token);+ }+ setRedirect(route) {+ self.redirects.push(route);+ }+ }++ class NotificationsStub extends Service {+ error(m) {+ self.notified.errors.push(m);+ }+ info(m) {+ self.notified.info.push(m);+ }+ }++ this.owner.register('service:fetch', FetchStub);+ this.owner.register('service:session', SessionStub);+ this.owner.register('service:notifications', NotificationsStub);++ this.controller = this.owner.lookup('controller:auth/oauth-callback');++ // Patch intl on the instance rather than registering a stub: ember-intl's own+ // initializer resolves service:intl during container boot, so an owner.register+ // here wins or loses depending on which other test files ran first. Asserting+ // on the key keeps these tests independent of the English copy.+ Object.defineProperty(this.controller.intl, 't', {+ configurable: true,+ value: (key) => key,+ });++ // The router service cannot be replaced with owner.register — Ember resolves+ // its own before a unit test gets the chance — so patch the instance, the+ // same way tests/unit/controllers/auth/login-test.js does.+ Object.defineProperty(this.controller.router, 'transitionTo', {+ configurable: true,+ value: (...args) => {+ self.transitions.push(args);+ return Promise.resolve();+ },+ });+ });++ test('it exchanges the handoff code and establishes the session', async function (assert) {+ const controller = this.controller;++ await controller.start({ handoff: 'handoff-code', returnTo: null });++ assert.deepEqual(this.posted, [{ path: 'auth/oauth/exchange', body: { code: 'handoff-code' }, options: { rawError: true } }]);+ assert.deepEqual(this.manualTokens, ['sanctum-token']);+ // The session service performs the transition itself from handleAuthentication().+ assert.deepEqual(this.transitions, []);+ });++ test('it points the post-login transition at the requested page', async function (assert) {+ const controller = this.controller;++ await controller.start({ handoff: 'handoff-code', returnTo: '/console/orders' });++ assert.strictEqual(this.redirects.length, 1, 'a redirect target was set');+ assert.deepEqual(this.manualTokens, ['sanctum-token']);+ });++ test('it ignores a return path that is not console-relative', async function (assert) {+ const controller = this.controller;++ // The server already rejects these, so reaching here means something is+ // wrong; the console refuses to act on it rather than trusting the echo.+ await controller.start({ handoff: 'handoff-code', returnTo: 'https://evil.tld/x' });++ assert.deepEqual(this.redirects, []);+ assert.deepEqual(this.manualTokens, ['sanctum-token']);+ });++ test('it sends a two factor challenge to the two-fa route without a session', async function (assert) {+ this.exchangeResult = () => Promise.resolve({ isEnabled: true, twoFaSession: 'two-fa-token' });+ const controller = this.controller;++ await controller.start({ handoff: 'handoff-code' });++ // Signing in through a provider does not waive the second factor.+ assert.deepEqual(this.transitions, [['auth.two-fa', { queryParams: { token: 'two-fa-token' } }]]);+ assert.deepEqual(this.manualTokens, [], 'no session is established yet');+ });++ test('it hands a registration intent to the onboarding flow', async function (assert) {+ this.exchangeResult = () =>+ Promise.resolve({+ status: 'registration_required',+ intent: 'rti_abc',+ prefill: { name: 'Ada', email: '[email protected]', email_verified: true },+ });+ const controller = this.controller;++ await controller.start({ handoff: 'handoff-code' });++ const oauth = this.owner.lookup('service:oauth');++ assert.strictEqual(oauth.registration.intent, 'rti_abc');+ assert.strictEqual(oauth.registration.prefill.email, '[email protected]');+ assert.deepEqual(this.transitions, [['onboard']]);+ assert.deepEqual(this.manualTokens, []);+ });++ test('it reports a provider failure carried in the fragment and returns to sign in', async function (assert) {+ const controller = this.controller;++ await controller.start({ error: 'access_denied' });++ assert.deepEqual(this.posted, [], 'no exchange is attempted');+ assert.deepEqual(this.notified.errors, ['auth.login.oauth.errors.access-denied']);+ assert.deepEqual(this.transitions, [['auth.login']]);+ });++ test('it treats a missing handoff code as an invalid state', async function (assert) {+ const controller = this.controller;++ await controller.start({});++ assert.deepEqual(this.posted, []);+ assert.deepEqual(this.notified.errors, ['auth.login.oauth.errors.invalid-state']);+ });++ test('it maps server error codes to copy and never renders a raw server string', async function (assert) {+ const cases = [+ ['invalid_exchange_code', 'auth.login.oauth.errors.expired'],+ ['link_required', 'auth.login.oauth.errors.link-required'],+ ['registration_disabled', 'auth.login.oauth.errors.registration-disabled'],+ ['not_verified', 'auth.login.oauth.errors.not-verified'],+ ['customer_login_not_allowed', 'auth.login.oauth.errors.customer-account'],+ ['rate_limited', 'auth.login.oauth.errors.rate-limited'],+ ['something_new_from_the_server', 'auth.login.oauth.errors.generic'],+ ];++ for (const [code, key] of cases) {+ this.notified.errors = [];+ this.exchangeResult = () => Promise.reject({ code, errors: ['raw server text that must not be shown'] });++ const controller = this.controller;+ await controller.start({ handoff: 'handoff-code' });++ assert.deepEqual(this.notified.errors, [key], `${code} maps to ${key}`);+ }+ });++ test('an exchange with no token and no known outcome fails closed', async function (assert) {+ this.exchangeResult = () => Promise.resolve({ unexpected: true });+ const controller = this.controller;++ await controller.start({ handoff: 'handoff-code' });++ assert.deepEqual(this.manualTokens, []);+ assert.deepEqual(this.notified.errors, ['auth.login.oauth.errors.exchange-failed']);+ assert.deepEqual(this.transitions, [['auth.login']]);+ });+});diff --git a/console/tests/unit/routes/auth/oauth-callback-test.js b/console/tests/unit/routes/auth/oauth-callback-test.jsnew file mode 100644index 00000000..2301ea41--- /dev/null+++ b/console/tests/unit/routes/auth/oauth-callback-test.js@@ -0,0 +1,48 @@+import { module, test } from 'qunit';+import { setupTest } from '@fleetbase/console/tests/helpers';+import window from 'ember-window-mock';++module('Unit | Route | auth/oauth-callback', function (hooks) {+ setupTest(hooks);++ test('it reads the handoff code out of the fragment', function (assert) {+ window.location.hash = '#handoff=abc123&return_to=%2Fdashboard';+ const route = this.owner.lookup('route:auth/oauth-callback');++ const payload = route.model();++ assert.strictEqual(payload.handoff, 'abc123');+ assert.strictEqual(payload.returnTo, '/dashboard');+ assert.strictEqual(payload.error, null);+ });++ test('it clears the fragment before the code is used', function (assert) {+ window.location.hash = '#handoff=abc123';+ const route = this.owner.lookup('route:auth/oauth-callback');++ route.model();++ // The code must not survive in the address bar, in history, or in anything+ // the user might copy and share.+ assert.notOk(String(window.location.hash).includes('abc123'), 'the code is gone from the url');+ });++ test('it reads an error carried in the fragment', function (assert) {+ window.location.hash = '#error=access_denied';+ const route = this.owner.lookup('route:auth/oauth-callback');++ const payload = route.model();++ assert.strictEqual(payload.error, 'access_denied');+ assert.strictEqual(payload.handoff, null);+ });++ test('an empty fragment yields nothing rather than throwing', function (assert) {+ window.location.hash = '';+ const route = this.owner.lookup('route:auth/oauth-callback');++ const payload = route.model();++ assert.deepEqual(payload, { handoff: null, error: null, returnTo: null });+ });+});diff --git a/console/tests/unit/services/oauth-test.js b/console/tests/unit/services/oauth-test.jsnew file mode 100644index 00000000..6d64e399--- /dev/null+++ b/console/tests/unit/services/oauth-test.js@@ -0,0 +1,101 @@+import { module, test } from 'qunit';+import { setupTest } from '@fleetbase/console/tests/helpers';+import Service from '@ember/service';+import window from 'ember-window-mock';+import config from '@fleetbase/console/config/environment';++module('Unit | Service | oauth', function (hooks) {+ setupTest(hooks);++ hooks.beforeEach(function () {+ const self = this;+ this.getCalls = [];+ this.getResult = () => Promise.resolve({ providers: [{ id: 'google', label: 'Google', icon: 'google' }] });++ class FetchStub extends Service {+ get(path) {+ self.getCalls.push(path);+ return self.getResult();+ }+ }++ this.owner.register('service:fetch', FetchStub);+ });++ test('it loads enabled providers from the api', async function (assert) {+ const service = this.owner.lookup('service:oauth');++ assert.false(service.isEnabled, 'nothing is offered before the list loads');++ const providers = await service.loadProviders();++ assert.deepEqual(this.getCalls, ['auth/oauth/providers']);+ assert.deepEqual(providers, [{ id: 'google', label: 'Google', icon: 'google' }]);+ assert.true(service.isEnabled);+ });++ test('an unreachable endpoint leaves sign-in working without oauth', async function (assert) {+ this.getResult = () => Promise.reject(new Error('network down'));+ const service = this.owner.lookup('service:oauth');++ await service.loadProviders();++ // A console that cannot reach the endpoint must still render the+ // email/password form rather than erroring out of beforeModel.+ assert.deepEqual(service.providers, []);+ assert.false(service.isEnabled);+ });++ test('a malformed payload is treated as no providers', async function (assert) {+ this.getResult = () => Promise.resolve({ providers: 'not-an-array' });+ const service = this.owner.lookup('service:oauth');++ await service.loadProviders();++ assert.deepEqual(service.providers, []);+ });++ test('it builds the authorization url against the api host', function (assert) {+ const service = this.owner.lookup('service:oauth');+ const url = new URL(service.authorizationUrl('google', { intent: 'login' }));++ assert.strictEqual(url.origin, new URL(service.apiHost).origin);+ assert.true(url.pathname.endsWith(`${config.API.namespace}/auth/oauth/google/redirect`));+ assert.strictEqual(url.searchParams.get('intent'), 'login');+ assert.strictEqual(url.searchParams.get('return_to'), null, 'omitted when not supplied');+ });++ test('it passes a return path through and escapes the provider id', function (assert) {+ const service = this.owner.lookup('service:oauth');++ const withReturn = new URL(service.authorizationUrl('google', { intent: 'signup', returnTo: '/orders?status=open' }));+ assert.strictEqual(withReturn.searchParams.get('return_to'), '/orders?status=open');+ assert.strictEqual(withReturn.searchParams.get('intent'), 'signup');++ assert.true(service.authorizationUrl('../evil').includes('..%2Fevil'), 'provider id is encoded, not interpolated raw');+ });++ test('starting authorization navigates rather than fetching', function (assert) {+ const service = this.owner.lookup('service:oauth');++ service.startAuthorization('google', { intent: 'login', returnTo: '/dashboard' });++ // Must be a top-level navigation: the endpoint answers 302 to the provider,+ // and an XHR would follow that cross-origin and fail CORS instead.+ assert.true(String(window.location.href).includes('auth/oauth/google/redirect'));+ assert.deepEqual(this.getCalls, [], 'no XHR is issued');+ });++ test('it holds a registration intent in memory only', function (assert) {+ const service = this.owner.lookup('service:oauth');++ service.setRegistration({ intent: 'rti_abc', prefill: { email: '[email protected]' } });+ assert.strictEqual(service.registration.intent, 'rti_abc');++ // The intent is a bearer credential; it must not outlive the tab.+ assert.strictEqual(window.localStorage.getItem('oauth:registration'), null);++ service.clearRegistration();+ assert.strictEqual(service.registration, null);+ });+});