The New Zealand parliament has narrowly approved a spying bill that opponents say represents a fundamental threat to democratic rights and freedoms.

Prompted by revelations of illegal spying on Kim Dotcom, the internet entrepreneur being sought for extradition from New Zealand by the US, the shakeup of the Government Communications Security Bureau (GCSB) progressed by a margin of two votes on Wednesday evening.

The prime minister, John Key, said the changes bolster oversight and settle confusion in the previous law, making it clear that the GCSB – similar to Britain's GCHQ – can conduct surveillance on behalf of domestic agencies, under warrant.

Opponents of the bill have argued that the new provisions giving GCSB the task of protecting New Zealanders from cyber-attack open a door to mass surveillance of electronic communications.

The prime minister has maintained that the measures, which he has compared to a Norton Antivirus for the country, do no such thing, and has pledged to resign should the agency be found to have embarked on mass surveillance.

The Green party co-leader, Russel Norman, argued that the legislation undermined freedom of expression. "It reduces our freedom to live free from state surveillance and in that respect is a bill that reduces the freedom of New Zealanders. It is the moment of truth," he said.

Key accused critics of the legislation, who include the New Zealand Law Society and the Human Rights Commission, of peddling "misinformation and conspiracy theories".

"Despite ill-informed claims to the contrary, nothing in this legislation allows for wholesale spying on New Zealanders. It actually tightens, not widens, the existing regime," he said.

The bill had faced widespread public opposition. Auckland town hall was filled to capacity on Monday night to rally against the legislation, and a Fairfax Media poll published on Wednesday morning found that 75% of New Zealanders were worried about the changes.

Critics have been motivated in part by concerns over the leaks from the former NSA contractor Edward Snowden.

The GCSB is one of the "five eyes" in the Echelon information-sharing network along with the US's NSA, GCHQ and agencies in Canada and Australia. Key has refused to be drawn on the way that New Zealand exchanges information within the network, but insists that the arrangement is not used to circumvent domestic laws.

New Zealand's spy agencies will be subject to an independent review every five to seven years, although the first such review will not take place for two years, after the next election.