Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .fernignore
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ conformance/
scripts/
testapp/
src/cache/
src/context-signature.ts
src/core/fetcher/custom.ts
src/credits/
src/datastream/
Expand All @@ -35,6 +36,8 @@ tests/conformance/
tests/integration/
tests/races/
tests/unit/cache/local.test.ts
tests/unit/context-signature.test.ts
tests/unit/context-signing.json
tests/unit/credits/
tests/unit/datastream/datastream-client.test.ts
tests/unit/datastream/redis-key-layout.test.ts
Expand Down
31 changes: 31 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -649,6 +649,37 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)
}
```

## Context Signatures

A browser SDK uses a publishable key, which anyone can read from your page, so on its own it can't prove which company or user it's acting for. When an environment requires context signatures, the API only accepts a publishable-key request whose company and user your backend has signed with the environment's secret API key. The browser SDK asks your backend for the signature through its `getContextSignature` option and sends it in the `X-Schematic-Context-Sig` header.

### Signing a context

Sign the logged-in user's own company and user, read from your session. Don't sign whatever company or user the browser asks for, or anyone could get a signature for another company.

```ts
import express from "express";
import { signContext } from "@schematichq/schematic-typescript-node";

const app = express();

app.post("/api/schematic/sign", (req, res) => {
const session = getSession(req); // however your app identifies the logged-in user
if (!session) {
return res.status(401).json({ error: "Unauthorized" });
}

const signature = signContext(process.env.SCHEMATIC_SECRET_KEY!, {
company: { id: session.companyId },
user: { id: session.userId },
});

res.json({ signature });
});
```

The company and user keys must match the context you give the browser SDK exactly, or the API rejects the signature. A signature is valid for 10 minutes by default; set a different lifetime, up to an hour, with the `lifetimeSeconds` option. The browser SDK reuses a signature until shortly before it expires, then asks for a new one. `signContext` throws a `ContextSignatureError` when the secret is missing, the lifetime is out of range, or a key's value isn't a string.

## Caching

### Local Caching
Expand Down
155 changes: 155 additions & 0 deletions src/context-signature.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,155 @@
/**
* Signs the context a browser SDK sends with a publishable key, for
* environments that require context signatures.
*
* A publishable key is public, so the API can't trust the company and user a
* browser names with it. When the environment requires signatures, your
* backend, which holds the secret API key, signs the logged-in user's own
* company and user, and the browser SDK sends that signature in the
* X-Schematic-Context-Sig header. Sign the context from your own authenticated
* session, never from what the browser asks for.
*
* The signature is `iat.exp.sig`, where `sig` is the unpadded base64url
* HMAC-SHA256 of `canonical(context).iat.exp` keyed with the secret API key,
* and `canonical` is the context's JSON with keys sorted by code point and no
* whitespace.
*/

import * as crypto from "crypto";

/**
* Request header the browser SDK sends the signature in.
*/
export const CONTEXT_SIGNATURE_HEADER = "X-Schematic-Context-Sig";

/**
* How long a signature is valid for unless `lifetimeSeconds` says otherwise.
* It matches how long the browser SDK reuses one.
*/
export const DEFAULT_CONTEXT_SIGNATURE_LIFETIME_SECONDS = 600;

/**
* The longest the API accepts a signature as valid for.
*/
export const MAX_CONTEXT_SIGNATURE_LIFETIME_SECONDS = 3600;

/**
* The company and user a browser SDK checks flags and sends events for, by
* their keys. Leave one out when it's absent; an empty object is signed as
* empty. It must match the context the browser SDK is given exactly.
*/
export interface SignableContext {
company?: Record<string, string>;
user?: Record<string, string>;
}

export interface SignContextOptions {
/**
* When the signature is valid from; now by default. Counted in whole
* seconds.
*/
issuedAt?: Date;
/**
* How long the signature is valid for, in whole seconds, from 1 up to
* MAX_CONTEXT_SIGNATURE_LIFETIME_SECONDS.
*/
lifetimeSeconds?: number;
}

/**
* Error thrown when a context can't be signed.
*/
export class ContextSignatureError extends Error {
constructor(message: string) {
super(message);
Object.setPrototypeOf(this, ContextSignatureError.prototype);
this.name = "ContextSignatureError";
}
}

/**
* Returns the X-Schematic-Context-Sig value for a context.
* @param secret - The secret API key for the environment the browser SDK's publishable key belongs to.
* @param context - The logged-in user's company and user keys.
* @param options - When the signature is valid from, and for how long.
* @throws {ContextSignatureError} If the secret is missing, the lifetime is out of range, or a key's value isn't a string.
*/
export function signContext(secret: string, context: SignableContext, options: SignContextOptions = {}): string {
if (!secret) {
throw new ContextSignatureError("A secret API key is required to sign a context.");
}

const lifetime = options.lifetimeSeconds ?? DEFAULT_CONTEXT_SIGNATURE_LIFETIME_SECONDS;
if (!Number.isInteger(lifetime) || lifetime < 1 || lifetime > MAX_CONTEXT_SIGNATURE_LIFETIME_SECONDS) {
throw new ContextSignatureError(
`lifetimeSeconds must be a whole number from 1 to ${MAX_CONTEXT_SIGNATURE_LIFETIME_SECONDS}.`,
);
}

const issuedAt = options.issuedAt ?? new Date();
const iat = Math.floor(issuedAt.getTime() / 1000);
if (!Number.isFinite(iat)) {
throw new ContextSignatureError("issuedAt must be a valid date.");
}

return signContextAt(secret, context, iat, iat + lifetime);
}

/**
* Signs a context for an explicit `iat` and `exp`, in unix seconds. Exported
* for tests; use signContext.
* @internal
*/
export function signContextAt(secret: string, context: SignableContext, iat: number, exp: number): string {
const payload = `${canonicalizeContext(context)}.${iat}.${exp}`;
const sig = crypto.createHmac("sha256", secret).update(payload, "utf8").digest("base64url");
return `${iat}.${exp}.${sig}`;
}

/**
* Encodes a context the way the API does before verifying it: keys sorted by
* code point, no whitespace, `<`, `>`, `&` and `/` left literal, and U+2028 and
* U+2029 escaped.
* @internal
*/
export function canonicalizeContext(context: SignableContext): string {
const parts: string[] = [];
// "company" sorts before "user".
if (context.company != null) {
parts.push(`"company":${canonicalizeKeys(context.company)}`);
}
if (context.user != null) {
parts.push(`"user":${canonicalizeKeys(context.user)}`);
}
return `{${parts.join(",")}}`;
}

function canonicalizeKeys(keys: Record<string, string>): string {
const names = Object.keys(keys).sort(compareCodePoints);
const entries = names.map((name) => {
const value = keys[name];
if (typeof value !== "string") {
throw new ContextSignatureError(`The value of context key "${name}" must be a string.`);
}
return `${encodeString(name)}:${encodeString(value)}`;
});
return `{${entries.join(",")}}`;
}

// The API sorts keys by their UTF-8 bytes, which is code point order. The
// default sort compares UTF-16 code units, which puts a character outside the
// BMP (a surrogate pair) before U+E000 to U+FFFF.
function compareCodePoints(a: string, b: string): number {
return Buffer.compare(Buffer.from(a, "utf8"), Buffer.from(b, "utf8"));
}

const loneSurrogate = /[\ud800-\udbff](?![\udc00-\udfff])|(?<![\ud800-\udbff])[\udc00-\udfff]/g;

// JSON.stringify escapes quotes, backslashes and control characters the way
// the API does. Two differences remain: the API escapes U+2028 and U+2029,
// and it reads a lone surrogate as U+FFFD.
function encodeString(value: string): string {
return JSON.stringify(value.replace(loneSurrogate, "\ufffd"))
.replace(/\u2028/g, "\\u2028")
.replace(/\u2029/g, "\\u2029");
}
9 changes: 9 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,15 @@ export type {
Reservation,
TrackWithReservationOptions,
} from "./credits";
export {
signContext,
ContextSignatureError,
CONTEXT_SIGNATURE_HEADER,
DEFAULT_CONTEXT_SIGNATURE_LIFETIME_SECONDS,
MAX_CONTEXT_SIGNATURE_LIFETIME_SECONDS,
type SignableContext,
type SignContextOptions,
} from "./context-signature";
export {
verifyWebhookSignature,
verifySignature,
Expand Down
104 changes: 104 additions & 0 deletions tests/unit/context-signature.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
import * as fs from "fs";
import * as path from "path";
import {
ContextSignatureError,
canonicalizeContext,
DEFAULT_CONTEXT_SIGNATURE_LIFETIME_SECONDS,
MAX_CONTEXT_SIGNATURE_LIFETIME_SECONDS,
type SignableContext,
signContext,
signContextAt,
} from "../../src/context-signature";

// context-signing.json is copied verbatim from api/lib/contextsig/testdata in
// the Schematic API, which generates it from the verifier and checks it in its
// own tests. Don't edit it here.
interface SigningVectors {
max_lifetime_seconds: number;
vectors: {
canonical: string;
context: SignableContext;
exp: number;
iat: number;
name: string;
secret: string;
signature: string;
}[];
}

const vectors: SigningVectors = JSON.parse(fs.readFileSync(path.join(__dirname, "context-signing.json"), "utf8"));

function window(signature: string): { iat: number; exp: number } {
const [iat, exp] = signature.split(".").map(Number);
return { iat, exp };
}

describe("context signing vectors", () => {
it("caps the lifetime where the API does", () => {
expect(MAX_CONTEXT_SIGNATURE_LIFETIME_SECONDS).toBe(vectors.max_lifetime_seconds);
});

it.each(vectors.vectors.map((v) => [v.name, v] as const))("%s", (_name, v) => {
expect(canonicalizeContext(v.context)).toBe(v.canonical);
expect(signContextAt(v.secret, v.context, v.iat, v.exp)).toBe(v.signature);
});
});

describe("signContext", () => {
const context: SignableContext = { company: { id: "comp_1" } };

it("signs for the default lifetime from now", () => {
const before = Math.floor(Date.now() / 1000);
const { iat, exp } = window(signContext("secret", context));

expect(iat).toBeGreaterThanOrEqual(before);
expect(iat).toBeLessThanOrEqual(Math.floor(Date.now() / 1000));
expect(exp - iat).toBe(DEFAULT_CONTEXT_SIGNATURE_LIFETIME_SECONDS);
});

it("signs from the time and for the lifetime given", () => {
const issuedAt = new Date(1_700_000_000_500);
const signature = signContext("secret", context, { issuedAt, lifetimeSeconds: 300 });

expect(signature).toBe(signContextAt("secret", context, 1_700_000_000, 1_700_000_300));
});

it.each([
0,
-60,
1.5,
MAX_CONTEXT_SIGNATURE_LIFETIME_SECONDS + 1,
86_400,
])("refuses a lifetime of %p seconds", (lifetimeSeconds) => {
expect(() => signContext("secret", context, { lifetimeSeconds })).toThrow(ContextSignatureError);
});

it("refuses an invalid issuedAt", () => {
expect(() => signContext("secret", context, { issuedAt: new Date(Number.NaN) })).toThrow(ContextSignatureError);
});

it("refuses a missing secret", () => {
expect(() => signContext("", context)).toThrow(ContextSignatureError);
});

it("refuses a value that isn't a string", () => {
const numeric = { company: { id: 123 } } as unknown as SignableContext;
expect(() => signContext("secret", numeric)).toThrow(ContextSignatureError);
});
});

describe("canonicalizeContext", () => {
it("leaves out a company or user that is null or undefined", () => {
const context = { company: null, user: undefined } as unknown as SignableContext;
expect(canonicalizeContext(context)).toBe("{}");
});

it("signs a lone surrogate as U+FFFD, as the API reads it", () => {
expect(canonicalizeContext({ company: { name: "a\ud800b" } })).toBe('{"company":{"name":"a\ufffdb"}}');
expect(canonicalizeContext({ company: { name: "a\udc00" } })).toBe('{"company":{"name":"a\ufffd"}}');
});

it("keeps a valid surrogate pair", () => {
expect(canonicalizeContext({ company: { name: "\ud83d\ude00" } })).toBe('{"company":{"name":"\ud83d\ude00"}}');
});
});
Loading
Loading