Skip to content
Open
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
14 changes: 10 additions & 4 deletions modules/sdk-api/src/bitgoAPI.ts
Original file line number Diff line number Diff line change
Expand Up @@ -712,10 +712,11 @@ export class BitGoAPI implements BitGoBase {
// prevent IE from caching requests
req.set('If-Modified-Since', 'Mon, 26 Jul 1997 05:00:00 GMT');

if (typeof window === 'undefined' && this._userAgent) {
// If not in the browser, set the User-Agent. Browsers don't allow
// setting of User-Agent, so we must disable this when run in the
// browser (browserify sets process.browser).
if (typeof XMLHttpRequest === 'undefined' && this._userAgent) {
// Set the User-Agent only in XHR-less runtimes (Node). Browsers don't allow setting of
// User-Agent, so we must disable this when XMLHttpRequest is available. Detection must
// be based on XHR rather than `window`: dedicated workers have no `window` but still
// run in a browser/XHR context where setting User-Agent fails.
req.set('User-Agent', this._userAgent);
}

Expand Down Expand Up @@ -2114,6 +2115,7 @@ export class BitGoAPI implements BitGoBase {
newPassword,
encryptionVersion,
progressCallback,
yieldEvery,
}: ChangePasswordOptions): Promise<any> {
if (!_.isString(oldPassword)) {
throw new Error('expected string oldPassword');
Expand All @@ -2123,6 +2125,8 @@ export class BitGoAPI implements BitGoBase {
throw new Error('expected string newPassword');
}

common.validateYieldEvery(yieldEvery);

const user = this.user();
if (typeof user !== 'object' || !user.username) {
throw new Error('missing required object user');
Expand Down Expand Up @@ -2200,6 +2204,7 @@ export class BitGoAPI implements BitGoBase {
encryptionVersion,
encryptionSession,
progressCallback: makeKeychainProgressCallback('v1'),
yieldEvery,
});
// Every v1 entry emits exactly one progress event, so the returned map's size is
// the v1 contribution to the denominator; v2 events below add it to their total.
Expand All @@ -2212,6 +2217,7 @@ export class BitGoAPI implements BitGoBase {
encryptionVersion,
encryptionSession,
progressCallback: makeKeychainProgressCallback('v2'),
yieldEvery,
});

// A v1-only account emits no v2 event, so its total would stay undefined for the
Expand Down
7 changes: 7 additions & 0 deletions modules/sdk-api/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -322,6 +322,13 @@ export interface ChangePasswordOptions {
encryptionVersion?: EncryptionVersion;
/** Optional observer invoked as the password rotation progresses through keychains and finalization. */
progressCallback?: PasswordRotationProgressCallback;
/**
* Opt-in cooperative-yielding boundary: after every N listed keychain records handled by a
* rotation loop, yield to a new macrotask so the host event loop can process I/O, worker
* messages, or repaints between bounded stretches of keychain crypto. Must be a positive safe
* integer. When omitted, the existing behavior is preserved exactly.
*/
yieldEvery?: number;
}

/**
Expand Down
10 changes: 10 additions & 0 deletions modules/sdk-api/src/v1/keychains.ts
Original file line number Diff line number Diff line change
Expand Up @@ -183,6 +183,7 @@ Keychains.prototype.list = function (params, callback) {
Keychains.prototype.updatePassword = function (params, callback) {
return async function coUpdatePassword() {
common.validateParams(params, ['oldPassword', 'newPassword'], [], callback);
common.validateYieldEvery(params.yieldEvery);
// @ts-expect-error - no implicit this
const encrypted = await this.bitgo.post(this.bitgo.url('/user/encrypted')).result();
const newKeychains = {};
Expand All @@ -198,6 +199,11 @@ Keychains.prototype.updatePassword = function (params, callback) {
// ignore observer exceptions so a throwing callback never affects rotation results
}
};
// Opt-in cooperative-yielding boundary: every `yieldEvery` listed records — updated and
// skipped alike — yields to a new macrotask so the host event loop can process I/O, worker
// messages, or repaints between bounded stretches of keychain crypto. `undefined` preserves
// the existing behavior exactly.
let processedRecords = 0;
for (const [xpub, oldEncryptedXprv] of Object.entries((encrypted as any).keychains)) {
try {
const decryptedPrv = await self.bitgo.decrypt({
Expand All @@ -217,6 +223,10 @@ Keychains.prototype.updatePassword = function (params, callback) {
newKeychains[xpub] = oldEncryptedXprv as string;
notifyProgress('skipped', xpub);
}
processedRecords++;
if (params.yieldEvery !== undefined && processedRecords % params.yieldEvery === 0) {
await new Promise<void>((resolve) => setTimeout(resolve, 0));
}
}
return { keychains: newKeychains, version: (encrypted as any).version };
}
Expand Down
89 changes: 83 additions & 6 deletions modules/sdk-api/test/unit/bitgoAPI.ts
Original file line number Diff line number Diff line change
Expand Up @@ -406,15 +406,15 @@ describe('Constructor', function () {
sinon.restore();
});

it('should set User-Agent header when running in Node.js (typeof window === undefined)', async function () {
it('should set User-Agent header when running in Node.js (no XMLHttpRequest)', async function () {
const bitgo = new BitGoAPI({
env: 'custom',
customRootURI: 'https://app.example.local',
userAgent: 'TestAgent/1.0',
});

// Ensure we're in a Node.js environment by verifying window is undefined
(typeof window).should.equal('undefined');
// Ensure we're in a Node.js environment by verifying XMLHttpRequest is undefined
(typeof XMLHttpRequest).should.equal('undefined');

const scope = nock('https://app.example.local')
.get('/api/v1/ping')
Expand All @@ -433,10 +433,11 @@ describe('Constructor', function () {
scope.isDone().should.be.true();
});

it('should not set User-Agent header when running in browser (typeof window !== undefined)', async function () {
// Mock the window object to simulate browser environment
it('should not set User-Agent header when running in browser (window and XMLHttpRequest available)', async function () {
// Mock the browser globals: window and XMLHttpRequest
const windowStub = { location: 'mock' };
(global as any).window = windowStub;
(global as any).XMLHttpRequest = class MockXMLHttpRequest {};

try {
const bitgo = new BitGoAPI({
Expand Down Expand Up @@ -467,8 +468,48 @@ describe('Constructor', function () {

scope.isDone().should.be.true();
} finally {
// Clean up the global window mock
// Clean up the global browser mocks
delete (global as any).window;
delete (global as any).XMLHttpRequest;
}
});

it('should not set User-Agent header in a dedicated worker runtime (no window, XMLHttpRequest available)', async function () {
// Dedicated workers expose XMLHttpRequest but not `window`; user-agent detection must be
// XHR-based rather than window-based so worker requests never attempt to set User-Agent.
(typeof window).should.equal('undefined');
(global as any).XMLHttpRequest = class MockXMLHttpRequest {};

try {
const bitgo = new BitGoAPI({
env: 'custom',
customRootURI: 'https://app.example.local',
userAgent: 'TestAgent/1.0',
});

const scope = nock('https://app.example.local')
.get('/api/v1/ping')
.reply(function () {
// Verify User-Agent header is NOT set to our custom value
const userAgent = this.req.headers['user-agent'];
if (userAgent && userAgent.includes('TestAgent/1.0')) {
throw new Error('User-Agent should not be set in a dedicated worker');
}
return [200, { status: 'ok' }];
});

await bitgo.ping({
reqId: {
toString: () => 'test-123',
inc: () => {
/* mock */
},
} as any,
});

scope.isDone().should.be.true();
} finally {
delete (global as any).XMLHttpRequest;
}
});
});
Expand Down Expand Up @@ -1345,6 +1386,42 @@ describe('Constructor', function () {
sinon.assert.calledWithMatch(v1UpdatePasswordStub, { encryptionVersion: 2 });
sinon.assert.calledWithMatch(v2UpdatePasswordStub, { encryptionVersion: 2 });
});
it('forwards yieldEvery to both v1 and v2 keychains().updatePassword calls', async function () {
nock(ROOT).get('/api/v2/user/checkBatchingPasswordFlow').query(true).reply(200, { isBatchingFlowEnabled: false });
nock(ROOT)
.post('/api/v1/user/changepassword', (body: any) => !!body.keychains && !!body.v2_keychains)
.reply(200, {});

await bitgo.changePassword({ oldPassword: 'oldpw', newPassword: 'newpw', yieldEvery: 1 });

sinon.assert.calledWithMatch(v1UpdatePasswordStub, { yieldEvery: 1 });
sinon.assert.calledWithMatch(v2UpdatePasswordStub, { yieldEvery: 1 });
});
it('passes yieldEvery: undefined to both lower-level calls when not requested', async function () {
nock(ROOT).get('/api/v2/user/checkBatchingPasswordFlow').query(true).reply(200, { isBatchingFlowEnabled: false });
nock(ROOT)
.post('/api/v1/user/changepassword', (body: any) => !!body.keychains && !!body.v2_keychains)
.reply(200, {});

await bitgo.changePassword({ oldPassword: 'oldpw', newPassword: 'newpw' });

// sinon records untyped args; the shape is pinned by the calledWithMatch assertions above.
const v1Params = v1UpdatePasswordStub.firstCall.args[0] as { yieldEvery?: number };
const v2Params = v2UpdatePasswordStub.firstCall.args[0] as { yieldEvery?: number };
// the key is forwarded but carries no value, preserving the no-yield behavior exactly
(v1Params.yieldEvery === undefined).should.be.true();
(v2Params.yieldEvery === undefined).should.be.true();
});
it('rejects invalid yieldEvery values at the public entry before any rotation work', async function () {
const invalidValues: unknown[] = [0, -1, 1.5, NaN, Number.MAX_SAFE_INTEGER + 1, '1'];
for (const yieldEvery of invalidValues) {
await bitgo
.changePassword({ oldPassword: 'oldpw', newPassword: 'newpw', yieldEvery: yieldEvery as number })
.should.be.rejectedWith('yieldEvery must be a positive safe integer');
}
sinon.assert.notCalled(v1UpdatePasswordStub);
sinon.assert.notCalled(v2UpdatePasswordStub);
});
it('creates one encryption session, passes it to both keychain update calls, and destroys it', async function () {
nock(ROOT).get('/api/v2/user/checkBatchingPasswordFlow').query(true).reply(200, { isBatchingFlowEnabled: false });
nock(ROOT)
Expand Down
44 changes: 44 additions & 0 deletions modules/sdk-api/test/unit/v1/keychains.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,8 @@ type V1KeychainsCtor = new (bitgo: V1Bitgo) => {
newPassword: string;
encryptionVersion?: number;
encryptionSession?: IEncryptionSession;
progressCallback?: (progress: { status: 'updated' | 'skipped'; currentKeychainId: string }) => void;
yieldEvery?: number;
}): Promise<V1UpdatePasswordResult>;
};

Expand Down Expand Up @@ -119,4 +121,46 @@ describe('v1 Keychains.updatePassword', function () {
result.keychains.xpubV1.should.equal('re-encrypted');
result.keychains.xpubV2.should.equal('re-encrypted');
});

it('yields to the event loop between records when yieldEvery: 1 is provided', async function () {
const stored = { xpubA: v1Envelope, xpubB: v1Envelope, xpubC: v1Envelope };
nock(ROOT).post('/api/v1/user/encrypted').reply(200, { version: 25, keychains: stored });

const encryptStub = sinon.stub().resolves('re-encrypted');
const keychains = new Keychains(makeBitgo(stored, { [v1Envelope]: 'plain-v1' }, encryptStub));

const timeline: string[] = [];
await keychains.updatePassword({
oldPassword: 'oldpw',
newPassword: 'newpw',
yieldEvery: 1,
progressCallback: (progress) => {
timeline.push(`progress:${progress.currentKeychainId}`);
if (timeline.length === 1) {
// A zero-delay timer scheduled from the first progress callback is enqueued before
// the loop's own yield timer, so with a per-record boundary it must run before the
// second record begins. Without yielding it would run after every record.
setTimeout(() => timeline.push('macrotask'), 0);
}
},
});

timeline.should.deepEqual(['progress:xpubA', 'macrotask', 'progress:xpubB', 'progress:xpubC']);
});

it('rejects invalid yieldEvery values before touching any keychain', async function () {
const stored = { xpubA: v1Envelope };
nock(ROOT).post('/api/v1/user/encrypted').reply(200, { version: 25, keychains: stored });

const encryptStub = sinon.stub().resolves('re-encrypted');
const keychains = new Keychains(makeBitgo(stored, { [v1Envelope]: 'plain-v1' }, encryptStub));

const invalidValues: unknown[] = [0, -1, 1.5, NaN, Number.MAX_SAFE_INTEGER + 1, '1'];
for (const yieldEvery of invalidValues) {
await keychains
.updatePassword({ oldPassword: 'oldpw', newPassword: 'newpw', yieldEvery: yieldEvery as number })
.should.be.rejectedWith('yieldEvery must be a positive safe integer');
}
encryptStub.called.should.equal(false);
});
});
8 changes: 8 additions & 0 deletions modules/sdk-core/src/bitgo/keychain/iKeychains.ts
Original file line number Diff line number Diff line change
Expand Up @@ -169,6 +169,14 @@ export interface UpdatePasswordOptions {
* invokes it.
*/
progressCallback?: KeychainPasswordUpdateProgressCallback;
/**
* Opt-in cooperative-yielding boundary: after every N listed keychain records handled by a rotation
* loop (updated, skipped, or missing-envelope), yield to a new macrotask (`setTimeout(..., 0)`) so the
* host event loop can process I/O, worker messages, or repaints between bounded stretches of keychain
* crypto. Must be a positive safe integer. When omitted, no yield timer is ever created and the existing
* behavior is preserved exactly.
*/
yieldEvery?: number;
}

export interface UpdateSingleKeychainPasswordOptions {
Expand Down
Loading
Loading