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
+731
View File
@@ -0,0 +1,731 @@
/* eslint no-console: 0 */
'use strict';
const urllib = require('./url');
const util = require('util');
const fs = require('fs');
const nmfetch = require('../fetch');
const errors = require('../errors');
const dns = require('dns');
const net = require('net');
const os = require('os');
const DNS_TTL = 5 * 60 * 1000;
const CACHE_CLEANUP_INTERVAL = 30 * 1000; // Minimum 30 seconds between cleanups
const MAX_CACHE_SIZE = 1000; // Maximum number of entries in cache
let lastCacheCleanup = 0;
module.exports._lastCacheCleanup = () => lastCacheCleanup;
module.exports._resetCacheCleanup = () => {
lastCacheCleanup = 0;
};
let networkInterfaces;
try {
networkInterfaces = os.networkInterfaces();
} catch (_err) {
// fails on some systems
}
module.exports.networkInterfaces = networkInterfaces;
const isFamilySupported = (family, allowInternal) => {
const ifaces = module.exports.networkInterfaces;
if (!ifaces) {
// hope for the best
return true;
}
return Object.keys(ifaces)
.map(key => ifaces[key])
.reduce((acc, val) => acc.concat(val), [])
.filter(i => !i.internal || allowInternal)
.some(i => i.family === 'IPv' + family || i.family === family);
};
const resolve = (family, hostname, options, callback) => {
options = options || {};
if (!isFamilySupported(family, options.allowInternalNetworkInterfaces)) {
return callback(null, []);
}
const dnsResolver = dns.Resolver ? new dns.Resolver(options) : dns;
dnsResolver['resolve' + family](hostname, (err, addresses) => {
if (err) {
switch (err.code) {
case dns.NODATA:
case dns.NOTFOUND:
case dns.NOTIMP:
case dns.SERVFAIL:
case dns.CONNREFUSED:
case dns.REFUSED:
case 'EAI_AGAIN':
return callback(null, []);
}
return callback(err);
}
return callback(null, Array.isArray(addresses) ? addresses : [].concat(addresses || []));
});
};
const dnsCache = (module.exports.dnsCache = new Map());
const formatDNSValue = (value, extra) => {
if (!value) {
return Object.assign({}, extra || {});
}
const addresses = value.addresses || [];
// Select a random address from available addresses, or null if none
const host = addresses.length > 0 ? addresses[Math.floor(Math.random() * addresses.length)] : null;
return Object.assign(
{
servername: value.servername,
host,
// Include all addresses for connection fallback support
_addresses: addresses
},
extra || {}
);
};
module.exports.resolveHostname = (options, callback) => {
options = options || {};
if (!options.host && options.servername) {
options.host = options.servername;
}
if (!options.host || net.isIP(options.host)) {
// nothing to do here
const value = {
addresses: [options.host],
servername: options.servername || false
};
return callback(
null,
formatDNSValue(value, {
cached: false
})
);
}
let cached;
if (dnsCache.has(options.host)) {
cached = dnsCache.get(options.host);
// Lazy cleanup with time throttling
const now = Date.now();
if (now - lastCacheCleanup > CACHE_CLEANUP_INTERVAL) {
lastCacheCleanup = now;
// Clean up expired entries
for (const [host, entry] of dnsCache.entries()) {
if (entry.expires && entry.expires < now) {
dnsCache.delete(host);
}
}
// If cache is still too large, remove oldest entries
if (dnsCache.size > MAX_CACHE_SIZE) {
const toDelete = Math.floor(MAX_CACHE_SIZE * 0.1); // Remove 10% of entries
const keys = Array.from(dnsCache.keys()).slice(0, toDelete);
keys.forEach(key => dnsCache.delete(key));
}
}
if (!cached.expires || cached.expires >= now) {
return callback(
null,
formatDNSValue(cached.value, {
cached: true
})
);
}
}
// Resolve both IPv4 and IPv6 addresses for fallback support
let ipv4Addresses = [];
let ipv6Addresses = [];
let ipv4Error = null;
let ipv6Error = null;
resolve(4, options.host, options, (err, addresses) => {
if (err) {
ipv4Error = err;
} else {
ipv4Addresses = addresses || [];
}
resolve(6, options.host, options, (err, addresses) => {
if (err) {
ipv6Error = err;
} else {
ipv6Addresses = addresses || [];
}
// Combine addresses: IPv4 first, then IPv6
const allAddresses = ipv4Addresses.concat(ipv6Addresses);
if (allAddresses.length) {
const value = {
addresses: allAddresses,
servername: options.servername || options.host
};
dnsCache.set(options.host, {
value,
expires: Date.now() + (options.dnsTtl || DNS_TTL)
});
return callback(
null,
formatDNSValue(value, {
cached: false
})
);
}
// No addresses from resolve4/resolve6, try dns.lookup as fallback
if (ipv4Error && ipv6Error) {
// Both resolvers had errors
if (cached) {
dnsCache.set(options.host, {
value: cached.value,
expires: Date.now() + (options.dnsTtl || DNS_TTL)
});
return callback(
null,
formatDNSValue(cached.value, {
cached: true,
error: ipv4Error
})
);
}
}
try {
dns.lookup(options.host, { all: true }, (err, addresses) => {
if (err) {
if (cached) {
dnsCache.set(options.host, {
value: cached.value,
expires: Date.now() + (options.dnsTtl || DNS_TTL)
});
return callback(
null,
formatDNSValue(cached.value, {
cached: true,
error: err
})
);
}
return callback(err);
}
// Get all supported addresses from dns.lookup
const supportedAddresses = addresses
? addresses.filter(addr => isFamilySupported(addr.family)).map(addr => addr.address)
: [];
if (addresses && addresses.length && !supportedAddresses.length) {
// there are addresses but none can be used
console.warn(`Failed to resolve IPv${addresses[0].family} addresses with current network`);
}
if (!supportedAddresses.length && cached) {
// nothing was found, fallback to cached value
return callback(
null,
formatDNSValue(cached.value, {
cached: true
})
);
}
const value = {
addresses: supportedAddresses.length ? supportedAddresses : [options.host],
servername: options.servername || options.host
};
dnsCache.set(options.host, {
value,
expires: Date.now() + (options.dnsTtl || DNS_TTL)
});
return callback(
null,
formatDNSValue(value, {
cached: false
})
);
});
} catch (lookupErr) {
if (cached) {
dnsCache.set(options.host, {
value: cached.value,
expires: Date.now() + (options.dnsTtl || DNS_TTL)
});
return callback(
null,
formatDNSValue(cached.value, {
cached: true,
error: lookupErr
})
);
}
return callback(ipv4Error || ipv6Error || lookupErr);
}
});
});
};
/**
* Parses connection url to a structured configuration object
*
* @param {String} str Connection url
* @return {Object} Configuration object
*/
module.exports.parseConnectionUrl = str => {
str = str || '';
const options = {};
const url = urllib.parse(str, true);
switch (url.protocol) {
case 'smtp:':
options.secure = false;
break;
case 'smtps:':
options.secure = true;
break;
case 'direct:':
options.direct = true;
break;
}
if (!isNaN(url.port) && Number(url.port)) {
options.port = Number(url.port);
}
if (url.hostname) {
options.host = url.hostname;
}
if (url.auth) {
const auth = url.auth.split(':');
options.auth = {
user: auth.shift(),
pass: auth.join(':')
};
}
Object.keys(url.query || {}).forEach(key => {
let obj = options;
let lKey = key;
let value = url.query[key];
if (!isNaN(value)) {
value = Number(value);
}
switch (value) {
case 'true':
value = true;
break;
case 'false':
value = false;
break;
}
// tls is nested object
if (key.indexOf('tls.') === 0) {
lKey = key.substr(4);
if (!options.tls) {
options.tls = {};
}
obj = options.tls;
} else if (key.indexOf('.') >= 0) {
// ignore nested properties besides tls
return;
}
if (!(lKey in obj)) {
obj[lKey] = value;
}
});
return options;
};
module.exports._logFunc = (logger, level, defaults, data, message, ...args) => {
const entry = Object.assign({}, defaults || {}, data || {});
delete entry.level;
let logLevel = level;
if (typeof logger[logLevel] !== 'function') {
// Provided logger does not implement this level. Fall back to a
// lower-severity handler instead of throwing.
logLevel = ['info', 'debug', 'log', 'trace', 'warn', 'error'].find(name => typeof logger[name] === 'function');
}
if (logLevel) {
logger[logLevel](entry, message, ...args);
}
};
/**
* Returns a bunyan-compatible logger interface. Uses either provided logger or
* creates a default console logger
*
* @param {Object} [options] Options object that might include 'logger' value
* @return {Object} bunyan compatible logger
*/
module.exports.getLogger = (options, defaults) => {
options = options || {};
const response = {};
const levels = ['trace', 'debug', 'info', 'warn', 'error', 'fatal'];
if (!options.logger) {
// use vanity logger
levels.forEach(level => {
response[level] = () => false;
});
return response;
}
const logger = options.logger === true ? createDefaultLogger(levels) : options.logger;
levels.forEach(level => {
response[level] = (data, message, ...args) => {
module.exports._logFunc(logger, level, defaults, data, message, ...args);
};
});
return response;
};
/**
* Wrapper for creating a callback that either resolves or rejects a promise
* based on input
*
* @param {Function} resolve Function to run if callback is called
* @param {Function} reject Function to run if callback ends with an error
*/
module.exports.callbackPromise = (resolve, reject) =>
function () {
const args = Array.from(arguments);
const err = args.shift();
if (err) {
reject(err);
} else {
resolve(...args);
}
};
module.exports.parseDataURI = uri => {
if (typeof uri !== 'string') {
return null;
}
// Early return for non-data URIs to avoid unnecessary processing
if (!uri.startsWith('data:')) {
return null;
}
// Find the first comma safely - this prevents ReDoS
const commaPos = uri.indexOf(',');
if (commaPos === -1) {
return null;
}
const data = uri.substring(commaPos + 1);
const metaStr = uri.substring('data:'.length, commaPos);
let encoding;
const metaEntries = metaStr.split(';');
if (metaEntries.length > 0) {
const lastEntry = metaEntries[metaEntries.length - 1].toLowerCase().trim();
// Only recognize valid encoding types to prevent manipulation
if (['base64', 'utf8', 'utf-8'].includes(lastEntry) && lastEntry.indexOf('=') === -1) {
encoding = lastEntry;
metaEntries.pop();
}
}
const contentType = metaEntries.length > 0 ? metaEntries.shift() : 'application/octet-stream';
const params = {};
for (let i = 0; i < metaEntries.length; i++) {
const entry = metaEntries[i];
const sepPos = entry.indexOf('=');
if (sepPos > 0) {
// Ensure there's a key before the '='
const key = entry.substring(0, sepPos).trim();
const value = entry.substring(sepPos + 1).trim();
if (key) {
params[key] = value;
}
}
}
// Decode data based on encoding with proper error handling
let bufferData;
try {
if (encoding === 'base64') {
bufferData = Buffer.from(data, 'base64');
} else {
try {
bufferData = Buffer.from(decodeURIComponent(data));
} catch (_decodeError) {
bufferData = Buffer.from(data);
}
}
} catch (_bufferError) {
bufferData = Buffer.alloc(0);
}
return {
data: bufferData,
encoding: encoding || null,
contentType: contentType || 'application/octet-stream',
params
};
};
/**
* Resolves a String or a Buffer value for content value. Useful if the value
* is a Stream or a file or an URL. If the value is a Stream, overwrites
* the stream object with the resolved value (you can't stream a value twice).
*
* This is useful when you want to create a plugin that needs a content value,
* for example the `html` or `text` value as a String or a Buffer but not as
* a file path or an URL.
*
* @param {Object} data An object or an Array you want to resolve an element for
* @param {String|Number} key Property name or an Array index
* @param {Object} [options] Optional access policy: { disableFileAccess, disableUrlAccess }
* @param {Function} callback Callback function with (err, value)
*/
module.exports.resolveContent = (data, key, options, callback) => {
// options is optional; support the legacy resolveContent(data, key, callback) signature
if (!callback && typeof options === 'function') {
callback = options;
options = false;
}
options = options || {};
let promise;
if (!callback) {
promise = new Promise((resolve, reject) => {
callback = module.exports.callbackPromise(resolve, reject);
});
}
resolveContentValue(data, key, options, callback);
return promise;
};
function resolveContentValue(data, key, options, callback) {
let content = (data && data[key] && data[key].content) || data[key];
const encoding = ((typeof data[key] === 'object' && data[key].encoding) || 'utf8')
.toString()
.toLowerCase()
.replace(/[-_\s]/g, '');
if (!content) {
return callback(null, content);
}
if (typeof content === 'object') {
if (typeof content.pipe === 'function') {
return resolveStream(content, (err, value) => {
if (err) {
return callback(err);
}
// we can't stream twice the same content, so we need
// to replace the stream object with the streaming result
if (data[key].content) {
data[key].content = value;
} else {
data[key] = value;
}
callback(null, value);
});
} else if (/^https?:\/\//i.test(content.path || content.href)) {
if (options.disableUrlAccess) {
return setImmediate(() => {
const err = new Error('Url access rejected for ' + (content.path || content.href));
err.code = errors.EURLACCESS;
callback(err);
});
}
return resolveStream(nmfetch(content.path || content.href, { headers: content.httpHeaders, tls: content.tls }), callback);
} else if (/^data:/i.test(content.path || content.href)) {
const parsedDataUri = module.exports.parseDataURI(content.path || content.href);
return callback(null, parsedDataUri && parsedDataUri.data ? parsedDataUri.data : Buffer.alloc(0));
} else if (content.path) {
if (options.disableFileAccess) {
return setImmediate(() => {
const err = new Error('File access rejected for ' + content.path);
err.code = errors.EFILEACCESS;
callback(err);
});
}
return resolveStream(fs.createReadStream(content.path), callback);
}
}
if (typeof data[key].content === 'string' && !['utf8', 'usascii', 'ascii'].includes(encoding)) {
content = Buffer.from(data[key].content, encoding);
}
// default action, return as is
setImmediate(() => callback(null, content));
}
/**
* Copies properties from source objects to target objects
*/
module.exports.assign = function (/* target, ... sources */) {
const args = Array.from(arguments);
const target = args.shift() || {};
args.forEach(source => {
Object.keys(source || {}).forEach(key => {
if (['tls', 'auth'].includes(key) && source[key] && typeof source[key] === 'object') {
// tls and auth are special keys that need to be enumerated separately
// other objects are passed as is
target[key] = Object.assign(target[key] || {}, source[key]);
} else {
target[key] = source[key];
}
});
});
return target;
};
module.exports.encodeXText = str => {
// ! 0x21
// + 0x2B
// = 0x3D
// ~ 0x7E
if (!/[^\x21-\x2A\x2C-\x3C\x3E-\x7E]/.test(str)) {
return str;
}
const buf = Buffer.from(str);
let result = '';
for (let i = 0, len = buf.length; i < len; i++) {
const c = buf[i];
if (c < 0x21 || c > 0x7e || c === 0x2b || c === 0x3d) {
result += '+' + (c < 0x10 ? '0' : '') + c.toString(16).toUpperCase();
} else {
result += String.fromCharCode(c);
}
}
return result;
};
/**
* Streams a stream value into a Buffer
*
* @param {Object} stream Readable stream
* @param {Function} callback Callback function with (err, value)
*/
function resolveStream(stream, callback) {
let responded = false;
const chunks = [];
let chunklen = 0;
stream.on('error', err => {
if (responded) {
return;
}
responded = true;
callback(err);
});
stream.on('readable', () => {
let chunk;
while ((chunk = stream.read()) !== null) {
chunks.push(chunk);
chunklen += chunk.length;
}
});
stream.on('end', () => {
if (responded) {
return;
}
responded = true;
let value;
try {
value = Buffer.concat(chunks, chunklen);
} catch (E) {
return callback(E);
}
callback(null, value);
});
}
/**
* Generates a bunyan-like logger that prints to console
*
* @returns {Object} Bunyan logger instance
*/
function createDefaultLogger(levels) {
const levelMaxLen = levels.reduce((max, level) => Math.max(max, level.length), 0);
const levelNames = new Map();
levels.forEach(level => {
let levelName = level.toUpperCase();
if (levelName.length < levelMaxLen) {
levelName += ' '.repeat(levelMaxLen - levelName.length);
}
levelNames.set(level, levelName);
});
const print = (level, entry, message, ...args) => {
let prefix = '';
if (entry) {
if (entry.tnx === 'server') {
prefix = 'S: ';
} else if (entry.tnx === 'client') {
prefix = 'C: ';
}
if (entry.sid) {
prefix = '[' + entry.sid + '] ' + prefix;
}
if (entry.cid) {
prefix = '[#' + entry.cid + '] ' + prefix;
}
}
message = util.format(message, ...args);
message.split(/\r?\n/).forEach(line => {
console.log('[%s] %s %s', new Date().toISOString().substr(0, 19).replace(/T/, ' '), levelNames.get(level), prefix + line);
});
};
const logger = {};
levels.forEach(level => {
logger[level] = print.bind(null, level);
});
return logger;
}
+151
View File
@@ -0,0 +1,151 @@
'use strict';
// URL parsing wrapper. Prefers the WHATWG `URL` (a global on Node 10+, and
// available as `require('url').URL` since Node 6.13+) and only falls back to the
// legacy, deprecation-warning-emitting `url.parse()` / `url.resolve()` on ancient
// Node versions that predate the WHATWG implementation.
//
// The WHATWG `URL` exposes a different shape than the legacy parser, so results
// are normalized back into the legacy field names the rest of the codebase reads
// (`protocol`, `hostname`, `port`, `pathname`, `path`, `search`, `auth`, `query`,
// `href`). This keeps every existing call site unchanged.
//
// Known, accepted divergences from the legacy parser:
// - non-special schemes (smtp:/smtps:/direct:) are not host-lowercased by
// WHATWG; cosmetic only, SMTP/DNS hosts are case-insensitive. (IDNA mapping
// and IPv6 brackets are normalized back by normalizeHostname below.)
// - a literal unescaped ':' inside a password is percent-encoded by WHATWG;
// such passwords should be percent-encoded by the caller anyway.
const urllib = require('url');
const punycode = require('../punycode');
// WHATWG URL constructor if available, otherwise undefined (Node < 6.13).
const URLImpl = (typeof URL !== 'undefined' && URL) || urllib.URL;
// Matches a "scheme:" not followed by "//" (and with something after it), used
// to re-insert the authority separator the legacy parser did not require.
const SLASHLESS_AUTHORITY = /^([a-zA-Z][a-zA-Z0-9+.-]*:)(?!\/\/)(.+)$/;
// decodeURIComponent that never throws. Legacy url.parse() decodes the auth
// component but tolerates malformed percent sequences, so mirror that.
function safeDecode(str) {
try {
return decodeURIComponent(str);
} catch (_err) {
return str;
}
}
// Derives the legacy-shaped bare hostname from a WHATWG URL. WHATWG keeps IPv6
// literals bracketed ('[::1]') and, for non-special schemes (smtp:/smtps:/socks:),
// percent-encodes a non-ASCII host instead of IDNA-mapping it. Both forms are
// un-resolvable when handed to net/dns/http.request — which is what every call
// site does — so map them back to what legacy url.parse() returned: the bare
// address and the punycode form. Idempotent on plain ASCII and already-punycode
// hosts, so special-scheme hosts (already IDNA-mapped by WHATWG) pass through.
function normalizeHostname(raw) {
let hostname = raw || '';
if (!hostname) {
// Host-less URL (e.g. 'direct:'): legacy returned '' here, not null;
// consumers do `hostname.length` / `'.' + hostname`, so keep it a string.
return '';
}
if (hostname.charAt(0) === '[' && hostname.charAt(hostname.length - 1) === ']') {
return hostname.slice(1, -1);
}
return punycode.toASCII(safeDecode(hostname));
}
module.exports.parse = (input, parseQueryString) => {
input = input || '';
if (!URLImpl) {
// Node < 6.13: no WHATWG URL available, use the legacy parser.
return urllib.parse(input, parseQueryString);
}
// Legacy url.parse() parses a "user:pass@host:port" authority that follows
// the scheme even without the "//" separator, for schemes outside its
// built-in slashed-protocol list (smtp:/smtps:/socks:/...). The WHATWG
// parser instead treats a scheme not followed by "//" as an opaque path.
// Re-insert the "//" so slash-less connection/proxy URLs keep resolving to
// an authority, as they did before. This assumes a slash-authority scheme,
// which every consumer here uses (http/https/smtp/smtps/socks/direct); an
// opaque scheme like mailto:/data:/tel: would be mis-split, but none reach
// this module.
const slashless = SLASHLESS_AUTHORITY.exec(input);
const normalized = slashless ? slashless[1] + '//' + slashless[2] : input;
let u;
try {
u = new URLImpl(normalized);
} catch (_err) {
// WHATWG rejects some input the legacy parser tolerated (empty/relative
// strings, scheme-relative '//host/path', out-of-range ports, ...). Fall
// back to the legacy parser so behavior — including the downstream errors
// callers rely on — is preserved. This is the only path that can still
// emit a deprecation warning; it fires for anything WHATWG cannot
// represent, including legitimate relative URLs, not just malformed input.
return urllib.parse(input, parseQueryString);
}
const hostname = normalizeHostname(u.hostname);
const port = u.port || null;
const pathname = u.pathname || null;
const search = u.search || null;
// Legacy `.auth` is the decoded "user[:pass]" string; WHATWG keeps the
// username/password percent-encoded, so decode to stay byte-compatible with
// existing consumers (parseConnectionUrl, Basic/Proxy-Authorization headers).
let auth = null;
if (u.username || u.password) {
// Gate on password too: legacy url.parse('smtps://:pass@host').auth was
// ':pass'. Dropping it would silently connect unauthenticated.
auth = safeDecode(u.username) + (u.password ? ':' + safeDecode(u.password) : '');
}
let query;
if (parseQueryString) {
// Mirror querystring.parse(): null-prototype object, repeated keys → array.
query = Object.create(null);
u.searchParams.forEach((value, key) => {
if (Object.prototype.hasOwnProperty.call(query, key)) {
if (Array.isArray(query[key])) {
query[key].push(value);
} else {
query[key] = [query[key], value];
}
} else {
query[key] = value;
}
});
} else {
query = search ? search.slice(1) : null;
}
return {
protocol: u.protocol || null,
host: u.host || null,
hostname,
port,
pathname,
search,
path: (pathname || '') + (search || '') || null,
href: u.href,
auth,
query
};
};
module.exports.resolve = (from, to) => {
if (!URLImpl) {
return urllib.resolve(from, to);
}
try {
return new URLImpl(to, from).href;
} catch (_err) {
// Malformed target — fall back to the legacy resolver.
return urllib.resolve(from, to);
}
};