Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support extended tokens + expose token feature for library use #15

Merged
merged 6 commits into from
Nov 5, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -35,12 +35,12 @@ This repository contains the **JavaScript** implementions of different OpenPAYGO

Server-side tasks include

- generating OpenPAYGO tokens
- generating OpenPAYGO tokens (normal and extended)
- decoding OpenPAYGO metrics payloads

Device side tasks

- decoding OpenPAYGO tokens
- decoding OpenPAYGO tokens (normal and extended)
- generating OpenPAYGO metrics payloads

## Installation
Expand Down
15 changes: 13 additions & 2 deletions src/encoder.js
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,7 @@ class OpenPAYGOTokenEncoder {
for (let i = 0; i < newCount - 1; i++) {
currentToken = shared.genNextToken(currentToken, key)
}

let finalToken = shared.putBaseInToken(currentToken, tokenBase)

if (restrictDigitSet) {
Expand All @@ -107,11 +108,12 @@ class OpenPAYGOTokenEncoder {
restrictDigitSet = false,
}) {
const startingBaseCode = sharedExtended.getTokenBase(startingCode)
const tokenBase = this.#encodeBase(startingBaseCode, value)
const tokenBase = this.#encodeBaseExtended(startingBaseCode, value)

let currentToken = sharedExtended.putBaseInToken(startingCode, tokenBase)
const newCount = this.#getNewCount(count, mode)

for (let i = 0; i < newCount - 1; i++) {
for (let i = 0; i < newCount - 2; i++) {
currentToken = sharedExtended.genNextToken(currentToken, key)
}
let finalToken = sharedExtended.putBaseInToken(currentToken, tokenBase)
Expand All @@ -135,6 +137,15 @@ class OpenPAYGOTokenEncoder {
return value + baseCode
}

#encodeBaseExtended(baseCode, value) {
baseCode = BigInt(baseCode)
value = BigInt(value)
if (value + baseCode > 999999n) {
return value + baseCode - 1000000
}
return value + baseCode
}

#getNewCount(count, mode) {
let newCount
const currCountOdd = count % 2
Expand Down
60 changes: 32 additions & 28 deletions src/token.js
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,6 @@ class OpenPAYGOTokenShared {
let hash = this.genHash({
key: key,
msg: duplicatedToken,
asByte: true,
})

return this.convertHash2Token(hash)
Expand Down Expand Up @@ -98,59 +97,50 @@ class OpenPAYGOTokenShared {

class OpenPAYGOTokenSharedExtended {
static MAX_BASE_EXTENDED = 999999
static MAX_ACTIVATION_VALUE_EXTENDED = 999999
static TOKEN_VALUE_OFFSET_EXTENDED = 1000000
static MAX_ACTIVATION_VALUE_EXTENDED = 999999n
static TOKEN_VALUE_OFFSET_EXTENDED = 1000000n

constructor() {}

static getTokenBase(code) {
return code % this.TOKEN_VALUE_OFFSET_EXTENDED
return BigInt(code) % this.TOKEN_VALUE_OFFSET_EXTENDED
}

static putBaseInToken(token, tokenBase) {
token = BigInt(token)
tokenBase = BigInt(tokenBase)
if (tokenBase > this.MAX_BASE_EXTENDED) {
throw new Error("Invalid token base value")
}
return token - this.getTokenBase(token) + tokenBase
}

static genNextToken(prev_token, key) {
const conformedToken = Buffer.alloc(4) // Allocate buffer of 4 bytes
conformedToken.writeUInt32BE(prev_token, 0) // Write the integer value into buffer as big-endian
prev_token = BigInt(prev_token)
const conformedToken = Buffer.alloc(8) // Allocate buffer of 8 bytes
conformedToken.writeBigUInt64BE(prev_token, 0) // Write the integer value into buffer as big-endian

// Duplicate the buffer by concatenating it with itself
const duplicatedToken = Buffer.concat([conformedToken, conformedToken])
let hash = this.genHash({
key: key,
msg: duplicatedToken,
msg: conformedToken,
asByte: true,
})

return this.convertHash2Token(hash)
}

static convertHash2Token(hash) {
// convert hash from hex

const hashBuffer = bigintConversion.hexToBuf(hash, true)

const dView = new DataView(hashBuffer)

// take first 4 btypes
const hash_msb = dView.getUint32(0) // as big endian
// take last 4 bytes
const hash_lsb = dView.getUint32(4) // as big endian

const hashUnit = (hash_msb ^ hash_lsb) >>> 0
const token = this.convertTo29_5_bits(hashUnit)
const hashUint = bigintConversion.hexToBigint(hash)
const token = this.convertTo_40_bits(hashUint)
return token
}

static convertTo29_5_bits(hash_uint) {
static convertTo_40_bits(hash_uint) {
// port from original lib
const mask = ((1 << (64 - 24 + 1)) - 1) << 24
let temp = (hash_uint & mask) >>> 24
if (temp > 999999999999) temp = temp - 99511627777
// const mask = ((1 << (64 - 24 + 1)) - 1) << 24
const mask = 36893488147402326016n
let temp = (hash_uint & mask) >> 24n
if (temp > 999999999999n) temp = temp - 99511627777n
return temp
}

Expand Down Expand Up @@ -187,6 +177,14 @@ function bitArrayFromInt(number, bitLength) {
return bitArray
}

function bitArrayFromBigInt(number, bitLength) {
let bitArray = []
for (let i = 0; i < bitLength; i++) {
bitArray.push((number & (1n << BigInt(bitLength - 1 - i))) !== 0n)
}
return bitArray
}

function bitArrayToInt(bit_array) {
let num = 0
for (let bit of bit_array) {
Expand All @@ -209,14 +207,20 @@ function convertFrom4digitToken(token) {
function convertToNdigitToken(token, digit = 4) {
// token should be a number data type
let restrictedDigitToken = ""
let bitArray = bitArrayFromInt(token, digit * 2)
let bitArray
if (typeof token === "bigint") {
bitArray = bitArrayFromBigInt(token, digit * 2)
} else {
bitArray = bitArrayFromInt(token, digit * 2)
}

for (let i = 0; i < digit; i++) {
restrictedDigitToken += (
bitArrayToInt(bitArray.slice(i * 2, i * 2 + 2)) + 1
).toString()
}
return parseInt(restrictedDigitToken, 10)

return restrictedDigitToken
}

module.exports = {
Expand Down
10 changes: 4 additions & 6 deletions test/encoder.test.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
const sample = require("./sample_tokens.json")
const Encoder = require("../src/encoder").OpenPAYGOTokenEncoder
const shared = require("../src/token").OpenPAYGOTokenShared

describe("OpenPAYGOTokenEncoder test", () => {
test("generateToken", () => {
const encoder = new Encoder()

sample.forEach((s) => {
const data = s
try {
Expand All @@ -15,14 +15,12 @@ describe("OpenPAYGOTokenEncoder test", () => {
startingCode: data.starting_code,
restrictDigitSet: data.restricted_digit_set,
value: data.value_raw,
extendToken: false,
extendToken: data.extended_token,
})

expect(finalToken).toBe(data.token)
} catch (err) {
if (!err.message.includes("The value provided is too high.")) {
throw err
}
expect(data.extended_token).toBe(false)
expect(data.value_raw > shared.MAX_ACTIVATION_VALUE).toBe(true)
}
})
})
Expand Down
Loading
Loading