Skip to content
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
109 changes: 109 additions & 0 deletions __tests__/actiontoken-bundle-link.spec.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
require('dotenv').config();
const request = require('supertest');
const { expect } = require('chai');
const server = require('../server/app');
const seed = require('./seed');

function decode(actionToken) {
const part = actionToken.split('.')[1];
return JSON.parse(Buffer.from(part, 'base64url').toString());
}

describe('Action token: a bundle link promises a count, not named tokens', () => {
let bearerTokenA;
let bearerTokenB;

beforeEach(async () => {
await seed.clear();
await seed.seed();
bearerTokenA = seed.wallet.keycloak_account_id;
bearerTokenB = seed.walletB.keycloak_account_id;
});

async function issueBundleLink(size) {
const res = await request(server)
.post('/action-tokens')
.set('Authorization', `Bearer ${bearerTokenA}`)
.send({
recipient_email: 'samwel@example.com',
bundle: { bundle_size: size },
});
expect(res).to.have.property('statusCode', 201);
return res.body.action_token;
}

it('carries a count and names no tokens', async () => {
const payload = decode(await issueBundleLink(1));

expect(payload).to.have.property('token_count', 1);
expect(payload).to.not.have.property('token_ids');
});

it('survives the sender spending the token it would have named', async () => {
const link = await issueBundleLink(1);
const [spare] = await seed.addTokenToWallet(seed.wallet.id);

await request(server)
.post('/transfers')
.set('content-type', 'application/json')
.set('Authorization', `Bearer ${bearerTokenA}`)
.send({
tokens: [seed.token.id],
sender_wallet: seed.wallet.name,
receiver_wallet: seed.walletB.name,
})
.expect(202);

const redeemed = await request(server)
.post('/action-tokens/redeem')
.set('Authorization', `Bearer ${bearerTokenB}`)
.send({ action_token: link });

expect(redeemed).to.have.property('statusCode', 200);
expect(redeemed.body.parameters.tokens).eql([spare.id]);
});

it('refuses when the wallet has dropped below the promised count', async () => {
const link = await issueBundleLink(1);

await request(server)
.post('/transfers')
.set('content-type', 'application/json')
.set('Authorization', `Bearer ${bearerTokenA}`)
.send({
tokens: [seed.token.id],
sender_wallet: seed.wallet.name,
receiver_wallet: seed.walletB.name,
})
.expect(202);

const redeemed = await request(server)
.post('/action-tokens/redeem')
.set('Authorization', `Bearer ${bearerTokenB}`)
.send({ action_token: link });

expect(redeemed).to.have.property('statusCode', 409);
expect(redeemed.body.message).match(/does not have 1 tokens available/);
});

it('still claims a link that names its tokens', async () => {
const issued = await request(server)
.post('/action-tokens')
.set('Authorization', `Bearer ${bearerTokenA}`)
.send({
recipient_email: 'samwel@example.com',
tokens: [seed.token.id],
})
.expect(201);

expect(decode(issued.body.action_token)).to.have.property('token_ids');

const redeemed = await request(server)
.post('/action-tokens/redeem')
.set('Authorization', `Bearer ${bearerTokenB}`)
.send({ action_token: issued.body.action_token });

expect(redeemed).to.have.property('statusCode', 200);
expect(redeemed.body.parameters.tokens).to.include(seed.token.id);
});
});
7 changes: 7 additions & 0 deletions server/models/Token.js
Original file line number Diff line number Diff line change
Expand Up @@ -125,6 +125,13 @@ class Token {
return transactions;
}

async getTransferableByOwner(walletId, limit) {
return this._tokenRepository.getByFilter(
{ wallet_id: walletId, transfer_pending: false, claim: false },
{ limit },
);
}

async getByOwner(walletId, limit, offset) {
const tokens = await this._tokenRepository.getByFilter(
{ wallet_id: walletId },
Expand Down
24 changes: 14 additions & 10 deletions server/services/ActionTokenService.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@
*/
const jwt = require('jsonwebtoken');
const HttpError = require('../utils/HttpError');
const Session = require('../infra/database/Session');
const Token = require('../models/Token');
const TokenService = require('./TokenService');
const TransferService = require('./TransferService');
const WalletService = require('./WalletService');
Expand All @@ -30,6 +32,8 @@ const ACTION_TOKEN_SECRET = resolveActionTokenSecret();

class ActionTokenService {
constructor() {
this._session = new Session();
this._token = new Token(this._session);
this._tokenService = new TokenService();
this._transferService = new TransferService();
this._walletService = new WalletService();
Expand Down Expand Up @@ -80,6 +84,7 @@ class ActionTokenService {
keycloakId,
) {
let tokenIds;
let tokenCount;

let senderWalletId = walletLoginId;
if (sender_wallet) {
Expand Down Expand Up @@ -111,32 +116,30 @@ class ActionTokenService {
}
tokenIds = resolved.map((token) => token.id);
} else {
const resolved = await this._tokenService.getTokens({
wallet: sender_wallet,
limit: bundle.bundle_size,
offset: 0,
walletLoginId,
});
if (resolved.length < bundle.bundle_size) {
const available = await this._token.getTransferableByOwner(
senderWalletId,
bundle.bundle_size,
);
if (available.length < bundle.bundle_size) {
throw new HttpError(
409,
`Wallet does not have ${bundle.bundle_size} tokens available`,
);
}
tokenIds = resolved.map((token) => token.id);
tokenCount = bundle.bundle_size;
}

const actionToken = ActionTokenService.signActionToken({
sub: recipient_email,
sender_wallet_id: senderWalletId,
token_ids: tokenIds,
...(tokenIds ? { token_ids: tokenIds } : { token_count: tokenCount }),
});

const { exp } = ActionTokenService.verifyActionToken(actionToken);
return {
action_token: actionToken,
expires_at: new Date(exp * 1000).toISOString(),
token_count: tokenIds.length,
token_count: tokenIds ? tokenIds.length : tokenCount,
};
}

Expand All @@ -146,6 +149,7 @@ class ActionTokenService {
senderWalletId: payload.sender_wallet_id,
receiverWalletId: walletLoginId,
tokenIds: payload.token_ids,
tokenCount: payload.token_count,
});
}
}
Expand Down
33 changes: 27 additions & 6 deletions server/services/TransferService.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
const Session = require('../infra/database/Session');
const Transfer = require('../models/Transfer');
const Token = require('../models/Token');
const HttpError = require('../utils/HttpError');
const WalletService = require('./WalletService');
const TokenService = require('./TokenService');
Expand All @@ -11,6 +12,7 @@ class TransferService {
constructor() {
this._session = new Session();
this._transfer = new Transfer(this._session);
this._token = new Token(this._session);
this._walletService = new WalletService();
this._eventService = new EventService();
}
Expand Down Expand Up @@ -441,18 +443,37 @@ class TransferService {


// Transfer the tokens promised by a redeemed action token
async redeemActionToken({ senderWalletId, receiverWalletId, tokenIds }) {
async redeemActionToken({
senderWalletId,
receiverWalletId,
tokenIds,
tokenCount,
}) {
try {
await this._session.beginTransaction();

const senderWallet = await this._walletService.getById(senderWalletId);
const receiverWallet =
await this._walletService.getById(receiverWalletId);

const tokenService = new TokenService();
const tokens = await Promise.all(
tokenIds.map((id) => tokenService.getById({ id }, true)),
);
let tokens;
if (tokenIds) {
const tokenService = new TokenService();
tokens = await Promise.all(
tokenIds.map((id) => tokenService.getById({ id }, true)),
);
} else {
tokens = await this._token.getTransferableByOwner(
senderWallet.id,
tokenCount,
);
if (tokens.length < tokenCount) {
throw new HttpError(
409,
`Wallet does not have ${tokenCount} tokens available`,
);
}
}

const result = await this._transfer.transferActionToken(
receiverWallet.id,
Expand All @@ -464,7 +485,7 @@ class TransferService {
const payload = {
walletSender: senderWallet.name,
walletReceiver: receiverWallet.name,
tokenTransferred: tokenIds,
tokenTransferred: tokens.map((token) => token.id),
};

await this._eventService.logEvent({
Expand Down
Loading