feat: Passwordless cross-device authentication

- Arkitektur: docs/auth/passwordless-architecture.md
- Backend: iom/quixzoom-auth-service/ (FastAPI + Redis)
- Webb: quixzoom-market-pages/se/login/ (QR-kod + polling)
- App: iom/quixzoom-app/src/features/auth/ (push + deep links)

Flöde: QR-kod → app-godkännande → webb-inloggad
This commit is contained in:
Bernt
2026-07-07 07:11:50 +00:00
parent 4aa984ad74
commit 6989a98d75
61843 changed files with 5491611 additions and 872231 deletions
+144
View File
@@ -0,0 +1,144 @@
'use strict';
const fork = require('child_process').fork;
const path = require('path');
const _ = require('lodash');
const getPort = require('get-port');
const { killAsync } = require('./utils');
const CHILD_KILL_TIMEOUT = 30000;
const ChildPool = function ChildPool() {
if (!(this instanceof ChildPool)) {
return new ChildPool();
}
this.retained = {};
this.free = {};
};
const convertExecArgv = function(execArgv) {
const standard = [];
const promises = [];
_.forEach(execArgv, arg => {
if (arg.indexOf('--inspect') === -1) {
standard.push(arg);
} else {
const argName = arg.split('=')[0];
promises.push(
getPort().then(port => {
return `${argName}=${port}`;
})
);
}
});
return Promise.all(promises).then(convertedArgs => {
return standard.concat(convertedArgs);
});
};
ChildPool.prototype.retain = function(processFile) {
const _this = this;
let child = _this.getFree(processFile).pop();
if (child) {
_this.retained[child.pid] = child;
return Promise.resolve(child);
}
return convertExecArgv(process.execArgv).then(execArgv => {
child = fork(path.join(__dirname, './master.js'), {
execArgv
});
child.processFile = processFile;
_this.retained[child.pid] = child;
child.on('exit', _this.remove.bind(_this, child));
return initChild(child, child.processFile)
.then(() => {
return child;
})
.catch(err => {
this.remove(child);
throw err;
});
});
};
ChildPool.prototype.release = function(child) {
delete this.retained[child.pid];
this.getFree(child.processFile).push(child);
};
ChildPool.prototype.remove = function(child) {
delete this.retained[child.pid];
const free = this.getFree(child.processFile);
const childIndex = free.indexOf(child);
if (childIndex > -1) {
free.splice(childIndex, 1);
}
};
ChildPool.prototype.kill = function(child, signal) {
this.remove(child);
return killAsync(child, signal || 'SIGKILL', CHILD_KILL_TIMEOUT);
};
ChildPool.prototype.clean = function() {
const children = _.values(this.retained).concat(this.getAllFree());
this.retained = {};
this.free = {};
const allKillPromises = [];
children.forEach(child => {
allKillPromises.push(this.kill(child, 'SIGTERM'));
});
return Promise.all(allKillPromises).then(() => {});
};
ChildPool.prototype.getFree = function(id) {
return (this.free[id] = this.free[id] || []);
};
ChildPool.prototype.getAllFree = function() {
return _.flatten(_.values(this.free));
};
async function initChild(child, processFile) {
const onComplete = new Promise((resolve, reject) => {
const onMessageHandler = msg => {
if (msg.cmd === 'init-complete') {
resolve();
} else if (msg.cmd === 'error') {
reject(msg.error);
}
child.off('message', onMessageHandler);
};
child.on('message', onMessageHandler);
});
await new Promise(resolve =>
child.send({ cmd: 'init', value: processFile }, resolve)
);
await onComplete;
}
function ChildPoolSingleton(isSharedChildPool = false) {
if (isSharedChildPool === false) {
return new ChildPool();
} else if (
!(this instanceof ChildPool) &&
ChildPoolSingleton.instance === undefined
) {
ChildPoolSingleton.instance = new ChildPool();
}
return ChildPoolSingleton.instance;
}
module.exports = ChildPoolSingleton;
+200
View File
@@ -0,0 +1,200 @@
/**
* Master of child processes. Handles communication between the
* processor and the main process.
*
*/
'use strict';
let status;
let processor;
let currentJobPromise;
const { promisify } = require('util');
const { asyncSend } = require('./utils');
// https://stackoverflow.com/questions/18391212/is-it-not-possible-to-stringify-an-error-using-json-stringify
if (!('toJSON' in Error.prototype)) {
Object.defineProperty(Error.prototype, 'toJSON', {
value: function() {
const alt = {};
Object.getOwnPropertyNames(this).forEach(function(key) {
alt[key] = this[key];
}, this);
return alt;
},
configurable: true,
writable: true
});
}
async function waitForCurrentJobAndExit() {
status = 'TERMINATING';
try {
await currentJobPromise;
} finally {
// it's an exit handler
// eslint-disable-next-line no-process-exit
process.exit(process.exitCode || 0);
}
}
process.on('SIGTERM', waitForCurrentJobAndExit);
process.on('SIGINT', waitForCurrentJobAndExit);
process.on('message', msg => {
switch (msg.cmd) {
case 'init':
try {
processor = require(msg.value);
} catch (err) {
status = 'Errored';
err.message = `Error loading process file ${msg.value}. ${err.message}`;
return process.send({
cmd: 'error',
error: err
});
}
if (processor.default) {
// support es2015 module.
processor = processor.default;
}
if (processor.length > 1) {
processor = promisify(processor);
} else {
const origProcessor = processor;
processor = function() {
try {
return Promise.resolve(origProcessor.apply(null, arguments));
} catch (err) {
return Promise.reject(err);
}
};
}
status = 'IDLE';
process.send({
cmd: 'init-complete'
});
break;
case 'start':
if (status !== 'IDLE') {
return process.send({
cmd: 'error',
err: new Error('cannot start a not idling child process')
});
}
status = 'STARTED';
currentJobPromise = (async () => {
try {
const result = (await processor(wrapJob(msg.job))) || {};
await asyncSend(process, {
cmd: 'completed',
value: result
});
} catch (err) {
if (!err.message) {
// eslint-disable-next-line no-ex-assign
err = new Error(err);
}
await asyncSend(process, {
cmd: 'failed',
value: err
});
} finally {
status = 'IDLE';
currentJobPromise = null;
}
})();
break;
case 'stop':
break;
}
});
/*eslint no-process-exit: "off"*/
process.on('uncaughtException', err => {
if (!err.message) {
err = new Error(err);
}
process.send({
cmd: 'failed',
value: err
});
// An uncaughException leaves this process in a potentially undetermined state so
// we must exit
process.exit(-1);
});
/**
* Enhance the given job argument with some functions
* that can be called from the sandboxed job processor.
*
* Note, the `job` argument is a JSON deserialized message
* from the main node process to this forked child process,
* the functions on the original job object are not in tact.
* The wrapped job adds back some of those original functions.
*/
function wrapJob(job) {
/*
* Emulate the real job `progress` function.
* If no argument is given, it behaves as a sync getter.
* If an argument is given, it behaves as an async setter.
*/
let progressValue = job.progress;
job.progress = function(progress) {
if (progress) {
// Locally store reference to new progress value
// so that we can return it from this process synchronously.
progressValue = progress;
// Send message to update job progress.
return asyncSend(process, {
cmd: 'progress',
value: progress
});
} else {
// Return the last known progress value.
return progressValue;
}
};
/**
* Update job info
*/
job.update = function(data) {
process.send({
cmd: 'update',
value: data
});
};
/*
* Emulate the real job `log` function.
*/
job.log = function(row) {
return asyncSend(process, {
cmd: 'log',
value: row
});
};
/*
* Emulate the real job `update` function.
*/
job.update = function(data) {
process.send({
cmd: 'update',
value: data
});
job.data = data;
};
/*
* Emulate the real job `discard` function.
*/
job.discard = function() {
process.send({
cmd: 'discard'
});
};
return job;
}
+68
View File
@@ -0,0 +1,68 @@
'use strict';
const { asyncSend } = require('./utils');
module.exports = function(processFile, childPool) {
return function process(job) {
return childPool.retain(processFile).then(async child => {
let msgHandler;
let exitHandler;
await asyncSend(child, {
cmd: 'start',
job: job
});
const done = new Promise((resolve, reject) => {
msgHandler = function(msg) {
switch (msg.cmd) {
case 'completed':
resolve(msg.value);
break;
case 'failed':
case 'error': {
const err = new Error();
Object.assign(err, msg.value);
reject(err);
break;
}
case 'progress':
job.progress(msg.value);
break;
case 'update':
job.update(msg.value);
break;
case 'discard':
job.discard();
break;
case 'log':
job.log(msg.value);
break;
}
};
exitHandler = (exitCode, signal) => {
reject(
new Error(
'Unexpected exit code: ' + exitCode + ' signal: ' + signal
)
);
};
child.on('message', msgHandler);
child.on('exit', exitHandler);
});
return done.finally(() => {
child.removeListener('message', msgHandler);
child.removeListener('exit', exitHandler);
if (child.exitCode !== null || /SIG.*/.test(child.signalCode)) {
childPool.remove(child);
} else {
childPool.release(child);
}
});
});
};
};
+70
View File
@@ -0,0 +1,70 @@
'use strict';
function hasProcessExited(child) {
return !!(child.exitCode !== null || child.signalCode);
}
function onExitOnce(child) {
return new Promise(resolve => {
child.once('exit', () => resolve());
});
}
/**
* Sends a kill signal to a child resolving when the child has exited,
* resorting to SIGKILL if the given timeout is reached
*
* @param {ChildProcess} child
* @param {'SIGTERM' | 'SIGKILL'} [signal] initial signal to use
* @param {number} [timeoutMs] time to wait until sending SIGKILL
*
* @returns {Promise<void>} the killed child
*/
function killAsync(child, signal, timeoutMs) {
if (hasProcessExited(child)) {
return Promise.resolve(child);
}
// catch any new on exit
let onExit = onExitOnce(child);
child.kill(signal || 'SIGKILL');
if (timeoutMs === 0 || isFinite(timeoutMs)) {
const timeout = setTimeout(() => {
if (!hasProcessExited(child)) {
child.kill('SIGKILL');
}
}, timeoutMs);
onExit = onExit.then(() => {
clearTimeout(timeout);
});
}
return onExit;
}
/*
asyncSend
Same as process.send but waits until the send is complete
the async version is used below because otherwise
the termination handler may exit before the parent
process has recived the messages it requires
*/
const asyncSend = (proc, msg) => {
return new Promise((resolve, reject) => {
proc.send(msg, err => {
if (err) {
reject(err);
} else {
resolve();
}
});
});
};
module.exports = {
killAsync,
asyncSend
};