Sr. Content Developer at Microsoft, working remotely in PA, TechBash conference organizer, former Microsoft MVP, Husband, Dad and Geek.
166231 stories
·
33 followers

How to add license keys to an Electron app

1 Share

If you sell an Electron app, licensing needs two things: a way to activate a key once, and a check on every launch that still works offline. This post shows both with @keygrant/electron.

(Disclosure: we build KeyGrant. We made it because a new app usually has no customers yet, and licensing shouldn't cost you anything before you've sold a copy. It's free until your app takes off, with no hidden fees and no revenue share.)

What you need

  • A KeyGrant account (free up to 250 active licenses) and a product in the dashboard
  • A license key: issue one under Licenses > Issue a license, or create a test license
  • Node.js 20 or later. The SDK runs in Electron's main process, not in a renderer.

1. Install the SDK

npm install @keygrant/electron

2. Get your public key

Your app checks each license with your product's public key. Fetch it once and ship it with the app. The request needs no API key:

curl https://api.keygrant.dev/v1/products/my-product/pubkey
  • my-product is your product's API ID, the last part of its page's URL in the dashboard.
  • Keep the keys array from the response. You pass it to the SDK unchanged.
  • The dashboard's Signing key tab has a Copy key set button that copies the same thing.

3. Activate a key

Create one License for the process, and activate the key your customer enters:

import { License } from "@keygrant/electron";

const license = new License({
  product: "my-product",
  apiBaseUrl: "https://api.keygrant.dev",
  publicJwks: PUBLIC_KEYS, // the keys from step 2
  major: 1, // this build's major version
});

const result = await license.activate(userEnteredKey);
if (!result.ok) showActivationError(result.error);

activate checks the key with KeyGrant, takes one of the key's device seats for this machine, and stores a signed license (a JWT) on the device. When it fails, result.error says why, such as invalid-key or limit.

4. Check the license on every launch

async function checkLicense() {
  const status = await license.status();
  if (status.state === "licensed" || status.state === "trial") return; // run
  if (status.state === "unknown") {
    // The license file could not be read: keep running and check again shortly.
    setTimeout(checkLicense, 5_000);
    return;
  }
  // "expired" or "invalid": status.reason says why. "unlicensed": no key is stored yet.
  showActivationWindow(status);
}

checkLicense();

status() checks the stored license on the device and usually needs no network. When the license is close to its end, it renews it first, waiting at most 5 seconds for KeyGrant. If KeyGrant can't be reached, your app keeps working until the license runs out.

Selling it

Connect your Stripe account in the dashboard and pick the Stripe price for each license model. Each paid checkout then creates a key, with no code on your side. To have KeyGrant email the key to the buyer, choose KeyGrant sends them on the product's License delivery tab.

Your app's Buy button just opens your Stripe Payment Link:

import { shell } from "electron";

await shell.openExternal("https://buy.stripe.com/your-link");
// Once they have the key from the email:
const result = await license.activate(enteredKey);

Selling through Paddle instead? Its checkouts create keys the same way: https://keygrant.dev/docs/getting-started/paddle

Next

You can ship licensing on day one and pay nothing until you pass 250 active licenses. Questions welcome in the comments.

Read the whole story
alvinashcraft
3 minutes ago
reply
Pennsylvania, USA
Share this story
Delete

Building Your Own AI-First Design System

1 Share
Build an AI-first design system with an agent doing the legwork: inventory, tokens, components, voice, checks, and review, with a prompt for every step.
Read the whole story
alvinashcraft
5 minutes ago
reply
Pennsylvania, USA
Share this story
Delete

Microsoft names new comms chief: Chris Manzini, PepsiCo exec and Edelman vet

1 Share
Headshot of Chris Manzini, smiling, wearing clear-framed glasses and a navy sweater
Chris Manzini starts at Microsoft on Jan. 4, reporting to Vice Chair and President Brad Smith. (Microsoft Photo)

Microsoft named Chris Manzini, PepsiCo’s head of global communications, as its new chief communications officer, tapping an outsider but not a stranger to its business.

Before joining PepsiCo in December 2023, he spent about 20 years at the PR firm Edelman. By the end of that run he was president of Assembly, the agency Edelman built to work exclusively for Microsoft, and he led Edelman’s Microsoft business worldwide.

Manzini succeeds Frank X. Shaw, who took a similar path to the role. Shaw ran the Microsoft account at the agency now known as We. Communications before joining the company in 2009. He announced in September that he would leave after 17 years in-house.

The hiring of Manzini was announced internally Wednesday morning in an email from Brad Smith, Microsoft’s vice chair and president, who said the pick followed an extensive search. Smith credited Manzini with turning PepsiCo’s communications into a more integrated global team, and with pushing it forward in AI, data, digital and social media.

“Chris brings the exact mix of judgment, creativity, and experience that this moment requires, and I can’t wait for all of you to get to know him,” Smith wrote.

In a statement, Manzini said the AI era gives communicators a chance to earn trust and help shape business strategy, and that he “cannot imagine a more compelling place to pursue that ambition than Microsoft in this moment.”

One of his first challenges will be the ongoing aftermath from a global Microsoft 365 outage, which cut off Outlook email in more than 70 countries. CEO Satya Nadella opened Microsoft Ignite days later with an apology, telling customers, “We have work to do.”

Judson Althoff, CEO of Microsoft’s commercial business, told an investor conference Tuesday that the outage could cut year-over-year revenue growth for Microsoft 365 Commercial Cloud by 1 to 2 percentage points. CNBC put that at nearly $500 million in lost revenue.

“Our brand trades on trust, in fact, and not to mince words — we let the world down,” Althoff said.

Manzini starts Jan. 4 and will report to Smith. Microsoft restructured the function in September, after Shaw announced his plan to leave the company, moving communications out of its marketing group and into the corporate, external and legal affairs organization led by Smith.

In an internal memo at the time, Nadella described a media environment that is “increasingly fragmented and noisier than ever.”

He said he wants engineers, sellers, partners and others closest to Microsoft’s products and customers to become a bigger part of how the company tells its story.

In his memo Wednesday, Smith wrote that AI raises the bar on trust for Microsoft, which is why the company is bringing communications “closer to the heart of our strategy and business decisions.”

He thanked Shaw for his 17 years as CCO and nearly three decades of service to the company. Brent Colburn, Microsoft’s VP of global public affairs, has been interim communications chief since late September. Smith also thanked him for delaying a planned move to California to take on the role.

Read the whole story
alvinashcraft
5 minutes ago
reply
Pennsylvania, USA
Share this story
Delete

How do you build securely when AI is writing more of the code?

1 Share

Your agent has finished making a change. The tests pass, and the code looks plausible, but you don't have the time to closely review every line. How do you know what you're shipping is secure?

AI agents are accelerating software development, but they can also unintentionally introduce vulnerable code, expose secrets, or suggest nonexistent dependencies. As AI-generated code scales across repositories and languages, security becomes increasingly critical. From January to October 2026, GitHub detected over 200 million vulnerabilities, based on internal data. This represents a 100% increase year over year, underscoring the growing need to secure code at scale.

Keeping your application secure means checking code as you build, reviewing changes before they merge, and looking for risks across the wider project. That's why GitHub combines built-in security checks with different kinds of analysis and gives you ways to investigate findings and apply fixes where you're already coding.

Let's follow a change from the agent session to the pull request and the wider codebase. Along the way, you'll see how to build security into your own development workflow on GitHub. These aren't one-time checks or growing backlogs of findings. Instead, it's an ongoing process of finding vulnerabilities followed by evaluating and applying suggested fixes, without switching between disconnected tools.

The agent says it's done. What did it miss?

Just because an agent says it's finished the work doesn't mean it's safe. Your change can pass every test and still carry a security risk.

Consider an example where your agent updates a PHP search endpoint and builds the database query by inserting the search text directly into the SQL. Ordinary searches still work, so you'd only catch the problem by reading the code closely and asking why the agent built the query that way. But that search text could change the SQL itself and give attackers a way to access your data.

Reading every line to find a problem like this is slow, and these kinds of errors are easy to miss. A local security review can do that first pass for you. Before you open a pull request, run /security-review in the Copilot app, Copilot CLI, or Copilot Chat in VS Code on your active changes.

The review returns prioritized findings and remediation suggestions. It's focused on your local changes, not a full repository audit, and the review itself doesn't edit your code. You can ask Copilot to explain a finding or try a fix in your working copy.

For your PHP endpoint, the review could flag SQL injection. As a fix, it might suggest a parameterized query, which keeps the SQL instructions separate from the user's search value. You can then apply the fix and test that ordinary searches still work and crafted input can no longer alter the query.

Your pull request is open. What could still slip through?

While a local review is valuable, the pull request is the next checkpoint, and it has its own weak spot: reviewers can suggest and commit changes of their own, and any one of them could introduce a new risk. Your team still needs a check that runs on every pull request before code gets merged.

CodeQL is the foundation of GitHub Code Security's pull request checks. Complementary AI-powered scanning builds on that base, extending coverage to additional languages and vulnerability patterns.

These two kinds of analysis work in different ways:

  • CodeQL builds a database representing the code, then runs queries over that representation to identify potential problems. Its default query suite is designed for high precision and few false positives.
  • AI Scanning uses agents to explore the repository and reason about how the code works. Rather than relying only on predefined queries, it can investigate unfamiliar attack patterns and vulnerabilities in business logic, including in additional languages outside CodeQL's coverage.

In our example, PHP is one of those additional languages outside of CodeQL's coverage. AI Scanning checks the endpoint on the pull request and any findings come with suggested fixes for you or your reviewers to evaluate.

What about the code you didn't touch?

Pull request checks examine code that's new or changing, but they don't scan what's already there. Older code can go unchecked for months or years, and even code that appeared to be safe when it shipped may not hold up as attackers find new techniques.

In our example, an older part of the application builds database queries too, and nobody has changed it in months. It may carry the same kind of risk as the endpoint you just fixed, and no pull request will ever bring it up for review.

To look at code like that, if you have write access to a repository, you can run Standard AI Scan on its default branch.

The scan uses a proprietary harness with multiple models when available. Rather than reading every file in full, its agent searches the project and selects files and functions to examine within a time budget. It can examine languages CodeQL supports as well as those outside its coverage.

When the scan finishes, findings from the repository AI Scan appear alongside CodeQL alerts in the code scanning backlog. When CodeQL alerts already cover the same issue, AI Scan suppresses the duplicate findings.

From there, you can assign these alerts, link issues, include them in security campaigns, and use supported autofix workflows.

If you're working in the Copilot app, the GitHub security extension brings all code scanning alerts into a security canvas. You can find alerts, ask Copilot to explain them, and work on fixes without leaving the app. The same canvas supports the local security review we used earlier, so you can check new changes and act on existing alerts in one place.

The security canvas in the GitHub Copilot app showing local security review and code scanning findings

Your critical project warrants another look

For most work, the checks you've seen so far are enough. But regular scanning is built to work within practical limits, such as time and scope. In some situations, such as a major release or an audit, you can't afford to leave any stone unturned.

Suppose the example application is approaching a critical release. You've checked the endpoint and scanned the wider codebase, but the stakes of this release call for the most thorough investigation possible before shipping.

Deep Scan, which is powered by Microsoft's Codename MDASH and currently in private preview, is intended for higher-attention situations such as release testing and audits. Like Standard AI Scan, you run it on a repository with a click.

CodeQL, Standard AI Scan, and Deep Scan alerts all share the same backlog and come with fix suggestions. Agentic autofix works across all three, as well as partner tools, helping you turn findings into fixes within a shared workflow.

Build with security in the loop

Whether you're writing code yourself or working with an agent, these security checks help you evaluate what you're building from your first local change through to the codebase you maintain. You can use focused, local reviews while you build, complementary CodeQL and AI-powered analysis on pull requests, and broader, hybrid scans to look beyond what's recently changed, all within the same GitHub workflow.

No single green check certifies the whole codebase, but together, these approaches give you more chances to find issues and provide a clearer path from a finding to a fix you have reviewed.

FeatureWhen to use it
Local security review (/security-review)Review your active changes for vulnerabilities before opening a pull request.
CodeQL and AI ScanningCheck pull requests for vulnerabilities in new or changed code before merging.
Standard AI ScanScan your repository's default branch for risks in code that hasn't changed recently.
Deep ScanRun a more thorough scan for higher-attention situations, such as release testing or an audit.

Put security into your next change

Next time you work with an agent, run /security-review in the Copilot app, Copilot CLI, or Copilot Chat in VS Code to check your changes for vulnerabilities before opening a pull request.

The post How do you build securely when AI is writing more of the code? appeared first on The GitHub Blog.

Read the whole story
alvinashcraft
5 minutes ago
reply
Pennsylvania, USA
Share this story
Delete

Staff Engineers in the Age of AI: Rethinking Technical Leadership

1 Share

Artificial intelligence is transforming software engineering by accelerating code generation, testing, documentation, and architectural exploration. However, faster code delivery does not guarantee better software. As AI becomes integral to development, technical leaders must ensure that productivity gains do not compromise quality, critical thinking, or engineering ownership. Ultimately, when an AI-generated solution fails in production, responsibility remains with the engineers and the organization.

For Staff Engineers, this shift extends beyond adopting new tools. They must not only use AI effectively but also guide teams to question its outputs, understand trade-offs, recognize limitations, and make informed decisions. How can leaders scale teams without introducing new dependencies? How can they promote AI adoption while maintaining engineering judgment? This article examines the challenges, opportunities, and common pitfalls of technical leadership in the age of AI, focusing on how Staff Engineers can turn individual productivity gains into lasting team capabilities.

Read the whole story
alvinashcraft
6 minutes ago
reply
Pennsylvania, USA
Share this story
Delete

How to Use SQLAlchemy ORM to Work with Databases in Python

1 Share

Python applications often store their data in relational databases. When you write the SQL yourself, you also have to turn rows into objects, link related records, and protect queries against SQL injection. Each schema change then means finding and updating the affected queries by hand.

An Object Relational Mapper (ORM) takes much of this work off your hands by mapping Python classes to database tables. A class describes a table, an object stands for a row, and an attribute holds a column value. SQLAlchemy, a widely used Python database library, includes an ORM that writes the SQL for you and still lets you inspect it.

In this tutorial, you'll build a small library database with SQLAlchemy ORM. You'll define models, add and query records, load related data efficiently, and handle failed transactions. Let's get started!

You can get the Colab notebook for this tutorial and follow along.

Table of Contents

Prerequisites

To follow along, you'll need:

  • Python 3.11 or later
  • Familiarity with Python classes and type hints
  • Basic SQL knowledge: tables, primary keys, foreign keys, and joins
  • SQLAlchemy 2.1 or later in a virtual environment (the installation steps are covered next)

SQLAlchemy is the library your code will use, and SQLite is the database it will talk to. SQLite works through Python's built-in sqlite3 module, so you don't have to set up a database server.

How to Install SQLAlchemy

Create and activate a virtual environment:

python -m venv .venv
source .venv/bin/activate

On Windows, activate it with .venv\Scripts\activate. Then install SQLAlchemy:

pip install "sqlalchemy>=2.1"

The code in this tutorial was tested with SQLAlchemy 2.1.9. Create a file named main.py, and add each Python snippet to the bottom of it as you go.

How to Define Your Models

Every model inherits from a shared base class. Start by creating one:

from sqlalchemy import ForeignKey, String
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column, relationship


class Base(DeclarativeBase):
    pass

Base keeps a record of every table you declare through its subclasses.

How to Create the Author Model

Add an Author class:

class Author(Base):
    __tablename__ = "authors"

    id: Mapped[int] = mapped_column(primary_key=True)
    name: Mapped[str] = mapped_column(String(100))
    email: Mapped[str] = mapped_column(unique=True)

    books: Mapped[list["Book"]] = relationship(
        back_populates="author", cascade="all, delete-orphan"
    )

Let's parse the definition:

  • __tablename__ sets the name of the table.
  • Mapped[...] declares the Python type of each attribute.
  • mapped_column() adds database details such as the primary key, length, or a unique constraint.
  • relationship() links an author to a list of books. The cascade option saves, and deletes, those books along with their author.

How to Create the Book Model

Each book belongs to one author:

class Book(Base):
    __tablename__ = "books"

    id: Mapped[int] = mapped_column(primary_key=True)
    title: Mapped[str] = mapped_column(String(200))
    year: Mapped[int]
    rating: Mapped[float | None]
    author_id: Mapped[int] = mapped_column(ForeignKey("authors.id"))

    author: Mapped["Author"] = relationship(back_populates="books")

ForeignKey("authors.id") connects the two tables. The back_populates arguments keep both sides of the relationship in sync in Python.

The type hints also control nullability. year is a required column, while float | None allows rating to be empty.

Diagram showing the Author and Book Python classes mapped to the authors and books database tables, with a one-to-many relationship between the classes and a foreign key from books.author_id to authors.id. Created on diagrams.net (draw.io)

How to Connect to the Database

An engine manages connections to your database. Create one, then create the tables:

from sqlalchemy import create_engine

engine = create_engine("sqlite://")
Base.metadata.create_all(engine)

print(list(Base.metadata.tables))

Output:

['authors', 'books']

The URL sqlite:// creates an in-memory database, so every run starts fresh. To keep your data on disk, use sqlite:///library.db.

create_all() creates only the tables that don't exist yet. It leaves existing tables unchanged, so use a migration tool such as Alembic when your schema changes.

How to Add Records

You talk to the database through a session. Think of it as a shopping cart: you put objects in, and commit() is the checkout.

from sqlalchemy.orm import Session

ursula = Author(
    name="Ursula K. Le Guin",
    email="ursula@example.com",
    books=[
        Book(title="A Wizard of Earthsea", year=1968, rating=4.6),
        Book(title="The Dispossessed", year=1974, rating=4.8),
    ],
)

At this point, ursula is a regular Python object that exists only in memory. Create a second author:

octavia = Author(
    name="Octavia E. Butler",
    email="octavia@example.com",
    books=[Book(title="Kindred", year=1979)],
)

Now save both:

with Session(engine) as session:
    session.add_all([ursula, octavia])
    session.commit()
    print(ursula.id, octavia.id)

Output:

1 2

You added only the authors, and SQLAlchemy saved their books too. It also filled in each author_id for you.

The with block closes the session when you're done, even if an error occurs.

How to Query Data

To read data, build a statement with select() and run it through a session.

How to Filter and Sort Results

Fetch the books published after 1970, oldest first:

from sqlalchemy import select

stmt = select(Book).where(Book.year > 1970).order_by(Book.year)

with Session(engine) as session:
    for book in session.scalars(stmt):
        print(book.title, book.year)

Output:

The Dispossessed 1974
Kindred 1979

scalars() returns Book objects you can work with directly. If you're curious about the SQL, print the statement:

print(stmt)

Output:

SELECT books.id, books.title, books.year, books.rating, books.author_id 
FROM books 
WHERE books.year > :year_1 ORDER BY books.year

The :year_1 placeholder shows that the value travels separately from the SQL text. This protects your query against SQL injection.

How to Fetch a Single Record

Use get() for a primary key lookup. For any other condition that matches at most one row, use scalar_one_or_none():

with Session(engine) as session:
    first_book = session.get(Book, 1)
    print(first_book.title)

    stmt = select(Author).where(Author.email == "nobody@example.com")
    print(session.execute(stmt).scalar_one_or_none())

Output:

A Wizard of Earthsea
None

How to Join and Aggregate Tables

Suppose you want to count the books by each author. Join the tables and group the rows:

from sqlalchemy import func

stmt = (
    select(Author.name, func.count(Book.id))
    .join(Author.books)
    .group_by(Author.id)
    .order_by(Author.name)
)

join(Author.books) uses the relationship to work out the join condition. Since you're selecting individual columns, call execute() to get rows back:

with Session(engine) as session:
    for name, total in session.execute(stmt):
        print(f"{name}: {total}")

Output:

Octavia E. Butler: 1
Ursula K. Le Guin: 2

By default, SQLAlchemy loads a relationship when you first access it. This is called lazy loading.

To see its cost, add a query counter:

from sqlalchemy import event

queries = []


@event.listens_for(engine, "before_cursor_execute")
def track_query(conn, cursor, statement, *args):
    queries.append(statement)

The problem: loop over the authors and access their books.

with Session(engine) as session:
    for author in session.scalars(select(Author)):
        print(author.name, len(author.books))

print("Queries:", len(queries))

Output:

Ursula K. Le Guin 2
Octavia E. Butler 1
Queries: 3

One query fetched the authors, and each author triggered another. With 500 authors, you'd send 501 queries. This is the N+1 query problem.

The solution: ask for the books up front with selectinload().

from sqlalchemy.orm import selectinload

queries.clear()
stmt = select(Author).options(selectinload(Author.books))

with Session(engine) as session:
    for author in session.scalars(stmt):
        print(author.name, len(author.books))

print("Queries:", len(queries))

Output:

Ursula K. Le Guin 2
Octavia E. Butler 1
Queries: 2

The second query loads the books for all the authors in one batch. I generally go for selectinload() first for collections. For many-to-one links such as Book.author, joinedload() is a good fit.

How to Update and Delete Records

To update a row, load the object and change its attribute:

with Session(engine) as session:
    stmt = select(Book).where(Book.title == "Kindred")
    kindred = session.scalars(stmt).one()

    kindred.rating = 4.7
    session.commit()
    print(kindred.title, kindred.rating)

Output:

Kindred 4.7

The session tracks the change and sends an UPDATE statement when you commit.

To delete a row, pass the object to delete():

with Session(engine) as session:
    author = session.get(Author, 2)
    session.delete(author)
    session.commit()

    remaining = session.scalar(select(func.count(Book.id)))
    print("Books left:", remaining)

Output:

Books left: 2

Deleting Octavia also deleted Kindred, thanks to the cascade rule on Author.books.

No worries if you can't recall what cascade does. The cascade="all, delete-orphan" setting on Author.books tells SQLAlchemy that when you delete an author, it should delete that author's books too.

Before the deletion, the database has three books: Ursula wrote A Wizard of Earthsea and The Dispossessed, and Octavia wrote Kindred. The code deletes one author, Octavia, whose ID is 2, so SQLAlchemy also removes her only book, Kindred. Three books minus one leaves two, both by Ursula, which is why the output shows Books left: 2.

How to Handle Transactions

A transaction groups changes so that they all succeed or all fail.

The problem: add a new author along with an email address that's already taken.

duplicate = Author(name="Another Ursula", email="ursula@example.com")

with Session(engine) as session:
    session.add(duplicate)
    session.commit()

Output:

da6886e5-fc9e-4e71-9003-ff19faa6c25c

The solution: replace that last with block with the code below, which opens the transaction using session.begin() and catches the error.

from sqlalchemy.exc import IntegrityError

try:
    with Session(engine) as session, session.begin():
        session.add(Author(name="N. K. Jemisin", email="nora@example.com"))
        session.add(Author(name="Another Ursula", email="ursula@example.com"))
except IntegrityError:
    print("That email already exists. Nothing was saved.")

Output:

That email already exists. Nothing was saved.

session.begin() commits when the block succeeds and rolls back when it raises an exception. The first author in the block was valid, but the rollback discarded that insert too:

with Session(engine) as session:
    print(session.scalars(select(Author.name)).all())

Which is why you can't find N.K. Jemisin in the output:

['Ursula K. Le Guin']

If you call commit() yourself and want to keep using the same session after a failure, call session.rollback() first.

Conclusion

In this tutorial, you defined two related models, saved and queried records, fixed an N+1 problem, and rolled back a failed transaction.

The table below maps each task to the tool you used for it:

Task What to use
Define a table A subclass of Base with mapped_column()
Link two tables ForeignKey and relationship()
Add records session.add() or session.add_all()
Fetch by primary key session.get()
Fetch many objects session.scalars(select(...))
Fetch columns session.execute(select(...))
Load collections up front selectinload()
Delete a record session.delete()
Commit or roll back automatically session.begin()

The ORM is a good choice when your application creates, reads, and updates related objects. For large bulk operations or complex reports, SQLAlchemy Core or handwritten SQL gives you tighter control.

As a next step, switch the engine to a database file and add Alembic to manage schema changes. The official SQLAlchemy ORM documentation covers relationships and loading strategies in more depth. Keep learning!



Read the whole story
alvinashcraft
6 minutes ago
reply
Pennsylvania, USA
Share this story
Delete
Next Page of Stories