Debbie Clay

Debbie Clay

1589418602

How to create randomly generated backgrounds with the CSS Paint API

The CSS Paint API (aka CSS Custom Paint) enables developers to write JavaScript functions to draw images into CSS properties such as background-image, border-image, etc.

  • Introduction – 00:00
  • Getting started with the CSS Paint API – 02:01
  • Add the CSS paint() function – 02:50
  • Write an external paint worklet file – 03:20
  • Dynamic backgrounds with the CSS Paint API – 06:50
  • Creating randomly generated backgrounds – 09:20

The CSS Paint API (aka CSS Custom Paint) enables developers to write JavaScript functions to draw images into CSS properties such as background-image, border-image, etc. In this article, we’ll discuss the basics of the CSS Paint API and, specifically, how to create randomly generated backgrounds.

What is the CSS Paint API

The CSS Paint API is part of CSS Houdini, a set of low-level APIs that give developers direct access to the CSS Object Model (CSSOM). With Houdini, developers can create their own CSS features, even they are not implemented in the browsers.

Typically, we would add a background image to an element like this:

body {
  background-image: url('path/to/image.jpg');
}

This image is static. If you think technically, when the browser parses this CSS code, it sends an HTTP request to the URL and fetches the image. It then displays the image as the background image of body.

Unlike static images, you can use the CSS Paint API to create dynamic backgrounds. Keep reading to see how.

Getting started with the CSS Paint API

To begin using the CSS Paint API, start with the following steps.

  1. Add the CSS paint() function
  2. Write an external paint worklet file
  3. Invoke the worklet in the main thread

Before creating a dynamic background, let’s start with a simple static background composed of bubbles.

Static Background Composed of Bubbles

First, we need to establish an element to style. We’ll use a simple <div> element.

<!-- index.html -->
<div id="bubble-background"></div>

Step 1: Add the CSS paint() function

To use CSS Paint API for the background, add the paint() function to the background-image property of an element.

div#bubble-background {
  width:400px;
  height:200px;
  background-image: paint(bubblePaint);
}

bubblePaint is the worklet we’ll create in the next steps.

Step 2: Write an external paint worklet file

We need to keep the worklets in an external JavaScript file — we’ll call it bubble-paint.js.

// bubble-paint.js
registerPaint('bubblePaint', class {
  paint(ctx, geom) {
    const circleSize = 10; 
    const bodyWidth = geom.width;
    const bodyHeight = geom.height;

    const maxX = Math.floor(bodyWidth / circleSize);
    const maxY = Math.floor(bodyHeight / circleSize); 

    for (let y = 0; y < maxY; y++) {
      for (let x = 0; x < maxX; x++) {
        ctx.fillStyle = '#eee';
        ctx.beginPath();
        ctx.arc(x * circleSize * 2 + circleSize, y * circleSize * 2 + circleSize, circleSize, 0, 2 * Math.PI, true);
        ctx.closePath();
        ctx.fill();
      }
    }
  }
});

In this file, the registerPaint() function registers a paint worklet. The first parameter is the name of the worklet (same as the one we used in paint(bubblePaint)). The next parameter should be a class with the paint() method.

The paint() method is where we write the JavaScript code to render the image. Here we’ve used two arguments:

  1. ctx is similar to CanvasRenderingContext2D (the return value of canvas.getContext("2d")), though not identical. According to Google:

    A paint worklet’s context is not 100% the same as a <canvas> context. As of now, text rendering methods are missing and for security reasons you cannot read back pixels from the canvas.

  2. geom contains two elements: the width and height of the painting element

Inside the function, there is some logic to create the pattern. The ctx. functions are what we use to create canvases. If you are not familiar with canvases, I’d suggest you to go through this Canvas API tutorial.

Step 3: Invoke the worklet in the main thread

The next step is to invoke the worklet in the main JavaScript thread (usually in the HTML file).

Dynamic backgrounds with the CSS Paint API

Let’s make the color and size of the above bubbles dynamic. It’s pretty simple with CSS variables.

Step 1: Add CSS variables

div#bubble-background {
  --bubble-size: 40;
  --bubble-color: #eee;

  // other styles
}

Step 2: Use CSS variables

To use those CSS variables in the paint() method, we must first tell the browser we’re going to use it. This is done by adding the inputProperties() static attribute to the class.

// bubble-paint.js
registerPaint('bubblePaint', class {
  static get inputProperties() { return ['--bubble-size', '--bubble-color']; }

  paint() { /* */ }
});

We can access those properties from the third parameter of the paint() function.

paint(ctx, geom, properties) {
    const circleSize = parseInt(properties.get('--bubble-size').toString());
    const circleColor = properties.get('--bubble-color').toString(); 

    const bodyWidth = geom.width;
    const bodyHeight = geom.height;

    const maxX = Math.floor(bodyWidth / circleSize);
    const maxY = Math.floor(bodyHeight / circleSize); 

    for (let y = 0; y < maxY; y++) {
      for (let x = 0; x < maxX; x++) {
        ctx.fillStyle = circleColor;
        ctx.beginPath();
        ctx.arc(x * circleSize * 2 + circleSize, y * circleSize * 2 + circleSize, circleSize, 0, 2 * Math.PI, true);
        ctx.closePath();
        ctx.fill();
      }
    }
}

Dynamic Background Made With CSS Variables

That’s how easy it is to create dynamic backgrounds using the CSS Paint API.

This example on CodePen has two different backgrounds for desktop and mobile devices.

The trick is to change the variable values inside a media query.

@media screen and (max-width:600px) {
  div#bubble-background {
    --bubble-size: 20;
    --bubble-color: green; 
  }
}

Isn’t that cool? Imagine having static images — you need to have two different images hosted on a server to create those backgrounds. With the CSS Paint API, we can create an endless number of beautiful graphics.

Creating randomly generated backgrounds

Now that you’re comfortable using the CSS Paint API, let’s explore how we can create randomly generated backgrounds using the CSS Paint API.

The Math.random() function is the key to making randomly generated backgrounds.

Math.random()
// returns a float number inclusive of 0 and exclusive of 1

Here we are carrying out roughly the same process as we did earlier; the only difference is that we are using the Math.random function in the paint() method.

Let’s create a background with a random gradient.

body {
  width:100%;
  height:100%;
  background-image: paint(randomBackground);
}


registerPaint('randomBackground', class {
  paint(ctx, geom) {
    const color1 = getRandomHexColor();
    const color2 = getRandomHexColor();

    const gradient = ctx.createLinearGradient(0, 0, geom.width, 0);
    gradient.addColorStop(0, color1);
    gradient.addColorStop(1, color2);

    ctx.fillStyle = gradient;
    ctx.fillRect(0, 0, geom.width, geom.height);
  }
})

function getRandomHexColor() {
  return '#'+ Math.floor(Math.random() * 16777215).toString(16)
}

The getRandomHexColor function does the math part to create a random hex color. See this helpful tutorial for more details about how this works.

Here’s the final result of our random background. If you reload the page, you’ll see random gradients, which you can use to make unique and interesting webpages.

You’ll also notice that the colors change when you resize the browser window. That’s because the browser rerenders the background by calling the paint() method with different geom values upon resizing.

Although Math.random merely generates a simple, random number, it’s the most important function to know when creating any random background. The range of awesome things you can build using this method is limited only by your imagination.

Browser compatibility

As amazing as the CSS Paint API is, browser compatibility can be an issue. Only the most recent browser versions support it. Here’s the browser compatibility data from Is Houdini Ready Yet? as of this writing.

Houdini's Browser Compatibility

Judging by this data, it’s not yet a good idea to use Houdini in production. However, the Google Chrome Labs team created a polyfill that makes the CSS Paint API work in most browsers. Nevertheless, be sure to test dynamic backgrounds on all major browsers before using it in production.

Detecting browser support

Here’s how to detect browser support in JavaScript:

if ('paintWorklet' in CSS) {
  CSS.paintWorklet.addModule('bubble-paint.js');
}

And in CSS:

@supports (background: paint(id)) {
  div#bubble-background {
    width:400px;
    height:200px;
    background-image: paint(bubblePaint);
  }
}
>

Fallback

CSS fallback properties help improve browser support.

aside {
  background-image: url('/path/to/static/image');
  background-image: paint(bubblePaint);
}

Browsers that don’t support the paint() function won’t recognize that syntax. Therefore, it will ignore the second one and load the URL. Browsers that support it will understand both syntaxes, but the second one will override the first.

Other interesting use cases for CSS Paint API

Below are some other useful and exciting ways to use the CSS Paint API.

Image placeholder

With the CSS Paint API, we can draw a placeholder to display while an image is loading. This requires both Houdini’s new CSS Properties and the CSS Paint API.

Note that only a few browsers support the <image> syntax for CSS Properties, so it might not work in your browser.

Brush stroke background

I’ve seen countless business websites that use brush strokes to emphasis their marketing keywords. While it’s possible to create brush strokes using canvas, it’s much easier with the CSS Paint API.

Since it’s only CSS, you can change the variable and reuse the brush stroke as needed.

.another-brushstroke {
  --brush-color: #fff;
  background-image: paint(brushstroke);
}

Conclusion

In this guide, we covered the basics of the CSS Paint API and explored how to use it with some examples. You should now have the background you need to create more creative and dynamic images with this new API. Although we focused on background-image, you can use the paint() function in other properties too (e.g., border-image). The CSS Paint API, along with the other CSS Houdini features, represents the future of CSS, so now’s the time to get started.

#css #api #web-development

What is GEEK

Buddha Community

How to create randomly generated backgrounds with the CSS Paint API

Top 10 API Security Threats Every API Team Should Know

As more and more data is exposed via APIs either as API-first companies or for the explosion of single page apps/JAMStack, API security can no longer be an afterthought. The hard part about APIs is that it provides direct access to large amounts of data while bypassing browser precautions. Instead of worrying about SQL injection and XSS issues, you should be concerned about the bad actor who was able to paginate through all your customer records and their data.

Typical prevention mechanisms like Captchas and browser fingerprinting won’t work since APIs by design need to handle a very large number of API accesses even by a single customer. So where do you start? The first thing is to put yourself in the shoes of a hacker and then instrument your APIs to detect and block common attacks along with unknown unknowns for zero-day exploits. Some of these are on the OWASP Security API list, but not all.

Insecure pagination and resource limits

Most APIs provide access to resources that are lists of entities such as /users or /widgets. A client such as a browser would typically filter and paginate through this list to limit the number items returned to a client like so:

First Call: GET /items?skip=0&take=10 
Second Call: GET /items?skip=10&take=10

However, if that entity has any PII or other information, then a hacker could scrape that endpoint to get a dump of all entities in your database. This could be most dangerous if those entities accidently exposed PII or other sensitive information, but could also be dangerous in providing competitors or others with adoption and usage stats for your business or provide scammers with a way to get large email lists. See how Venmo data was scraped

A naive protection mechanism would be to check the take count and throw an error if greater than 100 or 1000. The problem with this is two-fold:

  1. For data APIs, legitimate customers may need to fetch and sync a large number of records such as via cron jobs. Artificially small pagination limits can force your API to be very chatty decreasing overall throughput. Max limits are to ensure memory and scalability requirements are met (and prevent certain DDoS attacks), not to guarantee security.
  2. This offers zero protection to a hacker that writes a simple script that sleeps a random delay between repeated accesses.
skip = 0
while True:    response = requests.post('https://api.acmeinc.com/widgets?take=10&skip=' + skip),                      headers={'Authorization': 'Bearer' + ' ' + sys.argv[1]})    print("Fetched 10 items")    sleep(randint(100,1000))    skip += 10

How to secure against pagination attacks

To secure against pagination attacks, you should track how many items of a single resource are accessed within a certain time period for each user or API key rather than just at the request level. By tracking API resource access at the user level, you can block a user or API key once they hit a threshold such as “touched 1,000,000 items in a one hour period”. This is dependent on your API use case and can even be dependent on their subscription with you. Like a Captcha, this can slow down the speed that a hacker can exploit your API, like a Captcha if they have to create a new user account manually to create a new API key.

Insecure API key generation

Most APIs are protected by some sort of API key or JWT (JSON Web Token). This provides a natural way to track and protect your API as API security tools can detect abnormal API behavior and block access to an API key automatically. However, hackers will want to outsmart these mechanisms by generating and using a large pool of API keys from a large number of users just like a web hacker would use a large pool of IP addresses to circumvent DDoS protection.

How to secure against API key pools

The easiest way to secure against these types of attacks is by requiring a human to sign up for your service and generate API keys. Bot traffic can be prevented with things like Captcha and 2-Factor Authentication. Unless there is a legitimate business case, new users who sign up for your service should not have the ability to generate API keys programmatically. Instead, only trusted customers should have the ability to generate API keys programmatically. Go one step further and ensure any anomaly detection for abnormal behavior is done at the user and account level, not just for each API key.

Accidental key exposure

APIs are used in a way that increases the probability credentials are leaked:

  1. APIs are expected to be accessed over indefinite time periods, which increases the probability that a hacker obtains a valid API key that’s not expired. You save that API key in a server environment variable and forget about it. This is a drastic contrast to a user logging into an interactive website where the session expires after a short duration.
  2. The consumer of an API has direct access to the credentials such as when debugging via Postman or CURL. It only takes a single developer to accidently copy/pastes the CURL command containing the API key into a public forum like in GitHub Issues or Stack Overflow.
  3. API keys are usually bearer tokens without requiring any other identifying information. APIs cannot leverage things like one-time use tokens or 2-factor authentication.

If a key is exposed due to user error, one may think you as the API provider has any blame. However, security is all about reducing surface area and risk. Treat your customer data as if it’s your own and help them by adding guards that prevent accidental key exposure.

How to prevent accidental key exposure

The easiest way to prevent key exposure is by leveraging two tokens rather than one. A refresh token is stored as an environment variable and can only be used to generate short lived access tokens. Unlike the refresh token, these short lived tokens can access the resources, but are time limited such as in hours or days.

The customer will store the refresh token with other API keys. Then your SDK will generate access tokens on SDK init or when the last access token expires. If a CURL command gets pasted into a GitHub issue, then a hacker would need to use it within hours reducing the attack vector (unless it was the actual refresh token which is low probability)

Exposure to DDoS attacks

APIs open up entirely new business models where customers can access your API platform programmatically. However, this can make DDoS protection tricky. Most DDoS protection is designed to absorb and reject a large number of requests from bad actors during DDoS attacks but still need to let the good ones through. This requires fingerprinting the HTTP requests to check against what looks like bot traffic. This is much harder for API products as all traffic looks like bot traffic and is not coming from a browser where things like cookies are present.

Stopping DDoS attacks

The magical part about APIs is almost every access requires an API Key. If a request doesn’t have an API key, you can automatically reject it which is lightweight on your servers (Ensure authentication is short circuited very early before later middleware like request JSON parsing). So then how do you handle authenticated requests? The easiest is to leverage rate limit counters for each API key such as to handle X requests per minute and reject those above the threshold with a 429 HTTP response. There are a variety of algorithms to do this such as leaky bucket and fixed window counters.

Incorrect server security

APIs are no different than web servers when it comes to good server hygiene. Data can be leaked due to misconfigured SSL certificate or allowing non-HTTPS traffic. For modern applications, there is very little reason to accept non-HTTPS requests, but a customer could mistakenly issue a non HTTP request from their application or CURL exposing the API key. APIs do not have the protection of a browser so things like HSTS or redirect to HTTPS offer no protection.

How to ensure proper SSL

Test your SSL implementation over at Qualys SSL Test or similar tool. You should also block all non-HTTP requests which can be done within your load balancer. You should also remove any HTTP headers scrub any error messages that leak implementation details. If your API is used only by your own apps or can only be accessed server-side, then review Authoritative guide to Cross-Origin Resource Sharing for REST APIs

Incorrect caching headers

APIs provide access to dynamic data that’s scoped to each API key. Any caching implementation should have the ability to scope to an API key to prevent cross-pollution. Even if you don’t cache anything in your infrastructure, you could expose your customers to security holes. If a customer with a proxy server was using multiple API keys such as one for development and one for production, then they could see cross-pollinated data.

#api management #api security #api best practices #api providers #security analytics #api management policies #api access tokens #api access #api security risks #api access keys

Autumn  Blick

Autumn Blick

1601381326

Public ASX100 APIs: The Essential List

We’ve conducted some initial research into the public APIs of the ASX100 because we regularly have conversations about what others are doing with their APIs and what best practices look like. Being able to point to good local examples and explain what is happening in Australia is a key part of this conversation.

Method

The method used for this initial research was to obtain a list of the ASX100 (as of 18 September 2020). Then work through each company looking at the following:

  1. Whether the company had a public API: this was found by googling “[company name] API” and “[company name] API developer” and “[company name] developer portal”. Sometimes the company’s website was navigated or searched.
  2. Some data points about the API were noted, such as the URL of the portal/documentation and the method they used to publish the API (portal, documentation, web page).
  3. Observations were recorded that piqued the interest of the researchers (you will find these below).
  4. Other notes were made to support future research.
  5. You will find a summary of the data in the infographic below.

Data

With regards to how the APIs are shared:

#api #api-development #api-analytics #apis #api-integration #api-testing #api-security #api-gateway

Queenie  Davis

Queenie Davis

1625931180

Drawing Graphics with the CSS Paint API

CSS Paint is an API that allows developers to programatically generate and draw graphics where CSS expects an image.

It is part of CSS Houdini, an umbrella term for seven new low-level APIs that expose different parts of the CSS engine and allows developers to extend CSS by hooking into the styling and layout process of a browser’s rendering engine.

It enables developers to write code the browser can parse as CSS, thereby creating new CSS features without waiting for them to be implemented natively in browsers.

Today we will explore two particular APIs, that are part of the CSS Houdini umbrella:

  1. CSS Paint, which at the time of writing this article, has been fully implemented in Chrome, Opera and Edge and is available in Firefox and Safari via a polyfill.
  2. CSS Properties and Values API, that will allow us to explicitly define our CSS variables, their initial values, what type of values they support and whether these variables can be inherited.

CSS Paint provides us with ability to render graphics using a PaintWorklet, a stripped down version of the CanvasRenderingContext2D. The major differences are:

  • No support for text rendering
  • No direct pixel access / manipulation

With these two omissions in mind, anything you can draw using canvas2d, you can draw on a regular DOM element using the CSS Paint API. For those of you who have done any graphics using canvas2d, you should be right at home.

Furthermore, we as developers have the ability to pass CSS variables as inputs to our PaintWorklet and control its presentation using custom predefined attributes.

This allows for a high degree of customisation, even by design people who may not be necessarily familiar with Javascript.

You can see more examples here and here. And with that out of the way, let’s get to coding!

Simplest example: two diagonal lines

Let’s create a CSS paintlet, that once loaded, will draw two diagonal lines across the surface of the DOM element we apply it to. The paintlet drawing surface size will adapt to the width and height of the DOM element and we will be able to control the diagonal line thickness by passing in a CSS variable.

  • Creating our PaintWorklet
  • Registering our CSS PaintWorklet
  • Referencing our paintlet as a CSS background
  • Particle Connections
  • Line Loop
  • Noise Button
  • Curvy dividers

#tutorials #css houdini #css paint api #css #api

An API-First Approach For Designing Restful APIs | Hacker Noon

I’ve been working with Restful APIs for some time now and one thing that I love to do is to talk about APIs.

So, today I will show you how to build an API using the API-First approach and Design First with OpenAPI Specification.

First thing first, if you don’t know what’s an API-First approach means, it would be nice you stop reading this and check the blog post that I wrote to the Farfetchs blog where I explain everything that you need to know to start an API using API-First.

Preparing the ground

Before you get your hands dirty, let’s prepare the ground and understand the use case that will be developed.

Tools

If you desire to reproduce the examples that will be shown here, you will need some of those items below.

  • NodeJS
  • OpenAPI Specification
  • Text Editor (I’ll use VSCode)
  • Command Line

Use Case

To keep easy to understand, let’s use the Todo List App, it is a very common concept beyond the software development community.

#api #rest-api #openai #api-first-development #api-design #apis #restful-apis #restful-api

Marcelle  Smith

Marcelle Smith

1598083582

What Are Good Traits That Make Great API Product Managers

As more companies realize the benefits of an API-first mindset and treating their APIs as products, there is a growing need for good API product management practices to make a company’s API strategy a reality. However, API product management is a relatively new field with little established knowledge on what is API product management and what a PM should be doing to ensure their API platform is successful.

Many of the current practices of API product management have carried over from other products and platforms like web and mobile, but API products have their own unique set of challenges due to the way they are marketed and used by customers. While it would be rare for a consumer mobile app to have detailed developer docs and a developer relations team, you’ll find these items common among API product-focused companies. A second unique challenge is that APIs are very developer-centric and many times API PMs are engineers themselves. Yet, this can cause an API or developer program to lose empathy for what their customers actually want if good processes are not in place. Just because you’re an engineer, don’t assume your customers will want the same features and use cases that you want.

This guide lays out what is API product management and some of the things you should be doing to be a good product manager.

#api #analytics #apis #product management #api best practices #api platform #api adoption #product managers #api product #api metrics