13 Commits

Author SHA1 Message Date
3bc2546439 feat: v1.4 version release 2025-08-08 17:50:19 +03:00
e43cf044e0 Merge pull request 'v1.4 rel' (#10) from dev into main
Reviewed-on: http://git.lisoveliy.su/Lisoveliy/TOTPFit/pulls/10
2025-08-08 16:43:06 +02:00
08894ee061 chore: prettier cleanup 2025-08-08 17:42:47 +03:00
1e69a70ea0 feat: added beta support of square devices 2025-08-08 17:36:16 +03:00
86f382bef9 feat: updated icons, updated docs 2025-08-08 17:25:51 +03:00
eaf6aefd5b refactor, feat: added proton auth support, added instruction for proton, added errors, some refactor and cleanup 2025-08-08 17:21:54 +03:00
52d053e024 fix: disabled deletion while edit in progress 2025-08-08 16:03:46 +03:00
f8fa7a8507 Merge pull request 'Added pull request from GitHub https://github.com/Lisoveliy/totpfit/pull/1, fix of settings app' (#11) from from-mirror into main
Reviewed-on: http://git.lisoveliy.su/Lisoveliy/TOTPFit/pulls/11
2025-08-08 14:39:41 +02:00
259c2cdd2e feat: added sort for totps, added possibility to change issuer and client name 2025-08-08 15:34:34 +03:00
d45be3ee68 fix: provided hashType into getOTP 2025-08-07 16:56:07 +03:00
56d5edc37b fix, chore, feat: refactor of settings app, fix of Google Auth migration parse, added rename button(testing), added sort feature, added timeout to screen turning off, formated codes with space between 6-digits codes
Co-authored-by: DemiarUA <demiar97@gmail.com>
https://github.com/Lisoveliy/totpfit/pull/1
2025-08-07 16:53:54 +03:00
ea75f03fbe Merge branch 'main' of https://git.lisoveliy.su/lisoveliy/totpfit 2025-07-26 14:30:03 +03:00
7c33fcffc8 feat: updated icon 2025-07-26 14:30:01 +03:00
26 changed files with 599 additions and 250 deletions

View File

@@ -1,17 +1,22 @@
# TOTPFIT
### Another 2FAuthenticator based on TOTP for Zepp Amazfit GTS 4 with Google Authenticator migration support
### Another 2FAuthenticator based on TOTP for Zepp OS with Google Authenticator and Proton Authenticator support
![alt text](docs/assets/image2.png)
![alt text](docs/assets/image2.png)![alt text](docs/assets/image.jpg)
### Features:
- Supports of `otpauth://` links with parameters "client", "issuer", "algorithm", "digits", "period", "offset"
- Addition/Edition/Deletion of TOTPs from mobile app
- Support of Google Authenticator migration links formated: `otpauth-migration://offline?data=...` (At this stage with only 6 digits and only 30 seconds period)
- Support of `otpauth://` links with parameters "client", "issuer", "algorithm", "digits", "period", "offset"
- Support of Google Authenticator migration links formated: `otpauth-migration://offline?data=...`
- Support of **Proton Authenticator** export with parameters "client", "issuer", "algorithm", "digits", "period", "offset" **(BETA)**
- Addition/Sort/Edition/Deletion of TOTPs from mobile app
### Guides:
[How to add 2FA TOTP records (keys) on app](/docs/guides/how-to-add-totps/README.md)
#### This repo has mirror for issues on [GitHub](https://github.com/Lisoveliy/totpfit)
#### This repo has mirror for public issues on [GitHub](https://github.com/Lisoveliy/totpfit)
#### To contribute on this repo you must use my [Gitea](https://git.lisoveliy.su/Lisoveliy/totpfit)
Don't be shy to contact me for access!

View File

@@ -6,11 +6,11 @@
"appType": "app",
"version": {
"code": 1,
"name": "1.3.0"
"name": "1.4.0"
},
"icon": "icon.png",
"vender": "zepp",
"description": "Another 2FAuthenticator based on TOTP for Zepp Amazfit GTS 4"
"description": "Another 2FAuthenticator based on TOTP for Zepp OS"
},
"permissions": ["data:os.device.info", "device:os.local_storage"],
"runtime": {
@@ -37,6 +37,11 @@
{
"st": "s",
"dw": 390
},
{
"st": "r",
"dw": 390
}
]
}

Binary file not shown.

Before

Width:  |  Height:  |  Size: 76 KiB

After

Width:  |  Height:  |  Size: 21 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 76 KiB

After

Width:  |  Height:  |  Size: 21 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 76 KiB

After

Width:  |  Height:  |  Size: 21 KiB

BIN
docs/assets/image.jpg Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 115 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 27 KiB

View File

@@ -14,11 +14,9 @@ Then press OK, record will appear on page
![Added record](image-4.png)
You can edit your otpauth:// records using button "Change TOTP link". Your previous record will be replaced with a new otpauth:// link from text field, and previous link will not be shown on field.
### If you use google migrations (otpauth-migration:// links)
To add 2FA TOTP recods using migration from Google Authenticator app, you must go to menu, select "Transfer accounts" -> "Export accounts"
To add 2FA TOTP records using migration from Google Authenticator app, you must go to menu, select "Transfer accounts" -> "Export accounts"
Select codes then screenshot QR code and scan (decode) it to a URI. Use any app providing scan from image, ex: "Search screen" function (Google Lens) on Google Assistant.
@@ -34,4 +32,23 @@ Then press OK, all selected records from Google Authenticator will appear on pag
![Added records from otpauth-migration](image-7.png)
You can edit your records using button "Change TOTP link". Your previous record will be replaced with a new otpauth:// link from text field (otpauth-migration:// will not work), and previous link will not be shown on field.
### If you use Proton Authenticator
To add 2FA TOTP records from Proton Authenticator you must go to settings and press "Export":
![alt text](photo_2025-08-08_17-10-27.jpg)
After this save file and open it on text editor:
![alt text](photo_2025-08-08_17-10-35.jpg)
![alt text](photo_2025-08-08_17-10-41.jpg)
Copy all stuff from file at clipboard and import in application:
![alt text](photo_2025-08-08_17-10-38.jpg)
![alt text](<Снимок экрана_20250808_170854.png>)
Then press OK, records will appear on page:
![alt text](<Снимок экрана_20250808_170912.png>)

Binary file not shown.

After

Width:  |  Height:  |  Size: 34 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 20 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 19 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 16 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 41 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 37 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 74 KiB

After

Width:  |  Height:  |  Size: 21 KiB

View File

@@ -107,7 +107,7 @@ export function decodeProto(buffer) {
}
} catch (err) {
reader.resetToCheckpoint();
console.log(`ERR: ${err}`);
console.log(err);
}
return {

View File

@@ -13,25 +13,21 @@ export function getHOTP(counter, secret, digits = 6, hashType = "SHA-1") {
//Stage 1: Prepare data
const rawDataCounter = new DataView(new ArrayBuffer(8));
rawDataCounter.setUint32(4, counter);
const bCounter = new Uint8Array(rawDataCounter.buffer);
const bSecret = new Uint8Array(
decode(secret)
.match(/.{1,2}/g)
.map((chunk) => parseInt(chunk, 16)),
); //confirmed
//Stage 2: Hash data
const jssha = new jsSHA(hashType, "UINT8ARRAY");
jssha.setHMACKey(bSecret, "UINT8ARRAY");
jssha.update(bCounter);
const hmacResult = jssha.getHMAC("UINT8ARRAY"); //confirmed
//Stage 3: Dynamic truncate
const offsetB = hmacResult[19] & 0xf;
const P = hmacResult.slice(offsetB, offsetB + 4);
P[0] = P[0] & 0x7f;
//Stage 4: Format string
let res = (
new DataView(P.buffer).getInt32(0) % Math.pow(10, digits)

View File

@@ -48,7 +48,12 @@ export class TOTP {
*/
getOTP(time = Date.now()) {
const unixTime = (time / 1000 + this.timeOffset) / this.fetchTime;
const otp = getHOTP(Math.floor(unixTime), this.secret, this.digits, this.hashType);
const otp = getHOTP(
Math.floor(unixTime),
this.secret,
this.digits,
this.hashType,
);
const expireTime =
time +
(this.fetchTime -

View File

@@ -1,12 +1,13 @@
{
"name": "totpfit",
"version": "1.3.0",
"description": "Another 2FAuthenticator based on TOTP for Zepp Amazfit GTS 4",
"version": "1.4.0",
"description": "Another 2FAuthenticator based on TOTP for Zepp OS with Google Authenticator and Proton Authenticator support",
"main": "app.js",
"author": "Lisoveliy",
"license": "MIT",
"devDependencies": {
"@zeppos/device-types": "^3.0.0"
"@zeppos/device-types": "^3.0.0",
"prettier": "3.6.2"
},
"dependencies": {
"@zeppos/zml": "^0.0.27",

View File

@@ -2,14 +2,18 @@ import { RenderAddButton } from "./render/totpRenderer";
import { initLoop } from "./render/index/renderer";
import { BasePage } from "@zeppos/zml/base-page";
import { LocalStorage } from "@zos/storage";
import { setPageBrightTime } from "@zos/display";
const app = getApp();
const brightTimeMs = 300000;
let waitForFetch = true;
Page(
BasePage({
onInit() {
setPageBrightTime({ brightTime: brightTimeMs });
this.getTOTPData()
.then((x) => {
app._options.globalData.TOTPS = JSON.parse(x) ?? [];
@@ -22,7 +26,7 @@ Page(
this.initPage();
})
.catch((x) => {
console.log(`ERR: Init failed - ${x}`);
console.log(`Init failed: ${x}`);
try {
let localStorage = new LocalStorage();
app._options.globalData.TOTPS = JSON.parse(

View File

@@ -22,11 +22,12 @@ function renderContainers(buffer) {
}
const renderData = [];
function renderTOTPs(buffer) {
for (let i = 0; i < buffer.length; i++) {
let otpData = TOTP.copy(buffer[i]).getOTP();
renderData[i] = {
OTP: RenderOTPValue(i, otpData.otp),
OTP: RenderOTPValue(i, formatOTP(otpData.otp)),
expireBar: RenderExpireBar(
i,
otpData.createdTime,
@@ -49,9 +50,15 @@ function renderTOTPs(buffer) {
if (otpData.expireTime < Date.now()) {
otpData = TOTP.copy(buffer[i]).getOTP();
renderData[i].OTP.setProperty(prop.MORE, {
text: otpData.otp,
text: formatOTP(otpData.otp),
});
}
}, 50);
}
}
function formatOTP(otp) {
if (otp.length === 6) return `${otp.substring(0, 3)} ${otp.substring(3)}`;
return otp;
}

View File

@@ -9,26 +9,42 @@ export const colors = {
};
export const content = {
addTotpsHint: "For add a 2FA TOTP record you must have otpauth:// link or otpauth-migration:// link from Google Authenticator Migration QR-Code",
addTotpsHint:
"For add a 2FA TOTP record you must have otpauth:// link otpauth-migration://" +
"link from Google Authenticator Migration QR-Code or Proton authenticator Export JSON string." +
"If you have a questions - check instruction below!",
totpRecordsHint: "TOTP records:",
createButton: {
placeHolder: "otpauth(-migration)://",
label: "Add new TOTP record"
label: "Add new TOTP record",
},
instructionLink: {
label: "Instruction | Report issue (GitHub)",
source: "https://github.com/Lisoveliy/totpfit/blob/main/docs/guides/how-to-add-totps/README.md"
source: "https://github.com/Lisoveliy/totpfit/blob/main/docs/guides/how-to-add-totps/README.md",
},
changeButton: {
label: "Change TOTP link",
placeHolder: "otpauth(-migration)://"
placeHolder: "otpauth(-migration)://",
},
renameButtons: {
rename: "Rename",
renameIssuer: "Rename Issuer",
renameClient: "Rename Client",
},
saveButton: {
label: "Save",
},
deleteButton: {
label: "Delete"
label: "Delete",
},
totpLabelText: {
eval(issuer, client) {return `${issuer}: ${client}`;}
eval(issuer, client) {
return `${issuer}: ${client}`;
},
},
totpDescText: {
eval(hashType, digits, fetchTime, timeOffset) { return `${hashType} | ${digits} digits | ${fetchTime} seconds | ${timeOffset} sec offset`; }
}
eval(hashType, digits, fetchTime, timeOffset) {
return `${hashType} | ${digits} digits | ${fetchTime} seconds | ${timeOffset} sec offset`;
},
},
};

View File

@@ -1,7 +1,70 @@
import { getTOTPByLink } from "./utils/queryParser.js";
import { createTOTPCard } from "./ui/card.js";
import { colors, content } from "./consts.js";
let _props = null;
let editingIndex = -1;
let tempIssuer = "";
let tempClient = "";
let errorMessage = "";
function updateStorage(storage) {
_props.settingsStorage.setItem("TOTPs", JSON.stringify(storage));
}
function GetTOTPList(storage) {
return storage.map((element, index) => {
return createTOTPCard({
element,
index,
storage,
isEditing: editingIndex === index,
tempIssuer,
tempClient,
onIssuerChange: (val) => {
tempIssuer = val;
},
onClientChange: (val) => {
tempClient = val;
},
onRename: () => {
editingIndex = index;
tempIssuer = element.issuer;
tempClient = element.client;
_props.settingsStorage.setItem("requestUpdate", Math.random());
},
onSave: () => {
storage[index].issuer = tempIssuer;
storage[index].client = tempClient;
editingIndex = -1;
updateStorage(storage);
},
onDelete: () => {
storage.splice(index, 1);
updateStorage(storage);
},
onMoveUp: () => {
if (index > 0) {
[storage[index], storage[index - 1]] = [
storage[index - 1],
storage[index],
];
updateStorage(storage);
}
},
onMoveDown: () => {
if (index < storage.length - 1) {
[storage[index], storage[index + 1]] = [
storage[index + 1],
storage[index],
];
updateStorage(storage);
}
},
isEditInProgress: editingIndex !== -1,
});
});
}
AppSettingsPage({
build(props) {
@@ -27,75 +90,67 @@ AppSettingsPage({
content.addTotpsHint,
)
: null;
const createButton = TextInput({
placeholder: content.createButton.placeHolder,
label: content.createButton.label,
onChange: (changes) => {
try {
errorMessage = "";
let link = getTOTPByLink(changes);
if (link == null) {
console.log("ERR: link is invalid");
return;
if (Array.isArray(link)) {
storage.push(...link);
} else {
storage.push(link);
}
if (Array.isArray(link)) storage.push(...link);
else storage.push(link);
updateStorage(storage);
} catch (e) {
errorMessage = e.message;
updateStorage(storage);
}
},
labelStyle: {
backgroundColor: colors.notify,
display: "flex",
alignItems: "center",
justifyContent: "center",
margin: "10px",
marginBottom: "10px",
marginLeft: "10px",
marginRight: "10px",
fontSize: "20px",
color: colors.text,
borderRadius: "5px",
position: storage.length < 1 ? "absolute" : null, //TODO: Сделать что-то с этим кошмаром
bottom: storage.length < 1 ? "0px" : null,
left: storage.length < 1 ? "0px" : null,
right: storage.length < 1 ? "0px" : null,
height: "45px",
},
});
var body = Section(
const errorText = errorMessage
? Text(
{
style: {
color: colors.alert,
textAlign: "center",
},
},
errorMessage,
)
: null;
const bottomContainer = View(
{
style: {
backgroundColor: colors.bg,
minHeight: "100vh",
},
},
[
View(
{
style: {
textAlign: "center",
},
},
storage.length < 1
? addTOTPsHint
: Text(
{
align: "center",
paragraph: true,
style: {
marginBottom: "10px",
color: colors.bigText,
fontSize: 23,
fontWeight: "500",
verticalAlign: "middle",
},
},
"TOTP records:",
),
),
...totpEntrys,
createButton,
View(
{
style: {
display: "flex",
justifyContent: "center",
marginTop: "10px",
marginBottom: "10px",
},
},
Link(
@@ -105,121 +160,65 @@ AppSettingsPage({
content.instructionLink.label,
),
),
],
errorText,
createButton,
].filter(Boolean),
);
return body;
},
});
/**
* Get DOM elements of TOTP records
* @param {*} storage Array of TOTP objects
* @returns Array of DOM elements
*/
function GetTOTPList(storage) {
let totpEntrys = [];
let counter = 0;
storage.forEach((element) => {
const elementId = counter;
const totpLabelText = Text(
const pageContainer = View(
{
align: "center",
style: {
color: colors.text,
fontSize: "18px",
fontWeight: "500",
},
paragraph: true,
},
content.totpLabelText.eval(element.issuer, element.client),
);
const changeButton = TextInput({
placeholder: content.changeButton.placeHolder,
label: content.changeButton.label,
onChange: (changes) => {
try {
let link = getTOTPByLink(changes);
if (Array.isArray(link)) return;
storage[elementId] = link;
updateStorage(storage);
} catch (err) {
console.log(`ERR: ${err}`);
}
},
labelStyle: {
backgroundColor: colors.notify,
textAlign: "center",
backgroundColor: colors.bg,
height: "100vh",
display: "flex",
alignItems: "center",
justifyContent: "center",
margin: "10px",
flexGrow: 1,
fontSize: "20px",
color: colors.text,
borderRadius: "5px",
},
});
const totpDescText = Text(
{
style: {
color: colors.text,
fontSize: "14px",
},
align: "center",
},
content.totpDescText.eval(element.hashType, element.digits, element.fetchTime, element.timeOffset),
);
const deleteButton = Button({
onClick: () => {
storage = storage.filter(
(x) => storage.indexOf(x) != elementId,
);
updateStorage(storage);
},
style: {
backgroundColor: colors.alert,
fontSize: "18px",
color: colors.text,
height: "fit-content",
margin: "10px",
},
label: content.deleteButton.label,
});
const view = View(
{
style: {
textAlign: "center",
backgroundColor: colors.secondaryBg,
borderRadius: "5px",
margin: "10px",
flexDirection: "column",
justifyContent: "space-between",
},
},
[
totpLabelText,
totpDescText,
View(
{
style: {
display: "grid",
gridTemplateColumns: "1fr 100px",
textAlign: "center",
},
},
[changeButton, deleteButton],
[
storage.length < 1
? addTOTPsHint
: Text(
{
align: "center",
paragraph: true,
style: {
marginTop: "10px",
marginBottom: "10px",
color: colors.bigText,
fontSize: 23,
fontWeight: "500",
verticalAlign: "middle",
},
},
content.totpRecordsHint,
),
],
),
View(
{
style: {
height: "100%",
overflowX: "hidden",
overflowY: "auto",
backgroundColor: colors.bg,
},
},
[...totpEntrys],
),
bottomContainer,
],
);
totpEntrys.push({ text: totpDescText, view: view });
counter++;
return pageContainer;
},
});
return totpEntrys.map((x) => x.view);
}
/**
* Update
* @param {*} storage Array of TOTP objects
*/
function updateStorage(storage) {
_props.settingsStorage.setItem("TOTPs", JSON.stringify(storage));
}

187
setting/ui/card.js Normal file
View File

@@ -0,0 +1,187 @@
import { colors, content } from "../consts";
export function createTOTPCard({
element,
index,
storage,
isEditing,
tempIssuer,
tempClient,
onRename,
onSave,
onDelete,
onMoveUp,
onMoveDown,
onIssuerChange,
onClientChange,
isEditInProgress,
}) {
const infoView = View(
{
style: {
display: "flex",
flexDirection: "column",
alignItems: "flex-start",
},
},
isEditing
? [
TextInput({
label: content.renameButtons.renameIssuer,
value: tempIssuer,
onChange: onIssuerChange,
labelStyle: {
backgroundColor: colors.notify,
display: "flex",
alignItems: "center",
justifyContent: "center",
margin: "10px",
fontSize: "20px",
color: colors.text,
borderRadius: "5px",
height: "40px",
width: "200px",
},
subStyle: {
display: "none",
},
}),
TextInput({
label: content.renameButtons.renameClient,
value: tempClient,
onChange: onClientChange,
labelStyle: {
backgroundColor: colors.notify,
display: "flex",
alignItems: "center",
justifyContent: "center",
margin: "10px",
fontSize: "20px",
color: colors.text,
borderRadius: "5px",
height: "40px",
width: "200px",
},
subStyle: {
display: "none",
},
}),
]
: [
Text(
{
style: {
color: colors.text,
marginBottom: "2px",
fontWeight: "600",
},
},
`Issuer: ${element.issuer}`,
),
Text(
{ style: { color: colors.text, fontWeight: "600" } },
`Client: ${element.client}`,
),
],
);
const buttonsView = View(
{ style: { display: "flex", flexDirection: "row" } },
isEditing
? [
Button({
label: content.saveButton.label,
style: {
margin: "5px",
backgroundColor: "#28a745",
color: colors.text,
},
onClick: onSave,
}),
]
: [
Button({
label: content.renameButtons.rename,
style: {
margin: "5px",
backgroundColor: colors.notify,
color: colors.text,
},
onClick: onRename,
}),
!isEditInProgress
? Button({
label: content.deleteButton.label,
style: {
margin: "5px",
backgroundColor: colors.alert,
color: colors.text,
},
onClick: onDelete,
})
: null,
],
);
const reorderView = View(
{ style: { display: "flex", flexDirection: "column" } },
[
Button({
label: "⬆",
disabled: index === 0,
style: {
margin: "2px",
color: colors.text,
backgroundColor: colors.notify,
},
onClick: onMoveUp,
}),
Button({
label: "⬇",
disabled: index === storage.length - 1,
style: {
margin: "2px",
color: colors.text,
backgroundColor: colors.notify,
},
onClick: onMoveDown,
}),
],
);
const mainContent = View({ style: { flexGrow: 1, padding: "5px" } }, [
infoView,
Text(
{
style: {
color: colors.text,
fontSize: "14px",
marginTop: "5px",
},
},
content.totpDescText.eval(
element.hashType,
element.digits,
element.fetchTime,
element.timeOffset,
),
),
buttonsView,
]);
return View(
{
style: {
display: "flex",
flexDirection: "row",
justifyContent: "space-between",
alignItems: "center",
backgroundColor: colors.secondaryBg,
borderRadius: "5px",
margin: "10px",
padding: "5px",
},
},
[mainContent, reorderView],
);
}

View File

@@ -0,0 +1,11 @@
export class ProtonBackupExport {
version;
entries = Array.of(ProtonTotpRecord);
}
export class ProtonTotpRecord {
content = {
uri,
entry_type,
};
}

View File

@@ -1,16 +1,29 @@
import { decodeProto, TYPES } from "../../lib/protobuf-decoder/protobufDecoder";
import { TOTP } from "../../lib/totp-quickjs";
import { base64decode, encode } from "../../lib/totp-quickjs/base32decoder";
import { ProtonBackupExport } from "./protonBackupExport";
const otpauthScheme = "otpauth:/";
const googleMigrationScheme = "otpauth-migration:/";
const otpauthScheme = "otpauth://";
const googleMigrationScheme = "otpauth-migration://";
export function getTOTPByLink(link) {
if (link.includes(otpauthScheme)) return getByOtpauthScheme(link);
if (link.includes(googleMigrationScheme))
try {
//proton export
const json = JSON.parse(link);
console.log(json);
return getByProtonBackup(json);
} catch (e) {
if (link.startsWith(googleMigrationScheme)) {
//google migration export
return getByGoogleMigrationScheme(link);
return null;
}
if (link.startsWith(otpauthScheme)) {
//otpauth export
return getByOtpauthScheme(link);
}
throw new Error(
`Unsupported link type. Please use an otpauth:// or otpauth-migration:// link\n ERR: ${e}`,
);
}
}
function getHashType(algorithm) {
@@ -20,80 +33,163 @@ function getHashType(algorithm) {
else return "SHA-1";
}
function getByProtonBackup(protonjson) {
try {
if ("entries" in protonjson && protonjson.version == 1) {
//Is proton export?
console.log(1);
const protonBE = Object.assign(
new ProtonBackupExport(),
protonjson,
);
const res = protonBE.entries.map((x) => {
return getByOtpauthScheme(x.content.uri);
});
console.log(res);
return res;
} else throw new Error("use proton export backup with version: 1");
} catch (e) {
console.log(e);
throw new Error(`Unsupported JSON type: ${e}`);
}
}
function getByOtpauthScheme(link) {
try {
let args = link.split("/", otpauthScheme.length);
let type = args[2]; //Returns 'hotp' or 'totp'
let issuer = args[3].split(":")[0]?.split("?")[0]; //Returns issuer
let client =
args[3].split(":")[1]?.split("?")[0] ??
args[3].split(":")[0]?.split("?")[0]; //Returns client
let secret = args[3].split("secret=")[1]?.split("&")[0]; //Returns secret
let period = args[3].split("period=")[1]?.split("&")[0]; //Returns period
let digits = args[3].split("digit=")[1]?.split("&")[0]; //Returns digits
let algorithm = args[3].split("algorithm=")[1]?.split("&")[0]; //Returns algorithm
let offset = args[3].split("offset=")[1]?.split("&")[0] ?? 0; //Returns offset
let args = link.split("?");
let path = args[0];
let params = args[1];
let pathParts = path.split("/");
let type = pathParts[2]; //hotp or totp
let label = decodeURIComponent(pathParts[3]);
let issuerFromLabel = label.includes(":") ? label.split(":")[0] : null;
let client = label.includes(":") ? label.split(":")[1].trim() : label;
client = decodeURIComponent(client);
let secret = params.match(/secret=([^&]*)/)?.[1];
let issuerFromParams = params.match(/issuer=([^&]*)/)?.[1];
let issuer = issuerFromParams
? decodeURIComponent(issuerFromParams)
: decodeURIComponent(issuerFromLabel);
if (!issuer) issuer = client;
let period = params.match(/period=([^&]*)/)?.[1];
let digits = params.match(/digits=([^&]*)/)?.[1];
let algorithm = params.match(/algorithm=([^&]*)/)?.[1];
let offset = params.match(/offset=([^&]*)/)?.[1] ?? 0;
if (type.toLowerCase() != "totp")
throw new Error("Type is not valid, requires 'TOTP'");
if (secret === undefined) throw new Error("Secret not defined");
if (issuer == client) {
issuer = args[3].split("issuer=")[1]?.split("&")[0];
}
issuer = decodeURIComponent(issuer);
client = decodeURIComponent(client);
if (!secret) throw new Error("Secret not defined");
return new TOTP(
secret,
issuer,
client,
Number(digits),
Number(period),
Number(digits) || 6,
Number(period) || 30,
Number(offset),
getHashType(algorithm),
);
} catch (err) {
console.log(`ERR: ${err}`);
return null;
console.log("Failed to parse otpauth scheme:", err);
throw new Error(
`Invalid otpauth:// link. Please check the link and try again. ERR: ${err}`,
);
}
}
function getByGoogleMigrationScheme(link) {
let data = link.split("data=")[1]; //Returns base64 encoded data
data = decodeURIComponent(data);
let decode = base64decode(data);
let proto = decodeProto(decode);
try {
const data = link.split("data=")[1];
if (!data) return null;
let protoTotps = [];
const decodedData = decodeURIComponent(data);
const buffer = base64decode(decodedData);
const proto = decodeProto(buffer);
proto.parts.forEach((part) => {
if (part.type == TYPES.LENDELIM) {
protoTotps.push(decodeProto(part.value));
}
});
let totps = [];
protoTotps.forEach((x) => {
let type = x.parts.filter((x) => x.index == 6)[0]; //find type of OTP
if (type.value !== "2") {
console.log("ERR: it's a not TOTP record");
return;
}
let secret = x.parts.filter((x) => x.index == 1)[0].value;
secret = encode(secret);
let name = bytesToString(x.parts.filter((x) => x.index == 2)[0].value);
let issuer = bytesToString(
x.parts.filter((x) => x.index == 3)[0].value,
const totps = [];
const otpParameters = proto.parts.filter(
(p) => p.index === 1 && p.type === TYPES.LENDELIM,
);
totps.push(new TOTP(secret, issuer, name, 6, 30, 0, "SHA-1"));
otpParameters.forEach((part) => {
const totp = parseSingleMigrationEntry(part);
if (totp) {
totps.push(totp);
}
});
return totps;
return totps.length > 0 ? totps : null;
} catch (err) {
console.log("Failed to parse Google Migration scheme:", err);
throw new Error(
"Invalid otpauth-migration:// link. Failed to parse migration data.",
);
}
}
function parseSingleMigrationEntry(part) {
const totpProto = decodeProto(part.value);
const otpData = {};
const protoPartHandlers = {
1: (p) => {
otpData.secret = encode(p.value);
},
2: (p) => {
otpData.name = bytesToString(p.value);
},
3: (p) => {
otpData.issuer = bytesToString(p.value);
},
4: (p) => {
otpData.algorithm = p.value;
},
5: (p) => {
otpData.digits = p.value;
},
6: (p) => {
otpData.type = p.value;
},
};
totpProto.parts.forEach((p) => {
const handler = protoPartHandlers[p.index];
if (handler) {
handler(p);
}
});
if (otpData.type !== "2") {
return null;
}
const digitsMap = { 1: 6, 2: 8 };
const algoMap = { 1: "SHA-1", 2: "SHA-256", 3: "SHA-512" };
const finalDigits = digitsMap[otpData.digits] || 6;
const finalAlgo = algoMap[otpData.algorithm] || "SHA-1";
const finalIssuer = otpData.issuer || otpData.name;
const finalName = otpData.name;
if (!otpData.secret || !finalName) {
throw new Error("Skipping record with missing secret or name.");
}
return new TOTP(
otpData.secret,
finalIssuer,
finalName,
finalDigits,
30,
0,
finalAlgo,
);
}
function bytesToString(bytes) {