Cybersecurity & cyberwarfare ha ricondiviso questo.

U.S. CISA adds a flaw in Microsoft Defender to its Known Exploited Vulnerabilities catalog
securityaffairs.com/191164/hac…
#securityaffairs #hacking
Cybersecurity & cyberwarfare ha ricondiviso questo.

The media in this post is not displayed to visitors. To view it, please go to the original post.

TypeScript 7.0 Beta: il nuovo compilatore in Go è circa 10 volte più veloce
#tech
spcnet.it/typescript-7-0-beta-…
@informatica


TypeScript 7.0 Beta: il nuovo compilatore in Go è circa 10 volte più veloce


Il team di TypeScript ha rilasciato la beta ufficiale di TypeScript 7.0, e non si tratta di un aggiornamento incrementale: il compilatore è stato riscritto in Go, con miglioramenti di performance che in molti scenari superano un fattore 10x. Dopo quasi un anno di anteprime tecniche sotto il nome TypeScript Native Preview, Microsoft porta la versione nativa del compilatore a un pubblico molto più ampio e la raccomanda per uso quotidiano, pur restando formalmente in beta.

Perché riscrivere il compilatore in Go


Il compilatore di TypeScript era storicamente scritto nello stesso linguaggio che compilava. Questa scelta, elegante dal punto di vista del bootstrapping, ha sempre comportato un costo: su codebase di grandi dimensioni il tsc può impiegare decine di secondi (o minuti) per il type-checking e il watch mode si appesantisce rapidamente all’aumentare dei file.

La riscrittura in Go non è un rewrite da zero: il team parla esplicitamente di un port metodico, mantenendo parità strutturale con la logica di type-checking di TypeScript 6.0. Questo approccio riduce il rischio di regressioni semantiche: la stessa base di casi di test, le stesse regole, ma con le velocità permesse da codice nativo e dal parallelismo reale a memoria condivisa.

Il risultato, secondo Microsoft, è che TypeScript 7.0 è circa 10 volte più veloce di TypeScript 6.0. Team come Bloomberg, Figma, Google, Slack e Vercel hanno riportato numeri comparabili durante la beta privata, con riduzioni drastiche dei tempi di build in CI.

Come provarlo oggi


L’installazione avviene come package separato per non rompere le pipeline esistenti. Basta un singolo comando:

npm install -D @typescript/native-preview@beta
npx tsgo --version
# Version 7.0.0-beta

Durante la fase beta, l’eseguibile si chiama tsgo al posto di tsc. Per Visual Studio Code è disponibile l’estensione “TypeScript Native Preview”, che affianca il language service classico permettendo di confrontare i tempi di risposta in tempo reale.

Parallelismo configurabile


Una delle novità più sottili, ma con maggiore impatto pratico, è il parallelismo integrato nel compilatore:

  • --checkers N: numero di worker dedicati al type-checking (default 4). I worker mantengono viste indipendenti per evitare ricalcoli ridondanti, ma i risultati restano deterministici.
  • --builders N: abilita la compilazione parallela di più progetti referenziati (project references). Ha un effetto moltiplicativo quando combinato con --checkers, ed è particolarmente efficace nei monorepo.
  • --singleThreaded: forza l’esecuzione sequenziale per debugging o ambienti con memoria limitata (container CI con poca RAM, ad esempio).

Alzare --checkers aumenta la velocità ma anche il consumo di memoria: su agenti CI piccoli conviene fare qualche prova empirica prima di spingerlo oltre 8.

Breaking changes: la pulizia annunciata


TypeScript 7.0 è anche l’occasione per rimuovere anni di retrocompatibilità. Chi mantiene progetti legacy dovrà prestare attenzione, perché molte opzioni di configurazione sono semplicemente scomparse:

  • target: es5 non è più supportato.
  • downlevelIteration, moduleResolution: node/node10/classic, e i moduli amd, umd, systemjs, none sono stati rimossi.
  • baseUrl è stato eliminato: usare paths relativo alla root del progetto.
  • esModuleInterop, allowSyntheticDefaultImports e alwaysStrict non possono più essere disattivati.

Cambiano anche diversi default: strict: true, module: esnext, target pari all’ultima versione ECMAScript stabile prima di esnext, noUncheckedSideEffectImports: true, e soprattutto types: []. Quest’ultimo è il cambiamento che più spesso romperà le build: prima @types/* venivano inclusi automaticamente, ora vanno dichiarati esplicitamente:

{
  "compilerOptions": {
    "types": ["node", "jest"]
  }
}

Sul fronte del supporto a JavaScript con JSDoc, la pulizia è ancora più netta: i valori non possono più sostituire i tipi (usare typeof valore), la sintassi Closure-style function(string): void è rimossa, così come @enum e l’operatore postfisso !.

Convivenza con TypeScript 6.0


Per chi non può migrare subito tutte le pipeline, è possibile installare entrambe le versioni affiancate:

npm install -D typescript@npm:@typescript/typescript6

Così typescript continua a puntare a 6.0, mentre tsgo (o tsc7 dopo il rilascio finale) resta disponibile come entry point separato. È lo scenario consigliato per confrontare gradualmente i due compilatori su progetti reali prima di fare il cutover.

Roadmap e cosa aspettarsi


La beta è datata 21 aprile 2026; il rilascio stabile è previsto entro due mesi, con una release candidate alcune settimane prima. Nel frattempo arriveranno un --watch più efficiente, la parità di declaration file emit per JavaScript, miglioramenti all’editor (ricerca dei riferimenti ai file, comandi import/export più granulari) e una API programmatica stabile, attesa per TypeScript 7.1 o successiva.

Vale la pena migrare subito?


Per team che lavorano su codebase grandi e soffrono di type-check lenti, la risposta è “quasi sicuramente sì, almeno in parallelo”. Microsoft stessa dichiara il compilatore “altamente stabile e altamente compatibile” sulla base di test su codebase da milioni di righe. La strategia più prudente è: installare @typescript/native-preview come dev dependency aggiuntiva, introdurlo come job di CI opzionale accanto al tsc esistente, misurare i tempi reali e segnalare eventuali incompatibilità sul repository microsoft/typescript-go.

Le incompatibilità che emergeranno non saranno di natura logica ma di configurazione: soprattutto il nuovo default types: [] e la rimozione di baseUrl. Chi si è tenuto aggiornato con le versioni recenti dovrebbe cavarsela con poche modifiche al tsconfig.json.

Fonte: Announcing TypeScript 7.0 Beta di Daniel Rosenwasser sul blog ufficiale TypeScript (Microsoft DevBlogs).


Cybersecurity & cyberwarfare ha ricondiviso questo.

#Microsoft Graph API misused by new #GoGra #Linux #malware for hidden communication
securityaffairs.com/191153/unc…
#securityaffairs #hacking
Cybersecurity & cyberwarfare ha ricondiviso questo.

The media in this post is not displayed to visitors. To view it, please go to the original post.

291 – Dovreste tutti avere un’Intelligenza Artificiale in casa camisanicalzolari.it/291-dovre…
Cybersecurity & cyberwarfare ha ricondiviso questo.

The media in this post is not displayed to visitors. To view it, please go to the original post.

Il rischio cyber arriva dalle nuove assunzioni! NKITW: La rete della Corea Del Nord

📌 Link all'articolo : redhotcyber.com/post/il-rischi…

A cura di Bajram Zeqiri

#redhotcyber #news #coreadelnord #sanzioniinternazionali #cybersecurity #hacking #malware #ransomware

Making RAM at Home in Your Own Semiconductor Fab


The media in this post is not displayed to visitors. To view it, please log in.

There’s little point in setting up your own shed-based clean room for semiconductor purposes if you don’t try to do something practical with it. Something like responding to the RAMpocalypse by trying to make your own RAM, for example.
Testing the DRAM cells. (Credit: Dr. Semiconductor, YouTube)Testing the DRAM cells. (Credit: Dr. Semiconductor, YouTube)
After all, what could be so hard about etching the same repeating structures over and over? In a recent video, [Dr. Semiconductor]’s experience doing exactly this are detailed, with actual DRAM resulting at the end.

We covered the construction of the clean room shed previously, which should provide at least the basic conditions to produce semiconductors without worrying about contaminating dies. From here the process is reminiscent of etching PCBs, with a prepared surface coated with photoresist. Using UV exposure through a mask, the pattern is etched into the photoresist and from there the pattern is subsequently etched into the wafer’s surface.

With the patterns formed, the next step is doping of the silicon in order to creative the active structures, i.e. the transistors and capacitors. Doping can be done in a variety of ways, with ion implantation being the industry standard method, but a bit too expensive and bulky for a shed fab. Instead a spin-on-glass method was used. After this the remaining functional structures can be built up.

If anyone was expecting to see a DDR5 DRAM die pop out at the end, they’re bound to be disappointed. The target here was to create a 5×4 array of DRAM cells, for a dizzying 20 bits. Still, the fact that it’s possible to DIY DRAM like this at home is already pretty awesome, with clearly plenty of room to push it towards and past fabrication nodes of the 1990s and beyond.

Although the produced DRAM cells have fairly leaky capacitors, they’re good enough for their purpose, and the plan is to scale up to a large DRAM array from here. Whether the DRAM control logic will also be implemented in hardware like this remains to be seen, but the video’s ending makes it clear that the goal is to attach it to a PC somehow.

youtube.com/embed/h6GWikWlAQA?…


hackaday.com/2026/04/22/making…

Cybersecurity & cyberwarfare ha ricondiviso questo.

The media in this post is not displayed to visitors. To view it, please go to the original post.

🚀 Gli speaker della RHC Conference 2026

📍𝗤𝘂𝗮𝗻𝗱𝗼: Martedì 19 Maggio con ingresso dalle ore 8:45
📍𝗗𝗼𝘃𝗲: Teatro Italia, Via Bari 18, Roma (Metro Piazza Bologna)
📍𝗣𝗿𝗼𝗴𝗿𝗮𝗺𝗺𝗮: redhotcyber.com/linksSk2L/prog…
📍𝗜𝘀𝗰𝗿𝗶𝘇𝗶𝗼𝗻𝗲 conferenza di Martedì 19 Maggio: rhc-conference-2026.eventbrite…

#redhotcyber #rhcconference #conferenza #informationsecurity #ethicalhacking #dataprotection #hacking #cybersecurity #cybercrime #cybersecurityawareness #cybersecuritytraining #cybersecuritynews #privacy #infosecurity

Cybersecurity & cyberwarfare ha ricondiviso questo.

The media in this post is not displayed to visitors. To view it, please go to the original post.

Bufera su Telegram: le autorità del Regno Unito aprono un’inchiesta senza precedenti

📌 Link all'articolo : redhotcyber.com/post/bufera-su…

A cura di Silvia Felici

#redhotcyber #news #telegram #pedopornografia #ofcom #onlinesafetyact #privacyutenti #censurainternet #sicurezzainternet

Cybersecurity & cyberwarfare ha ricondiviso questo.

The media in this post is not displayed to visitors. To view it, please go to the original post.

Anthropic Mythos: scopre 271 vulnerabilità in Mozilla Firefox 150

📌 Link all'articolo : redhotcyber.com/post/anthropic…

A cura di Carolina Vivianti

#redhotcyber #news #intelligenzaartificiale #cybersecurity #sicurezzasoftware #vulnerabilita #firefox #mozilla #antropicmythos

How Gut Bacteria May Affect the Outcome of Cancer Immunotherapy


The media in this post is not displayed to visitors. To view it, please log in.

In the ongoing development of cancer immunotherapy, as well as our still developing understanding of the human immune system, there’s always been a bit of massive elephant in the room. The thing about human bodies is that they’re not just human cells, but also consist of trillions of bacteria that mostly live in the intestines. What effect these bacteria have on the immune system’s functioning and from there on immunotherapies was recently investigated by [Tariq A. Najar] et al., with an article published in Nature.

The relevant topic here is that of antigenic mimicry, involving microbial antigens that resemble self-antigens. Since these self-antigens are a crucial aspect of both autoimmune diseases and cancer immunotherapy there is considerable room for interaction with their microbial mimics. Correspondingly these mimics can have considerable negative as well as positive implications, ranging from potentially triggering an autoimmune condition to hindering or boosting cancer immunotherapy.

In this study mice were used to investigate the effect of such microbial interference, in particular focusing on immune checkpoint blockade (ICB), which refers to negative feedback responses within the immune system that some cancers use to protect themselves. In some immunotherapy patients ICB inhibiting using e.g. anti programmed cell death protein (anti-PD-1) treatment does not provoke a response for some reason.

For the study mice had tumors implanted and the effect of a particular microbe (segmented filamentous bacteria, SFB) on it studied, with the presence of it markedly improving the response to anti-PD-1 treatment due to anti-gens expressed by SFB despite the large gut-skin distance. Whether in humans similar mechanisms play a similarly strong role remains to be investigated, but it offers renewed hope that cancer immunotherapies like CAR T-cell immunotherapy will one day make cancer an easily curable condition.


hackaday.com/2026/04/22/how-gu…

Photographing Rocket Chute Deployment at 10 km


The media in this post is not displayed to visitors. To view it, please log in.

For those who haven’t been following along, [BPS.space] aka [Joe] is on a journey to launch a home-built rocket past the Kármán line where it will officially reach outer space. But one does not simply launch a rocket to outer space on the first try. The process is long and involves not only building a series of rockets, but designing and building propellant mixtures, solving aerodynamic problems, gaining several model rocket certifications along the way, and a whole host of other steps. He’s also documenting the entire process on video as well, which involves some custom camera work like this rocket selfie camera which will take an image of his rockets at apogee.

Like most problems in high-power rocketry, extremely tiny problems have a way of causing catastrophic failure, so every detail needs to be considered and planned for in the final design. For a camera that needs to jettison itself from the rocket at a precise moment after experiencing an incredible amount of forces, this is a complicated problem to solve. The initial design involves building a sled for a small deconstructed GoPro which uses springs and a servo to launch itself out of the rocket. The major problem with the design is that even the smallest torque on the sled will cause the camera to point in a random direction by the time it’s far enough from the rocket to take a picture. [Joe] tried a number of design iterations but could not get these torques to vanish.

One of the design limitations with this camera is that it won’t have any sort of parachute or tether itself to the rocket, so it will hit the ground at its terminal velocity. To keep that velocity down and improve survivability chances of the footage, the mass has to stay low. Eventually he settled on a semi-active control system by mounting a brass weight on a small motor, giving the camera module enough stability to stay pointed at the rocket long enough to take the video. Even though it hasn’t flown yet, admitting his first design wasn’t working at compromising on this solution which adds a bit of mass seems to be a good design change. We’ve been following along with his entire process so be sure to check out his actual rocket motor builds and teardowns as well.

youtube.com/embed/G61T-5d9jiA?…


hackaday.com/2026/04/22/photog…

Autonomous Coin Flipper Flips Expensive Coin


The media in this post is not displayed to visitors. To view it, please log in.

[Térence Grover] had a very special coin—a €1,000 commemorative piece only available to Monégasque nationals. If you want to flip one, normally you’d have to go snatch one up from somebody in Monaco—or you could just do it online!

Yes, he built an automated online coin flipper to flip this very special piece of coinage. A 12-volt solenoid is fired to flip the coin into the air. It then lands on its 3D-printed tray, where a Raspberry Pi-based computer vision system built with OpenCV and a TFLite model classifies whether the result is heads or tails via a machine learning algorithm. An iris mechanism operated by servo motor then centers the coin on the tray, so it sits back over the solenoid, ready to flip once again. [Térence] was eventually able to refine this simple homemade build to the point that it ran autonomously for a full 50,000 flips on a livestream without issue.

The mechanism in this build is not dissimilar to a coin flipper we’ve seen before. We’ve also explored the statistics involved, too. Video after the break.

youtube.com/embed/wyTiC2gsJaY?…


hackaday.com/2026/04/22/autono…

Cybersecurity & cyberwarfare ha ricondiviso questo.

NEW: The French government has disclosed a data breach at the agency that manages national IDs and passports.

Stolen data could include full names, dates and places of birth, mailing and email addresses, and phone numbers.

The number of affected individuals is unclear at this point.

techcrunch.com/2026/04/22/fran…

Cybersecurity & cyberwarfare ha ricondiviso questo.

NEW: Apple fixed the bug that law enforcement agencies, like the FBI, were taking advantage of to extract chat messages that had been deleted or disappeared automatically.

Until now the iPhone stored deleted or disappered messages in a database, allowing authorities to access them with forensic tools.

techcrunch.com/2026/04/22/appl…

reshared this

Cybersecurity & cyberwarfare ha ricondiviso questo.

Ironia della sorte: i dipendenti di Meta sono scontenti di dover installare software di sorveglianza sui PC aziendali.

Che strano: Meta, l'azienda fondata sul monitoraggio di ogni attività online dei suoi miliardi di utenti per indurli a cliccare su contenuti provocatori e pubblicità mirate, ha bisogno di registrare i tasti premuti dai dipendenti per sviluppare la sua IA e starebbe installando software di sorveglianza sui computer aziendali dei dipendenti

theregister.com/2026/04/22/met…

@informatica

Cybersecurity & cyberwarfare ha ricondiviso questo.

NIST is updating SP 800-133, which details the "FIPS approved" ways to generate keys.

There's a lot of good news in it, it approves a lot of stuff we were doing, like X-Wing seed derivation and c2sp.org/det-keygen.

Here are my comments: leaflet.pub/f6fc0b3b-161d-4e35…

reshared this

Cybersecurity & cyberwarfare ha ricondiviso questo.

#DDoS wave continues as #Mastodon hit after Bluesky incident
securityaffairs.com/191144/cyb…
#securityaffairs #hacking

FLOSS Weekly Episode 868: Remove the Noodles


The media in this post is not displayed to visitors. To view it, please log in.

This week Jonathan chats with Johannes Millan about Super Productivity and Parallel Code! Those are two very different projects, but both aiming for helping us get our work done. Super Productivity is a scheduling and time tracking suite, while Parallel Code is an almost-IDE for managing and isolating AI coding agents. This episode has something for everybody, so check it out!


youtube.com/embed/TYu7mxevrD4?…

Did you know you can watch the live recording of the show right on our YouTube Channel? Have someone you’d like us to interview? Let us know, or have the guest contact us! Take a look at the schedule here.

play.libsyn.com/embed/episode/…

Direct Download in DRM-free MP3.

If you’d rather read along, here’s the transcript for this week’s episode.

Places to follow the FLOSS Weekly Podcast:


Theme music: “Newer Wave” Kevin MacLeod (incompetech.com)

Licensed under Creative Commons: By Attribution 4.0 License


hackaday.com/2026/04/22/floss-…

AI For The Skeptics: The Universal Function For Some Things Only


The media in this post is not displayed to visitors. To view it, please log in.

It’s a phrase we use a lot in our community, “Drink the Kool-Aid”, meaning becoming unreasonably infatuated with a dubious idea, technology, or company. It has its origins in 1960s psychedelia, but given that it’s popularly associated with the mass suicide of the followers of Jim Jones in Guyana, perhaps we should find something else. In the sense we use it though, it has been flowing liberally of late with respect to AI, and the hype surrounding it. This series has attempted to peer behind that hype, first by examining the motives behind all that metaphorical Kool-Aid drinking, and then by demonstrating a simple example where the technology does something useful that’s hard to do another way. In that last piece we touched upon perhaps the thing that Hackaday readers should find most interesting, we saw the LLM’s possibility as a universal API for useful functions.

It’s Not What An LLM Can Make, It’s What It Can Do


When we program, we use functions all the time. In most programming languages they are built into the language or they can be user-defined. They encapsulate a piece of code that does something, so it can be repeatedly called. Life without them on an 8-bit microcomputer was painful, with many GOTO statements required to make something similar happen. It’s no accident then that when looking at an LLM as a sentiment analysis tool in the previous article I used a function GetSentimentAnalysis(subject,text) to describe what I wanted to do. The LLM’s processing capacity was a good fit to my task in hand, so I used it as the engine behind my function, taking a piece of text and a subject, and returning an integer representing sentiment. The word “do” encapsulates the point of this article, that maybe the hype has got it wrong in being all about what an LLM can make. Instead it should be all about what it can do. The people thinking they’ve struck gold because they can churn out content slop or make it send emails are missing this.
It's a fake pseudocode function for adding two numbers by calling an LLM. The return variable is the poop emoji.Please don’t hate me for this.
So we have an LLM, even a small one on our own computer, and looking at it in that light it’s immediately apparent that it can become a function to do almost any processing task, if you wrap the right prompt and API call in a function definition. Of course that’s dangerous, because if I may I would like to coin a new phrase: function slop.

As an example I can call an LLM to do simple numerical addition and it will perform the task, but doing so would be utterly pointless given the existence of the + operator. If you are going to use an LLM to perform a processing function it’s important that it be a function where doing so makes sense, otherwise your function is just function slop. A quick web search tells me that function slop is not yet a thing, so I would like to take this moment to apologise for what I may have unleashed upon the world.

Function slop aside though, using the LLM to do a processing task where it makes sense, shouldn’t be ignored as a useful tool. These things are very good at summarising and categorising information in the way a human might do it, a task that’s often hard in traditional programming, so if the job in hand fits those capabilities then it makes sense to use them.

This has been a three-part series, and unlike Star Wars or The Hitchhikers Guide To The Galaxy, it’s probably going to stay that way. I hope that in our explanation we’ve successfully looked beyond the hype and found something useful in all this. It’s odd though, as the one writing it you might think I would be bubbling over with new ideas, but aside from the previous article’s sentiment analysis I still find myself with not much I find the need to use an LLM for. Which is maybe the point, it’s one thing to know a bit about them, but just because they’re there doesn’t mean you have to use them.


hackaday.com/2026/04/22/ai-for…

Cybersecurity & cyberwarfare ha ricondiviso questo.

New: Cosmetics giant Rituals has confirmed a data breach involving its customer membership database. Won't say how many customers had personal information stolen (names, addresses, phone numbers, and more) but its website says it has 41M+ total customers.

Breach affects EU, UK and US customers.

techcrunch.com/2026/04/22/cosm…

reshared this

ACN: a marzo l’obbligo di notifica NIS2 rende visibili gli incidenti cyber


@Informatica (Italy e non Italy)
L’aumento degli incidenti registrati da ACN non racconta un peggioramento della sicurezza, ma segnala che finalmente li stiamo vedendo. Ecco i dati salienti del report mensile dell'ACN nel mese di marzo 2026 e qual è il passaggio più critico
L'articolo ACN: a marzo l’obbligo di

Cybersecurity & cyberwarfare ha ricondiviso questo.

The media in this post is not displayed to visitors. To view it, please go to the original post.

12 tecniche per ottimizzare le query PostgreSQL su dataset di grandi dimensioni
#tech
spcnet.it/12-tecniche-per-otti…
@informatica


12 tecniche per ottimizzare le query PostgreSQL su dataset di grandi dimensioni


Quando una tabella PostgreSQL cresce oltre il milione di righe, query che prima restituivano risultati in millisecondi iniziano ad impiegare secondi — o peggio. La buona notizia è che PostgreSQL offre strumenti potenti per affrontare questo problema. La cattiva notizia è che molti sviluppatori conoscono solo una parte di questi strumenti.

In questo articolo passiamo in rassegna le 12 tecniche più efficaci per ottimizzare le query su grandi dataset, con esempi SQL concreti per ciascuna.

1. Creare indici sulle colonne frequentemente filtrate


Il consiglio più noto, ma non per questo meno importante. Un indice trasforma una scansione sequenziale (O(n)) in una ricerca B-tree (O(log n)). La differenza su una tabella da un milione di righe può essere di due ordini di grandezza.

-- Prima: full sequential scan su ordini
SELECT * FROM orders WHERE customer_id = 42;

-- Creazione dell'indice
CREATE INDEX idx_orders_customer_id ON orders(customer_id);

-- Dopo: index scan, da 240ms a pochi ms

Usate EXPLAIN ANALYZE per verificare che l’indice venga effettivamente utilizzato.

2. Normalizzare il database in modo strategico


La normalizzazione riduce la ridondanza e migliora la coerenza dei dati, ma va applicata con giudizio. Una normalizzazione eccessiva crea decine di JOIN che possono diventare colli di bottiglia. La regola pratica: normalizzate i dati che cambiano spesso o che hanno alta cardinalità (liste di prodotti, clienti, categorie), denormalizzate i dati storici o di report dove la velocità di lettura è critica.

3. Evitare SELECT *


Selezionare tutte le colonne ha due costi nascosti: aumenta il volume di I/O e impedisce a PostgreSQL di soddisfare la query direttamente dall’indice (index-only scan). Specificate sempre le colonne necessarie:

-- Evitare
SELECT * FROM orders WHERE customer_id = 42;

-- Preferire
SELECT id, created_at, total_amount FROM orders WHERE customer_id = 42;

Quando le colonne selezionate fanno parte di un indice composito, PostgreSQL può restituire i dati senza accedere all’heap, eliminando un intero livello di I/O.

4. Ordinare i JOIN in modo efficiente


Il query planner moderno di PostgreSQL determina autonomamente l’ordine ottimale dei JOIN grazie al cost-based optimizer. Tuttavia, in scenari con molte tabelle o con join_collapse_limit ridotto, conviene strutturare i JOIN in modo che le tabelle più piccole (o più filtrate) vengano processate per prime, riducendo la cardinalità delle operazioni successive.

5. Usare LIMIT durante l’esplorazione dei dati


Apparentemente ovvio, ma spesso trascurato: se l’interfaccia utente mostra al massimo 50 risultati, non ha senso recuperarne un milione dal database.

SELECT id, name, email 
FROM customers 
ORDER BY created_at DESC 
LIMIT 50 OFFSET 0;

Attenzione al pagination problem: con OFFSET elevati, PostgreSQL scansiona comunque tutte le righe precedenti. Per paginazione su grandi dataset, preferite il keyset pagination (cursor-based).

6. Indici parziali per subset frequenti


Un indice parziale indicizza solo le righe che soddisfano una condizione, riducendo dimensioni e costo di manutenzione:

-- Indice solo sugli ordini completati (subset più frequentemente interrogato)
CREATE INDEX idx_completed_orders
ON orders(customer_id)
WHERE status = 'Completed';

-- La query deve includere la stessa condizione per usare l'indice
SELECT id, total_amount 
FROM orders 
WHERE customer_id = 42 AND status = 'Completed';

In un test pratico, questo indice ha dimezzato i tempi rispetto a un indice standard su tutte le righe.

7. Usare i tipi di dato più piccoli necessari


Ogni byte conta quando moltiplicato per milioni di righe. Preferite sempre il tipo più compatto che soddisfa il requisito:

  • integer (4 byte) invece di bigint (8 byte) per chiavi primarie < 2 miliardi
  • smallint (2 byte) per enumerazioni con pochi valori
  • timestamp invece di timestamptz se il fuso orario è fisso
  • varchar(n) con limite appropriato invece di text illimitato dove possibile

Tipi più piccoli significano pagine di dati più dense, quindi meno I/O per ogni query.

8. Non applicare funzioni sulle colonne indicizzate


Applicare una funzione a una colonna indicizzata invalida l’utilizzo dell’indice:

-- L'indice su name NON viene usato
SELECT * FROM customers WHERE LOWER(name) = 'mario rossi';

-- Soluzione: creare un indice funzionale
CREATE INDEX idx_customers_lower_name ON customers(LOWER(name));

-- Ora l'indice viene usato
SELECT * FROM customers WHERE LOWER(name) = 'mario rossi';

Lo stesso vale per funzioni su date come DATE(created_at): usate range di timestamp o create l’indice sulla funzione.

9. Partizionare le tabelle molto grandi


Il partizionamento divide una tabella logica in sotto-tabelle fisiche, permettendo a PostgreSQL di escludere partizioni irrilevanti (partition pruning) durante le query:

-- Tabella partizionata per anno
CREATE TABLE orders_partitioned (
    id         serial NOT NULL,
    customer_id integer,
    created_at  timestamp NOT NULL,
    CONSTRAINT pk_orders PRIMARY KEY (id, created_at)
) PARTITION BY RANGE (created_at);

-- Creazione delle partizioni annuali
CREATE TABLE orders_2024 PARTITION OF orders_partitioned
    FOR VALUES FROM ('2024-01-01') TO ('2025-01-01');

CREATE TABLE orders_2025 PARTITION OF orders_partitioned
    FOR VALUES FROM ('2025-01-01') TO ('2026-01-01');

Una query che filtra per anno legge solo la partizione corrispondente, ignorando completamente le altre.

10. Usare le transazioni per operazioni bulk


PostgreSQL esegue un commit (e quindi una scrittura sincrona su WAL) dopo ogni statement. Raggruppare più operazioni in un’unica transazione riduce drasticamente i costi di I/O:

-- Lento: un commit per ogni INSERT
INSERT INTO log_events VALUES (...);
INSERT INTO log_events VALUES (...);
-- ... x 10.000

-- Veloce: un solo commit per tutto il batch
BEGIN;
INSERT INTO log_events VALUES (...);
INSERT INTO log_events VALUES (...);
-- ... x 10.000
COMMIT;

In test pratici, l’approccio con transazione singola completa lo stesso lavoro in meno della metà del tempo rispetto agli inserimenti individuali.

11. Evitare transazioni long-running


Il modello MVCC (Multi-Version Concurrency Control) di PostgreSQL mantiene versioni multiple delle righe per garantire la consistenza delle letture. Le transazioni long-running bloccano il processo di VACUUM dal rimuovere le versioni obsolete, causando table bloat: tabelle che crescono fisicamente anche quando i dati logici non aumentano.

Spezzettate le operazioni pesanti in batch più piccoli e monitorate le transazioni attive con:

SELECT pid, now() - pg_stat_activity.query_start AS duration, query, state
FROM pg_stat_activity
WHERE state != 'idle' AND query_start IS NOT NULL
ORDER BY duration DESC;

12. Gestire il bloat con VACUUM


Ogni UPDATE e DELETE lascia righe “morte” sul disco. VACUUM le recupera:

-- VACUUM standard: recupera spazio senza bloccare le letture
VACUUM orders;

-- VACUUM FULL: recupera tutto lo spazio ma blocca l'accesso alla tabella
-- Usare solo in finestre di manutenzione programmate
VACUUM FULL orders;

-- Verificare lo stato del bloat
SELECT relname, n_dead_tup, n_live_tup,
       round(n_dead_tup::numeric / NULLIF(n_live_tup + n_dead_tup, 0) * 100, 2) AS dead_pct
FROM pg_stat_user_tables
ORDER BY n_dead_tup DESC
LIMIT 20;

Per la maggior parte dei workload, autovacuum è sufficiente. Assicuratevi che sia abilitato e calibrate i threshold in base al volume di modifiche della vostra applicazione:
-- Verificare la configurazione autovacuum per una tabella specifica
SELECT reloptions FROM pg_class WHERE relname = 'orders';

Riepilogo operativo


Non tutte le tecniche si applicano a ogni scenario. Un approccio efficace inizia sempre dall’analisi con EXPLAIN (ANALYZE, BUFFERS) per identificare i reali colli di bottiglia, poi applica le ottimizzazioni in modo mirato. L’indice sbagliato o il partizionamento mal configurato possono peggiorare le prestazioni invece di migliorarle.

Il punto di partenza universale resta lo stesso: misurare prima, ottimizzare dopo.


Fonte: 12 practices for optimizing PostgreSQL queries for large datasets — elmah.io Blog


Repairing a Mercedes EQC 300 BEV Battery


The media in this post is not displayed to visitors. To view it, please log in.

When [OGS Mechanics] got a Mercedes EQC 300 battery-electric car in for repair, it was found to have a bit of a weird issue: after sitting in a garage for a while, its range on battery had suddenly reduced significantly without clear cause. Although the typical response here is to just mark the battery pack as ‘faulty’ and replace the whole unit, [OGS] decided to dig into the pack to see what was going on.

The short version is that this particular battery pack consists of two individual batteries, each with its own BMS, one of which had reported a condition to the master BMS that triggered the ‘replace battery module’ error observed with the scan tool. From this it could also be seen that the first battery was at a 10% state-of-charge (SoC), and the second at 95%, making them incredibly unbalanced. Unfortunately the dealer procedure to rebalance did not work here, with only the second battery wanting to charge even after draining both to the same initial level.

To diagnose the underlying issue in earnest required gently prying open the battery pack like a massive glued-shut smartphone. Going by the theory that it is a software glitch, since the first battery was still at a healthy voltage level, it was decided to manually charge it. With both batteries now fully charged, the BMS for the first battery was then removed to have its memory overwritten with that of a known good BMS module, clearing the ‘replace battery module’ error.

Although in the preview for the next video it’s hinted that there’s also an internal balancing issue in the first battery pack, this could be another symptom of its BMS glitching out. Either way, it would seem that BEVs battery modules are both heavily dependent on software, as well as afflicted by the same throw-away culture that has people just buying a new smartphone when the battery fails.

youtube.com/embed/dgwQJJvl77w?…


hackaday.com/2026/04/22/repair…

Cybersecurity & cyberwarfare ha ricondiviso questo.

The media in this post is not displayed to visitors. To view it, please go to the original post.

Nel romanzo di Alfred Bester "Destinazione stelle" gli esseri umani hanno colonizzato l'intero Sistema Solare e stanno per partire verso le stelle. Il libro esce nel 1956: l'anno seguente, con lo Sputnik 1, si apre anche nella realtà l'era dell'esplorazione spaziale, un'impresa che fino a quel momento viveva soltanto nelle pagine della fantascienza e negli occhi dei bambini di fronte al cielo notturno.

Se in questi settant'anni l'umanità ha cominciato a dar corpo a quei sogni, è stato grazie al talento, al coraggio e alla tenacia di donne e uomini non sempre ricordati quanto meriterebbero: figure come le calcolatrici umane della NASA, gli ingegneri del programma sovietico, le programmatrici dell'Apollo, i tecnici dimenticati di mille altre missioni.

Qui racconterò le loro storie. Seguimi! 🚀

#Spazio #Astronomia #Fantascienza #StoriaDellaScienza #EsplorazioneSpaziale

@astronomia

Questa voce è stata modificata (2 mesi fa)
Cybersecurity & cyberwarfare ha ricondiviso questo.

Ciao!

Mi sono trasferito da @andrea_ferrero per raccontare qui le mie storie di spazio.

Continuerò a usare il vecchio profilo per i post personali.

@astronomia

Questa voce è stata modificata (2 mesi fa)
Cybersecurity & cyberwarfare ha ricondiviso questo.

Ecosia pianta 250 milioni di alberi grazie al suo motore di ricerca


reshared this

Cybersecurity & cyberwarfare ha ricondiviso questo.

The media in this post is not displayed to visitors. To view it, please go to the original post.

Europa: Sovranità Digitale o "Sindrome di Stoccolma" Tecnologica?

Europa, sappi essere coerente! O costruiamo davvero un'infrastruttura nostra, o smettiamo di lamentarci dello spionaggio mentre carichiamo i verbali del Consiglio UE su un server a Langley.

#redhotcyber #meme4cyber #meme #clodu #europa #digitale #cyber #hacking #hacker #infosec

reshared this

Cybersecurity & cyberwarfare ha ricondiviso questo.

U.K. intelligence says at least 100 countries now have access to government spyware, up from around 80 countries in 2023. The rise shows that spyware continues to proliferate and that the bar to obtaining spyware is lower.

techcrunch.com/2026/04/22/uk-g…

reshared this

What Have We Dumped on the Moon?


The media in this post is not displayed to visitors. To view it, please log in.

If you read a headline that signs of intelligent life were found on the moon, you might suspect a hoax. But they are there! Humans have dumped a lot of stuff on the moon, both in person and via uncrewed rockets. So after the apocalypse, what strange things will some alien exo-archaeologist find on our only natural satellite?

The Obvious


Of course, we’ve left parts of rockets, probes, and rovers. Only the top part of the Apollo Lunar Excursion Module left the moon. (See for yourself in the Apollo 17 ascent video below.) The bottoms are still there, along with the lunar rovers and a bunch of other science instruments and tools. There are boots and cameras, as you might expect.

But what about the strange things? As of 2012, NASA compiled a list of all known lunar junk that originated on Earth. The list starts with material from the non-Apollo US programs like the Surveyor and Lunar Prospector missions. Next up is the Apollo stuff, which is actually quite a bit: an estimated 400,000 pounds, we’ve heard. This ranges from the entire descent stage and lunar overshoes to urine bags. There are even commemorative patches and a gold olive branch.

After that, the list shows what’s known to be on the surface from the Russian space program, along with objects of Chinese, Indian, Japanese, and European origin.

youtube.com/embed/9HQfauGJaTs?…

The Sentimental

An Apollo 1 patch made its way to the moon.
Charles Duke on Apollo 16 left a framed family photo on the Moon’s surface with an inscription on the back. We figure if you go looking for it now, the sun will have bleached it white, but we appreciate the sentiment.

There are several objects meant to commemorate fallen astronauts and cosmonauts, including an Apollo 1 mission patch. You may recall that a fire during training killed all three of Apollo 1’s crew.

Lunar Prospector brought a portion of the ashes of Gene Shoemaker, a geologist who trained Apollo astronauts, to the moon. The capsule of ashes holds a quote from Romeo and Juliet:

And, when he shall die

Take him and cut him out in little stars

And he will make the face of heaven so fine

That all the world will be in love with night,

And pay no worship to the garish sun.


A half-dollar-sized disc has 73 goodwill messages from world leaders.
To date, Shoemaker is the only person who has remains on the moon.

While not exactly sentimental, NASA did send a silicon disc to the moon with Apollo 11 containing goodwill messages from 73 countries. The whole thing is about the size of a US half dollar, so if you want to read the messages, you might be better off reading the associated document.

Making tiny silicon wafers with finely-detailed etchings was pretty high tech in the late 1960s. GCA Corp used a reduction camera to make a negative photomask containing all the letters plus an inscription around its edge at its final size. This mask was given to Sprague, who etched it.

The Odd


One of the strange things on the NASA list is a falcon feather. That was left by Apollo 15’s Davis Scott, who carried out the classic experiment of dropping a feather and a hammer to note that they fell at the same speed, even in the weak gravity of the moon. The feather was from Baggin, the Air Force Academy’s mascot, and remains on the lunar surface today.

youtube.com/embed/ZVfhztmK9zI?…

Speaking of Baggin, there are 96 bags of human waste sitting up there. Probably best not to bring that up the next time you and your partner are gazing at the romantic moon overhead.

The Unconfirmed


Forrest Myers created a small ceramic wafer with tiny artwork from six artists, like Andy Warhol, titled “Moon Museum.” The tile features six drawings, including a stylized “AW” (Warhol), a line (Robert Rauschenberg), a black square (David Novros), a diagram (John Chamberlain), Mickey Mouse (Claes Oldenburg), and an interlocking design (Myers). Apparently, Novros and Chamberlain were inspired by circuit diagrams of some kind.

Bell Labs created the wafer. However, NASA failed to approve the project, and Myers sought an alternative.

Reportedly, Myers gave the chip to an unnamed Apollo 12 engineer who affixed it to the leg of the lunar module. However, NASA has not confirmed this, so we don’t know for sure if it is up there or not. Perhaps if you get to the neighborhood, you can check it out and let us know?

To the Dump

Apollo 11 Landing Site Map from The Lunar Legacy Project (note “toss zone” to the left).
You might wonder why so much stuff was left, but if you think about it, it makes sense. The rockets can only bring back so much stuff. Every camera you leave behind means more moon rocks you can bring home. You can buy a new camera, but you can’t buy more moon rocks.

According to the Lunar Legacy Project, Apollo 11, and presumably the other missions, had designated toss zones. (We guess “dumps” didn’t sound good.)

If you are looking for a more up-to-date list, the Wikipedia article can help fill in the gaps, at least for vehicles. There’s been quite a bit added since the NASA list, including items from the UAE, Israel, and Luxembourg. Plus, there are many new additions from other countries.

With the advent of high-resolution orbital cameras, you can see some of the landing sites better than ever. For example, the video below shows the Apollo 17 site imaged by the Lunar Reconnaissance Orbiter Camera.

youtube.com/embed/LIui93E8kkE?…

Of course, we are on our way back to the moon, and so are other space programs. So there will probably be even more human debris on the moon soon. It is only a matter of time before lunar waste management becomes a hot topic.

Title image “Map of artificial objects on the Moon” by [Footy2000]


hackaday.com/2026/04/22/what-h…

Cybersecurity & cyberwarfare ha ricondiviso questo.

#Microsoft out-of-band updates fixed critical #ASP.NET Core privilege escalation flaw
securityaffairs.com/191130/hac…
#securityaffairs #hacking
Cybersecurity & cyberwarfare ha ricondiviso questo.

The media in this post is not displayed to visitors. To view it, please go to the original post.

Booking.com Notifies Customers of Data Breach Exposing Reservation Details and Personal Information
#CyberSecurity
securebulletin.com/booking-com…
Cybersecurity & cyberwarfare ha ricondiviso questo.

Critical #BRIDGE:BREAK flaws impact #Lantronix and #Silex #Technology converters
securityaffairs.com/191114/hac…
#securityaffairs #hacking
Cybersecurity & cyberwarfare ha ricondiviso questo.

The media in this post is not displayed to visitors. To view it, please go to the original post.

E se ZionSiphon riuscisse davvero ad avvelenare le acque di Israele?

📌 Link all'articolo : redhotcyber.com/post/e-se-zion…

A cura di Carolina Vivianti

#redhotcyber #news #malware #cybersecurity #hacking #siberattacchi #impiantidricoltura #israele

Cybersecurity & cyberwarfare ha ricondiviso questo.

The media in this post is not displayed to visitors. To view it, please go to the original post.

Al via le Truffe Booking: ora gli hacker conoscono i dettagli dei tuoi viaggi

📌 Link all'articolo : redhotcyber.com/post/truffe-bo…

A cura di Simone D'Agostino

#redhotcyber #news #violationedatipersonali #cybersecurity #hacking #malware #securityonline

ESP32 Hosts a Public Website


The media in this post is not displayed to visitors. To view it, please log in.

If you wanted to host a website, you could use any one of a number of online services, or spin up a server on a spare computer at home. If you’re a bit more daring, you could also do what [Tech1k] did, and run one on an ESP32 microcontroller.

The site in question is available (or at least, should be) at HelloESP.com. The first revision ran entirely on an ESP32, serving pages from a SPIFFS filesystem. The device was also fitted with a BME280 environment sensor and an OLED screen. It had an uptime of 500 days before the board failed.

The site has since been relaunched, running on a board that is framed on [Tech1k]’s wall. It runs on an ESP32-WROOM-32D, paired with a BME280 again, along with a CCS811 CO2 and air quality sensor and a DS3231 RTC for accurate timekeeping. The ESP32 is setup to hold an outbound WebSocket to a Cloudflare worker, with the Worker routing HTTP requests to the site via that route. This avoids the need for port forwarding for the ESP32 to be visible to the outside world, and the Cloudflare Worker will also serve a static version of the page in the case of WiFi dropouts or other temporary failures.

It’s true that this isn’t a completely unheard of project—microcontrollers have been working as simple web servers for a long time now. Still, [Tech1k] did a great job of making this as robust as possible and more like a real functional webserver rather than just something that runs on a local network to serve up a config page. That’s worthy of note.

You can run webservers on all kinds of chips these days, even the Raspberry Pi Pico. If you’re doing web stuff on something weird, you know we always wanna hear about it on the tipsline!


hackaday.com/2026/04/22/esp32-…

Cybersecurity & cyberwarfare ha ricondiviso questo.

The media in this post is not displayed to visitors. To view it, please go to the original post.

Windows Defender Triple Zero-Day: BlueHammer, RedSun, and UnDefend Actively Exploited in the Wild
#CyberSecurity
securebulletin.com/windows-def…
Cybersecurity & cyberwarfare ha ricondiviso questo.

The media in this post is not displayed to visitors. To view it, please go to the original post.

Critical Fortinet FortiClient EMS Zero-Day CVE-2026-35616 Exploited Before Official Patch Was Released
#CyberSecurity
securebulletin.com/critical-fo…
Cybersecurity & cyberwarfare ha ricondiviso questo.

The media in this post is not displayed to visitors. To view it, please go to the original post.

Creare addon nativi per Node.js con .NET Native AOT: addio a Python e node-gyp
#tech
spcnet.it/creare-addon-nativi-…
@informatica


Creare addon nativi per Node.js con .NET Native AOT: addio a Python e node-gyp


Da sempre, creare addon nativi per Node.js significava entrare nel mondo di C++ e node-gyp, con la necessità di installare Python, Visual Studio Build Tools e una serie di dipendenze che trasformavano il setup dell’ambiente in un’impresa. Il team di C# Dev Kit di Microsoft ha trovato una soluzione elegante: usare .NET Native AOT per produrre librerie condivise compatibili con l’interfaccia N-API di Node.js, scritte interamente in C#.

In questo articolo vediamo come funziona questa tecnica, analizzando la struttura del progetto, il meccanismo di interop e i punti critici da tenere d’occhio in produzione.

Perché Node.js supporta addon scritti in qualsiasi linguaggio


Un addon nativo per Node.js è semplicemente una libreria condivisa (.dll su Windows, .so su Linux, .dylib su macOS) che esporta un punto di ingresso preciso: la funzione napi_register_module_v1. Node.js carica la libreria, chiama questa funzione e da quel momento il modulo è disponibile per JavaScript.

L’interfaccia che rende tutto questo possibile è N-API (Node-API), una API C stabile e ABI-compatibile tra le versioni di Node.js. Questo significa che qualsiasi linguaggio in grado di produrre una shared library ed esportare una funzione C può diventare un addon Node.js — incluso C# compilato con Native AOT.

Configurazione del progetto .NET


Il file di progetto è sorprendentemente minimale:

<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <TargetFramework>net10.0</TargetFramework>
    <PublishAot>true</PublishAot>
    <AllowUnsafeBlocks>true</AllowUnsafeBlocks>
  </PropertyGroup>
</Project>

Due impostazioni chiave:
  • PublishAot: abilita la compilazione Ahead-of-Time, producendo una shared library nativa invece di un assembly IL.
  • AllowUnsafeBlocks: necessario per l’interop con N-API tramite function pointer e tipi non gestiti.


Il punto di ingresso del modulo


L’entry point usa l’attributo [UnmanagedCallersOnly], che istruisce il compilatore a generare una funzione C-callable con la firma esatta attesa da Node.js:

[UnmanagedCallersOnly(
    EntryPoint = "napi_register_module_v1",
    CallConvs = [typeof(CallConvCdecl)])]
public static nint Init(nint env, nint exports)
{
    // Registrazione delle funzioni esposte
    return exports;
}

Il tipo nint (native-sized integer) rappresenta gli handle opachi che N-API usa per riferirsi agli oggetti JavaScript. Non si tratta di puntatori diretti a memoria, ma di token gestiti dall’engine V8 tramite N-API.

Risoluzione delle funzioni N-API a runtime


Le funzioni N-API (come napi_create_string_utf8 o napi_get_cb_info) sono esportate direttamente da node.exe, non da una DLL separata. Per fare in modo che P/Invoke le risolva correttamente, si registra un custom resolver:

private static void Initialize()
{
    NativeLibrary.SetDllImportResolver(
        System.Reflection.Assembly.GetExecutingAssembly(),
        ResolveDllImport);
}

private static nint ResolveDllImport(string libraryName, Assembly assembly, DllImportSearchPath? searchPath)
{
    if (libraryName == "node")
        return NativeLibrary.GetMainProgramHandle();
    return IntPtr.Zero;
}

Questo permette di dichiarare le importazioni P/Invoke con [LibraryImport("node")] e averle risolte contro il processo host a runtime.

Marshalling delle stringhe UTF-8


Uno dei punti più delicati è la conversione tra stringhe JavaScript (UTF-16 internamente in V8, UTF-8 via N-API) e stringhe .NET. La strategia ottimale prevede:

  • Uso dello stack per stringhe piccole (≤512 byte) tramite stackalloc
  • Uso di ArrayPool<byte> per stringhe più grandi, evitando allocazioni sull’heap


private static string GetStringArg(nint env, nint info, int argIndex)
{
    // Recupera l'handle dell'argomento
    nint value = GetArgument(env, info, argIndex);
    
    // Prima chiamata: ottieni la dimensione necessaria
    nuint byteCount;
    napi_get_value_string_utf8(env, value, null, 0, out byteCount);
    
    // Allocazione efficiente in base alla dimensione
    if (byteCount <= 512)
    {
        Span<byte> buffer = stackalloc byte[(int)byteCount + 1];
        napi_get_value_string_utf8(env, value, buffer, (nuint)buffer.Length, out _);
        return Encoding.UTF8.GetString(buffer[..^1]);
    }
    else
    {
        byte[] buffer = ArrayPool<byte>.Shared.Rent((int)byteCount + 1);
        try
        {
            napi_get_value_string_utf8(env, value, buffer, (nuint)buffer.Length, out _);
            return Encoding.UTF8.GetString(buffer, 0, (int)byteCount);
        }
        finally
        {
            ArrayPool<byte>.Shared.Return(buffer);
        }
    }
}

Implementazione di una funzione reale: lettura dal Registry


L’esempio concreto mostrato dal team di Microsoft è un lettore del Windows Registry, che sostituisce il precedente addon C++:

private static nint ReadStringValue(nint env, nint info)
{
    try
    {
        var keyPath = GetStringArg(env, info, 0);
        var valueName = GetStringArg(env, info, 1);
        
        using var key = Registry.CurrentUser.OpenSubKey(keyPath, writable: false);
        
        return key?.GetValue(valueName) is string value
            ? CreateString(env, value)
            : GetUndefined(env);
    }
    catch (Exception ex)
    {
        // CRITICO: le eccezioni non gestite in [UnmanagedCallersOnly] crashano il processo
        ThrowError(env, $"Registry read failed: {ex.Message}");
        return 0;
    }
}

Attenzione: in un metodo [UnmanagedCallersOnly], le eccezioni non gestite provocano il crash dell’intero processo Node.js. Il pattern try/catch con ThrowError trasforma l’eccezione .NET in un errore JavaScript, mantenendo stabile il runtime.

Integrazione con TypeScript


Dopo dotnet publish, il file prodotto viene rinominato con estensione .node (convenzione Node.js) e caricato normalmente da TypeScript:

interface RegistryAddon {
    readStringValue(keyPath: string, valueName: string): string | undefined;
}

const registry = require('./native/win32-x64/RegistryAddon.node') as RegistryAddon;

const sdkPath = registry.readStringValue(
    'SOFTWARE\\dotnet\\Setup\\InstalledVersions\\x64\\sdk',
    'InstallLocation'
);
console.log(`SDK installato in: ${sdkPath}`);

Limiti e considerazioni


Questa tecnica ha un limite importante: Native AOT non supporta la cross-compilazione. Per ogni piattaforma target (Windows x64, Linux x64, macOS ARM64…) è necessario un ambiente di build separato. In pratica, questo si risolve con pipeline CI che eseguono la build su runner del sistema operativo corrispondente.

Esiste anche un’alternativa di più alto livello, node-api-dotnet, che astrae molti dei dettagli mostrati qui e supporta scenari più complessi come l’esposizione di interi namespace .NET a JavaScript. L’approccio “thin wrapper” descritto in questo articolo è preferibile quando si vuole controllo totale e dipendenze minime.

Conclusioni


L’integrazione tra .NET Native AOT e N-API apre uno scenario interessante per i team che già lavorano con C# e devono interfacciarsi con l’ecosistema Node.js. Eliminare Python e node-gyp dal setup semplifica notevolmente l’ambiente di sviluppo e unifica le competenze necessarie intorno a un unico SDK.

Il risultato è codice nativo con prestazioni paragonabili al C++, scritto con la produttività e la type safety di C# moderno, deployabile su Windows, Linux e macOS.


Fonte: Writing Node.js addons with .NET Native AOT — Microsoft .NET Blog, Drew Noakes