@wwchen/stack 0.0.0-stage → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +79 -2
- package/blocks/AGENTS.md +77 -0
- package/blocks/CLAUDE.md +113 -0
- package/blocks/env.example +34 -0
- package/blocks/gitignore +18 -0
- package/configs/biome.json +45 -0
- package/configs/tsconfig.next.json +22 -0
- package/dist/auth/better-auth/index.d.ts +316 -0
- package/dist/auth/better-auth/index.js +237 -0
- package/dist/auth/better-auth/tables.d.ts +628 -0
- package/dist/auth/better-auth/tables.js +74 -0
- package/dist/auth/better-auth/users.d.ts +27 -0
- package/dist/auth/better-auth/users.js +128 -0
- package/dist/auth/index.d.ts +58 -0
- package/dist/auth/index.js +120 -0
- package/dist/auth/proxy.d.ts +14 -0
- package/dist/auth/proxy.js +50 -0
- package/dist/auth/safe-next.d.ts +17 -0
- package/dist/auth/safe-next.js +36 -0
- package/dist/auth/types.d.ts +47 -0
- package/dist/auth/types.js +5 -0
- package/dist/cli/context.d.ts +38 -0
- package/dist/cli/context.js +43 -0
- package/dist/cli/index.d.ts +4 -0
- package/dist/cli/index.js +95 -0
- package/dist/cli/neon.d.ts +97 -0
- package/dist/cli/neon.js +334 -0
- package/dist/cli/sync-blocks.d.ts +16 -0
- package/dist/cli/sync-blocks.js +97 -0
- package/dist/cli/user-create.d.ts +2 -0
- package/dist/cli/user-create.js +35 -0
- package/dist/cli/vercel-build.d.ts +4 -0
- package/dist/cli/vercel-build.js +72 -0
- package/dist/configs/vitest.d.ts +4 -0
- package/dist/configs/vitest.js +50 -0
- package/dist/connections/crypto.d.ts +8 -0
- package/dist/connections/crypto.js +50 -0
- package/dist/connections/index.d.ts +63 -0
- package/dist/connections/index.js +212 -0
- package/dist/connections/providers.d.ts +30 -0
- package/dist/connections/providers.js +47 -0
- package/dist/connections/table.d.ts +156 -0
- package/dist/connections/table.js +29 -0
- package/dist/db/explaining-pool.d.ts +16 -0
- package/dist/db/explaining-pool.js +62 -0
- package/dist/db/index.d.ts +21 -0
- package/dist/db/index.js +36 -0
- package/dist/db/migration-status.d.ts +8 -0
- package/dist/db/migration-status.js +41 -0
- package/dist/db/target.d.ts +26 -0
- package/dist/db/target.js +72 -0
- package/dist/db/testing/index.d.ts +27 -0
- package/dist/db/testing/index.js +71 -0
- package/dist/db/testing/isolate.d.ts +1 -0
- package/dist/db/testing/isolate.js +4 -0
- package/dist/db/testing/pglite.d.ts +21 -0
- package/dist/db/testing/pglite.js +71 -0
- package/dist/env/define-env.d.ts +37 -0
- package/dist/env/define-env.js +134 -0
- package/dist/env/index.d.ts +3 -0
- package/dist/env/index.js +3 -0
- package/dist/env/load-env-file.d.ts +15 -0
- package/dist/env/load-env-file.js +52 -0
- package/dist/env/stack-env.d.ts +40 -0
- package/dist/env/stack-env.js +60 -0
- package/dist/env/testing.d.ts +8 -0
- package/dist/env/testing.js +16 -0
- package/dist/http/client-ip.d.ts +12 -0
- package/dist/http/client-ip.js +28 -0
- package/dist/http/guards.d.ts +17 -0
- package/dist/http/guards.js +57 -0
- package/dist/http/rate-limit.d.ts +34 -0
- package/dist/http/rate-limit.js +79 -0
- package/dist/index.d.ts +1 -0
- package/dist/index.js +1 -0
- package/dist/jobs/index.d.ts +37 -0
- package/dist/jobs/index.js +51 -0
- package/dist/mail/index.d.ts +45 -0
- package/dist/mail/index.js +97 -0
- package/dist/next/api.d.ts +71 -0
- package/dist/next/api.js +118 -0
- package/dist/next/config.d.ts +8 -0
- package/dist/next/config.js +104 -0
- package/dist/next/cron.d.ts +14 -0
- package/dist/next/cron.js +40 -0
- package/dist/next/health.d.ts +19 -0
- package/dist/next/health.js +36 -0
- package/dist/next/index.d.ts +5 -0
- package/dist/next/index.js +4 -0
- package/dist/testing/next.d.ts +14 -0
- package/dist/testing/next.js +39 -0
- package/dist/ui/app.css +56 -0
- package/dist/ui/globals.css +152 -0
- package/dist/ui/icons.d.ts +17 -0
- package/dist/ui/icons.js +104 -0
- package/dist/ui/index.d.ts +33 -0
- package/dist/ui/index.js +41 -0
- package/dist/ui/theme.d.ts +18 -0
- package/dist/ui/theme.js +24 -0
- package/package.json +134 -4
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
// `stack user:create <email> [--admin]` — adds a real user to sign in as, through the app's own
|
|
2
|
+
// auth (`src/lib/auth.ts`, imported from the working directory with Node's type stripping, so it
|
|
3
|
+
// must use relative `.ts` imports). Sign-in never creates users; this is how the first admin
|
|
4
|
+
// exists. A duplicate email is an error, not a silent no-op.
|
|
5
|
+
//
|
|
6
|
+
// Where: like `stack with-neon`, your Neon dev branch unless DATABASE_URL or ENV_FILE says
|
|
7
|
+
// otherwise. Production is a deliberate `ENV_FILE=<production env file>` (docs/runbook.md).
|
|
8
|
+
import { CliError, importApp, loadAppEnv } from "./context.js";
|
|
9
|
+
import { devBranchEnv } from "./neon.js";
|
|
10
|
+
export async function userCreate(cli, args) {
|
|
11
|
+
const admin = args.includes("--admin");
|
|
12
|
+
const [email] = args.filter((arg) => arg !== "--admin");
|
|
13
|
+
if (!email) {
|
|
14
|
+
cli.error("usage: stack user:create <email> [--admin]");
|
|
15
|
+
return 2;
|
|
16
|
+
}
|
|
17
|
+
// The app's modules read process.env: the dev branch's connection (when nothing else names a
|
|
18
|
+
// database) wins over `.env`, which fills in only what is still unset.
|
|
19
|
+
Object.assign(cli.env, await devBranchEnv(cli));
|
|
20
|
+
loadAppEnv(cli);
|
|
21
|
+
const auth = (await importApp(cli, "src/lib/auth.ts")).auth;
|
|
22
|
+
if (!auth?.users)
|
|
23
|
+
throw new CliError("src/lib/auth.ts must export `auth` (a StackAuth).");
|
|
24
|
+
try {
|
|
25
|
+
const user = await auth.users.add(email, admin ? "admin" : "user");
|
|
26
|
+
cli.log(`created ${user.email}${admin ? " as an admin" : ""}. They sign in with a magic link or Google.`);
|
|
27
|
+
return 0;
|
|
28
|
+
}
|
|
29
|
+
catch (error) {
|
|
30
|
+
if (error instanceof Error && error.name === "DuplicateUserError") {
|
|
31
|
+
throw new CliError(`${error.message}. Nothing changed.`);
|
|
32
|
+
}
|
|
33
|
+
throw error;
|
|
34
|
+
}
|
|
35
|
+
}
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import { type Cli } from "./context.ts";
|
|
2
|
+
/** Every variable the stack's env reads a database connection from. */
|
|
3
|
+
export declare const DATABASE_URL_VARIABLES: readonly ["DATABASE_URL", "DATABASE_URL_UNPOOLED"];
|
|
4
|
+
export declare function vercelBuild(cli: Cli): Promise<number>;
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
// `stack vercel-build` — Vercel's build command. Neon's documented pattern: the build applies the
|
|
2
|
+
// migrations, so the deployment never goes live on a schema it was not built for.
|
|
3
|
+
//
|
|
4
|
+
// - Preview: migrates the one shared `preview` branch (see `stack neon reset-preview`), which lacks
|
|
5
|
+
// this PR's new migrations. Refuses if any of its database URLs turns out to be production.
|
|
6
|
+
// - Production: migrates production's database, then builds. A failed migration fails the build,
|
|
7
|
+
// so the new code never goes live on a schema it was not built for. The old deployment keeps
|
|
8
|
+
// serving while this runs, which is why every migration must be expand-then-contract.
|
|
9
|
+
// - Anything else (a local run): only builds.
|
|
10
|
+
import { endpointOf } from "../db/index.js";
|
|
11
|
+
import { CliError } from "./context.js";
|
|
12
|
+
import { migrate } from "./neon.js";
|
|
13
|
+
/** Every variable the stack's env reads a database connection from. */
|
|
14
|
+
export const DATABASE_URL_VARIABLES = ["DATABASE_URL", "DATABASE_URL_UNPOOLED"];
|
|
15
|
+
const hostOf = (url) => {
|
|
16
|
+
try {
|
|
17
|
+
return new URL(url).hostname;
|
|
18
|
+
}
|
|
19
|
+
catch {
|
|
20
|
+
return "(unparseable URL)";
|
|
21
|
+
}
|
|
22
|
+
};
|
|
23
|
+
/**
|
|
24
|
+
* A deployment that migrates needs a database URL. drizzle.config.ts migrates through the direct
|
|
25
|
+
* (unpooled) endpoint when it is set, bypassing PgBouncer; without it, through the pooler.
|
|
26
|
+
*/
|
|
27
|
+
function requireDatabaseUrl(cli, environment) {
|
|
28
|
+
if (!cli.env.DATABASE_URL_UNPOOLED && !cli.env.DATABASE_URL) {
|
|
29
|
+
// Not the Neon integration: its preview branches are cut from production, with its data.
|
|
30
|
+
const where = environment === "Preview"
|
|
31
|
+
? "the `preview` branch's URL from `stack neon reset-preview`, scoped to Preview"
|
|
32
|
+
: "production's URL, scoped to Production";
|
|
33
|
+
throw new CliError(`[build] ${environment} deployment with no DATABASE_URL: set it in Vercel (${where}).`);
|
|
34
|
+
}
|
|
35
|
+
if (!cli.env.DATABASE_URL_UNPOOLED) {
|
|
36
|
+
cli.error(`[build] ${environment}: no DATABASE_URL_UNPOOLED; migrating through the pooler.`);
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
export async function vercelBuild(cli) {
|
|
40
|
+
const environment = cli.env.VERCEL_ENV;
|
|
41
|
+
if (environment === "preview" || environment === "production") {
|
|
42
|
+
requireDatabaseUrl(cli, environment === "preview" ? "Preview" : "Production");
|
|
43
|
+
if (environment === "preview") {
|
|
44
|
+
// A backstop for a mis-scoped variable: a preview must never migrate or serve production.
|
|
45
|
+
// Every database URL is checked, not just the one migrate uses: the running preview reads
|
|
46
|
+
// DATABASE_URL, and Vercel previews run with NODE_ENV=production, so assertDevDatabase does
|
|
47
|
+
// not catch it at runtime. Pooled and direct hosts of one endpoint compare equal
|
|
48
|
+
// (endpointOf), whichever form each variable holds. Not optional: without production's host
|
|
49
|
+
// there is nothing to check against, and the host is not a secret, so it is set for every
|
|
50
|
+
// environment.
|
|
51
|
+
const productionHost = cli.env.PRODUCTION_DATABASE_HOST ?? "";
|
|
52
|
+
if (productionHost.trim() === "") {
|
|
53
|
+
throw new CliError("[build] PRODUCTION_DATABASE_HOST is not set on Preview, so this build cannot tell the " +
|
|
54
|
+
"preview database from production. Set it in Vercel for all environments " +
|
|
55
|
+
"(production's direct host, not a secret); see the runbook.");
|
|
56
|
+
}
|
|
57
|
+
for (const name of DATABASE_URL_VARIABLES) {
|
|
58
|
+
const value = cli.env[name];
|
|
59
|
+
if (value && endpointOf(value) === endpointOf(productionHost)) {
|
|
60
|
+
throw new CliError(`[build] This preview's ${name} (${hostOf(value)}) is production (${productionHost.trim()}). ` +
|
|
61
|
+
"Refusing to migrate or build; scope it to the `preview` branch (see the runbook).");
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
cli.log(`[build] ${environment}: migrating before the build.`);
|
|
66
|
+
// The database is remote by design; the guard's opt-in says this command means it.
|
|
67
|
+
const status = await migrate(cli, { ...cli.env, ALLOW_REMOTE_DATABASE: "1" });
|
|
68
|
+
if (status !== 0)
|
|
69
|
+
return status;
|
|
70
|
+
}
|
|
71
|
+
return (await cli.exec("pnpm", ["exec", "next", "build"], { env: cli.env, inherit: true })).code;
|
|
72
|
+
}
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import { resolve as resolvePath } from "node:path";
|
|
2
|
+
const toArray = (value) => value === undefined ? [] : Array.isArray(value) ? value : [value];
|
|
3
|
+
// Vitest settings shared by every app, ported from cc-rewards-tracker's vitest.config.ts.
|
|
4
|
+
// `overrides` is merged, not substituted: an app's `setupFiles`, `include`, `exclude` and `env`
|
|
5
|
+
// are added to the preset's, and any other key the app sets wins.
|
|
6
|
+
export function stackVitestConfig(overrides = {}, options = {}) {
|
|
7
|
+
const { test: appTest = {}, resolve: appResolve, ...appRest } = overrides;
|
|
8
|
+
const { root = process.cwd() } = options;
|
|
9
|
+
const alias = { "@": resolvePath(root, "src") };
|
|
10
|
+
const appAlias = appResolve?.alias;
|
|
11
|
+
const { setupFiles, include, exclude, env, ...appTestRest } = appTest;
|
|
12
|
+
return {
|
|
13
|
+
...appRest,
|
|
14
|
+
resolve: {
|
|
15
|
+
...appResolve,
|
|
16
|
+
// The `@/` alias exists for app and test code, matching `paths` in tsconfig.next.json.
|
|
17
|
+
// Worker, lib, db, server and script modules use relative `.ts` specifiers instead.
|
|
18
|
+
// `root` is the consuming project (default: the working directory Vitest runs from).
|
|
19
|
+
alias: Array.isArray(appAlias)
|
|
20
|
+
? [{ find: "@", replacement: alias["@"] }, ...appAlias]
|
|
21
|
+
: { ...alias, ...appAlias },
|
|
22
|
+
},
|
|
23
|
+
test: {
|
|
24
|
+
environment: "node",
|
|
25
|
+
globals: false,
|
|
26
|
+
pool: "forks",
|
|
27
|
+
// Integration tests boot an in-memory PGlite and run every migration; a cold start can take
|
|
28
|
+
// several seconds on a busy CI runner.
|
|
29
|
+
testTimeout: 60000,
|
|
30
|
+
hookTimeout: 60000,
|
|
31
|
+
...appTestRest,
|
|
32
|
+
// Runs before anything loads `.env`, so a test can never reach a real database.
|
|
33
|
+
setupFiles: ["@wwchen/stack/db/testing/isolate", ...toArray(setupFiles)],
|
|
34
|
+
include: [
|
|
35
|
+
"tests/unit/**/*.test.{ts,tsx}",
|
|
36
|
+
"tests/integration/**/*.test.{ts,tsx}",
|
|
37
|
+
"src/**/*.test.{ts,tsx}",
|
|
38
|
+
...toArray(include),
|
|
39
|
+
],
|
|
40
|
+
exclude: ["node_modules/**", ".next/**", "dist/**", "tests/e2e/**", ...toArray(exclude)],
|
|
41
|
+
env: {
|
|
42
|
+
TZ: "UTC",
|
|
43
|
+
// A fixed, test-only value so the suite is self-sufficient on a clean checkout (CI has no
|
|
44
|
+
// `.env`). It is not a secret and must never be used outside tests.
|
|
45
|
+
BETTER_AUTH_SECRET: "test-only-better-auth-secret-not-a-real-secret",
|
|
46
|
+
...env,
|
|
47
|
+
},
|
|
48
|
+
},
|
|
49
|
+
};
|
|
50
|
+
}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
export declare class TokenKeyError extends Error {
|
|
2
|
+
constructor(message: string);
|
|
3
|
+
}
|
|
4
|
+
/** The 32-byte key from its base64 form, or a `TokenKeyError` saying how to make one. */
|
|
5
|
+
export declare function parseEncryptionKey(raw: string | undefined): Buffer;
|
|
6
|
+
export declare function encryptToken(plain: string, key: Buffer): string;
|
|
7
|
+
/** The token, or an error that names the likely cause and never the token or the key. */
|
|
8
|
+
export declare function decryptToken(box: string, key: Buffer): string;
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import { createCipheriv, createDecipheriv, randomBytes } from "node:crypto";
|
|
2
|
+
/**
|
|
3
|
+
* Connected-account tokens are encrypted at rest with AES-256-GCM under `TOKEN_ENCRYPTION_KEY`
|
|
4
|
+
* (32 bytes, base64: `openssl rand -base64 32`), so a database leak alone exposes nobody's account.
|
|
5
|
+
* The format is ifttt's — `v1:<iv>:<tag>:<ciphertext>`, base64url parts — so tokens it stored move
|
|
6
|
+
* across unchanged. Changing the key makes every stored token unreadable: everyone reconnects.
|
|
7
|
+
*/
|
|
8
|
+
const VERSION = "v1";
|
|
9
|
+
export class TokenKeyError extends Error {
|
|
10
|
+
constructor(message) {
|
|
11
|
+
super(message);
|
|
12
|
+
this.name = "TokenKeyError";
|
|
13
|
+
}
|
|
14
|
+
}
|
|
15
|
+
/** The 32-byte key from its base64 form, or a `TokenKeyError` saying how to make one. */
|
|
16
|
+
export function parseEncryptionKey(raw) {
|
|
17
|
+
if (!raw)
|
|
18
|
+
throw new TokenKeyError("TOKEN_ENCRYPTION_KEY is not set (openssl rand -base64 32)");
|
|
19
|
+
const key = Buffer.from(raw, "base64");
|
|
20
|
+
if (key.length !== 32) {
|
|
21
|
+
throw new TokenKeyError("TOKEN_ENCRYPTION_KEY must be 32 bytes, base64-encoded (openssl rand -base64 32)");
|
|
22
|
+
}
|
|
23
|
+
return key;
|
|
24
|
+
}
|
|
25
|
+
export function encryptToken(plain, key) {
|
|
26
|
+
const iv = randomBytes(12);
|
|
27
|
+
const cipher = createCipheriv("aes-256-gcm", key, iv);
|
|
28
|
+
const ciphertext = Buffer.concat([cipher.update(plain, "utf8"), cipher.final()]);
|
|
29
|
+
return [VERSION, iv, cipher.getAuthTag(), ciphertext]
|
|
30
|
+
.map((part) => (typeof part === "string" ? part : part.toString("base64url")))
|
|
31
|
+
.join(":");
|
|
32
|
+
}
|
|
33
|
+
/** The token, or an error that names the likely cause and never the token or the key. */
|
|
34
|
+
export function decryptToken(box, key) {
|
|
35
|
+
const [version, iv, tag, ciphertext, extra] = box.split(":");
|
|
36
|
+
if (version !== VERSION || !iv || !tag || ciphertext === undefined || extra !== undefined) {
|
|
37
|
+
throw new Error("Unrecognised encrypted token format");
|
|
38
|
+
}
|
|
39
|
+
const decipher = createDecipheriv("aes-256-gcm", key, Buffer.from(iv, "base64url"));
|
|
40
|
+
decipher.setAuthTag(Buffer.from(tag, "base64url"));
|
|
41
|
+
try {
|
|
42
|
+
return Buffer.concat([
|
|
43
|
+
decipher.update(Buffer.from(ciphertext, "base64url")),
|
|
44
|
+
decipher.final(),
|
|
45
|
+
]).toString("utf8");
|
|
46
|
+
}
|
|
47
|
+
catch {
|
|
48
|
+
throw new Error("Could not decrypt a stored token (was TOKEN_ENCRYPTION_KEY changed?)");
|
|
49
|
+
}
|
|
50
|
+
}
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
import type { NodePgDatabase } from "drizzle-orm/node-postgres";
|
|
2
|
+
import type { ConnectionProvider } from "./providers.ts";
|
|
3
|
+
import type { ConnectionTable } from "./table.ts";
|
|
4
|
+
/**
|
|
5
|
+
* Connected accounts: a signed-in person connects an account at another service (ifttt's
|
|
6
|
+
* Foursquare) so the app can work on their behalf. This is deliberately not sign-in — a connection
|
|
7
|
+
* never signs anyone in and never creates a user (see the design's "Everyone signs in by email").
|
|
8
|
+
*
|
|
9
|
+
* The flow, as two route handlers the app mounts:
|
|
10
|
+
* - `start(userId, provider, next)` (GET `/api/connections/<provider>/start`): sets a one-off
|
|
11
|
+
* cookie holding a random nonce and redirects to the provider with a signed `state` naming the
|
|
12
|
+
* person, the provider, that nonce, an expiry (10 minutes) and where to go afterwards.
|
|
13
|
+
* - `callback(request, userId)` (GET `/api/connections/<provider>/callback`): accepts the code only
|
|
14
|
+
* when the state's signature holds, it has not expired, this browser holds its nonce (so nobody
|
|
15
|
+
* can make someone else finish a flow they started) and the signed-in person is the one who
|
|
16
|
+
* started it. It then stores the token encrypted and redirects to `next` with
|
|
17
|
+
* `?connection=<provider>&result=<code>` — a short code, never free text from the URL.
|
|
18
|
+
*/
|
|
19
|
+
export declare const CONNECT_COOKIE = "stack_connect";
|
|
20
|
+
/** What the callback reports in `?result=`. */
|
|
21
|
+
export type ConnectResult = "connected" | "invalid" | "expired" | "wrong_user" | "denied" | "exchange" | "taken";
|
|
22
|
+
export type Connection = {
|
|
23
|
+
provider: string;
|
|
24
|
+
subject: string;
|
|
25
|
+
name: string | null;
|
|
26
|
+
createdAt: Date;
|
|
27
|
+
updatedAt: Date;
|
|
28
|
+
};
|
|
29
|
+
type Database = NodePgDatabase<any>;
|
|
30
|
+
export type ConnectionsOptions = {
|
|
31
|
+
db: Database;
|
|
32
|
+
table: ConnectionTable;
|
|
33
|
+
providers: ConnectionProvider[];
|
|
34
|
+
/** Signs the OAuth state. The app's `BETTER_AUTH_SECRET`; a sub-key is derived from it. */
|
|
35
|
+
secret: string;
|
|
36
|
+
/** `TOKEN_ENCRYPTION_KEY`: 32 bytes, base64. Checked on first use, not at construction. */
|
|
37
|
+
encryptionKey: string | undefined;
|
|
38
|
+
/** The app's public origin (`APP_URL`): redirect URIs are built from it, never from a request. */
|
|
39
|
+
baseURL: string;
|
|
40
|
+
/** Where the provider sends people back. Default `/api/connections/<provider>/callback`. */
|
|
41
|
+
callbackPath?: (providerId: string) => string;
|
|
42
|
+
fetch?: typeof fetch;
|
|
43
|
+
now?: () => number;
|
|
44
|
+
};
|
|
45
|
+
export type Connections = {
|
|
46
|
+
start(userId: string, providerId: string, next?: string): Response;
|
|
47
|
+
callback(request: Request, userId: string | null): Promise<Response>;
|
|
48
|
+
/** The decrypted token, or null when the person has not connected this provider. */
|
|
49
|
+
token(userId: string, providerId: string): Promise<string | null>;
|
|
50
|
+
/** The person's connections, without tokens. */
|
|
51
|
+
list(userId: string): Promise<Connection[]>;
|
|
52
|
+
/** Everyone connected to a provider, without tokens: the people a scheduled job works for. */
|
|
53
|
+
connected(providerId: string): Promise<(Connection & {
|
|
54
|
+
userId: string;
|
|
55
|
+
})[]>;
|
|
56
|
+
/** Forgets the token. Revoking the app at the provider is the person's to do there. */
|
|
57
|
+
disconnect(userId: string, providerId: string): Promise<boolean>;
|
|
58
|
+
redirectUri(providerId: string): string;
|
|
59
|
+
};
|
|
60
|
+
export declare function createConnections(opts: ConnectionsOptions): Connections;
|
|
61
|
+
export { decryptToken, encryptToken, parseEncryptionKey, TokenKeyError } from "./crypto.ts";
|
|
62
|
+
export { type ConnectionProvider, FOURSQUARE_API_VERSION, foursquare } from "./providers.ts";
|
|
63
|
+
export { type ConnectionTable, connectionTable } from "./table.ts";
|
|
@@ -0,0 +1,212 @@
|
|
|
1
|
+
import { createHmac, randomBytes, timingSafeEqual } from "node:crypto";
|
|
2
|
+
import { and, asc, eq } from "drizzle-orm";
|
|
3
|
+
import { safeNext } from "../auth/safe-next.js";
|
|
4
|
+
import { decryptToken, encryptToken, parseEncryptionKey } from "./crypto.js";
|
|
5
|
+
/**
|
|
6
|
+
* Connected accounts: a signed-in person connects an account at another service (ifttt's
|
|
7
|
+
* Foursquare) so the app can work on their behalf. This is deliberately not sign-in — a connection
|
|
8
|
+
* never signs anyone in and never creates a user (see the design's "Everyone signs in by email").
|
|
9
|
+
*
|
|
10
|
+
* The flow, as two route handlers the app mounts:
|
|
11
|
+
* - `start(userId, provider, next)` (GET `/api/connections/<provider>/start`): sets a one-off
|
|
12
|
+
* cookie holding a random nonce and redirects to the provider with a signed `state` naming the
|
|
13
|
+
* person, the provider, that nonce, an expiry (10 minutes) and where to go afterwards.
|
|
14
|
+
* - `callback(request, userId)` (GET `/api/connections/<provider>/callback`): accepts the code only
|
|
15
|
+
* when the state's signature holds, it has not expired, this browser holds its nonce (so nobody
|
|
16
|
+
* can make someone else finish a flow they started) and the signed-in person is the one who
|
|
17
|
+
* started it. It then stores the token encrypted and redirects to `next` with
|
|
18
|
+
* `?connection=<provider>&result=<code>` — a short code, never free text from the URL.
|
|
19
|
+
*/
|
|
20
|
+
export const CONNECT_COOKIE = "stack_connect";
|
|
21
|
+
const STATE_TTL_SECONDS = 10 * 60;
|
|
22
|
+
const isUniqueViolation = (error, constraint) => {
|
|
23
|
+
const cause = error?.cause ?? error;
|
|
24
|
+
const pg = cause;
|
|
25
|
+
return pg?.code === "23505" && pg.constraint === constraint;
|
|
26
|
+
};
|
|
27
|
+
function readCookie(request, name) {
|
|
28
|
+
for (const part of (request.headers.get("cookie") ?? "").split(";")) {
|
|
29
|
+
const i = part.indexOf("=");
|
|
30
|
+
if (i > 0 && part.slice(0, i).trim() === name)
|
|
31
|
+
return part.slice(i + 1).trim();
|
|
32
|
+
}
|
|
33
|
+
return null;
|
|
34
|
+
}
|
|
35
|
+
function sameBytes(a, b) {
|
|
36
|
+
const x = Buffer.from(a);
|
|
37
|
+
const y = Buffer.from(b);
|
|
38
|
+
return x.length === y.length && timingSafeEqual(x, y);
|
|
39
|
+
}
|
|
40
|
+
export function createConnections(opts) {
|
|
41
|
+
const { db, table } = opts;
|
|
42
|
+
const providers = new Map(opts.providers.map((p) => [p.id, p]));
|
|
43
|
+
const now = opts.now ?? Date.now;
|
|
44
|
+
const fetchImpl = opts.fetch ?? fetch;
|
|
45
|
+
const secure = opts.baseURL.startsWith("https://");
|
|
46
|
+
const stateKey = createHmac("sha256", opts.secret).update("stack-connections-state-v1").digest();
|
|
47
|
+
const key = () => parseEncryptionKey(opts.encryptionKey);
|
|
48
|
+
const sign = (payload) => createHmac("sha256", stateKey).update(payload).digest("base64url");
|
|
49
|
+
function readState(raw) {
|
|
50
|
+
if (!raw)
|
|
51
|
+
return null;
|
|
52
|
+
const dot = raw.lastIndexOf(".");
|
|
53
|
+
if (dot <= 0)
|
|
54
|
+
return null;
|
|
55
|
+
const payload = raw.slice(0, dot);
|
|
56
|
+
if (!sameBytes(raw.slice(dot + 1), sign(payload)))
|
|
57
|
+
return null;
|
|
58
|
+
try {
|
|
59
|
+
const state = JSON.parse(Buffer.from(payload, "base64url").toString("utf8"));
|
|
60
|
+
const fields = [state.u, state.p, state.n, state.x];
|
|
61
|
+
if (!fields.every((f) => typeof f === "string") || typeof state.e !== "number")
|
|
62
|
+
return null;
|
|
63
|
+
return state;
|
|
64
|
+
}
|
|
65
|
+
catch {
|
|
66
|
+
return null;
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
const cookie = (value, maxAge) => [
|
|
70
|
+
`${CONNECT_COOKIE}=${value}`,
|
|
71
|
+
"Path=/",
|
|
72
|
+
`Max-Age=${maxAge}`,
|
|
73
|
+
"HttpOnly",
|
|
74
|
+
"SameSite=Lax",
|
|
75
|
+
...(secure ? ["Secure"] : []),
|
|
76
|
+
].join("; ");
|
|
77
|
+
function redirect(location, setCookie) {
|
|
78
|
+
const headers = new Headers({ location, "cache-control": "no-store" });
|
|
79
|
+
if (setCookie)
|
|
80
|
+
headers.append("set-cookie", setCookie);
|
|
81
|
+
return new Response(null, { status: 302, headers });
|
|
82
|
+
}
|
|
83
|
+
/** `next` with `connection` and `result` added; `next` is already a safe same-origin path. */
|
|
84
|
+
function landing(next, providerId, result) {
|
|
85
|
+
const url = new URL(next, "http://app.invalid");
|
|
86
|
+
url.searchParams.set("connection", providerId);
|
|
87
|
+
url.searchParams.set("result", result);
|
|
88
|
+
return `${url.pathname}${url.search}${url.hash}`;
|
|
89
|
+
}
|
|
90
|
+
const redirectUri = (providerId) => new URL(opts.callbackPath?.(providerId) ?? `/api/connections/${providerId}/callback`, opts.baseURL).toString();
|
|
91
|
+
const publicColumns = {
|
|
92
|
+
provider: table.provider,
|
|
93
|
+
subject: table.subject,
|
|
94
|
+
name: table.name,
|
|
95
|
+
createdAt: table.createdAt,
|
|
96
|
+
updatedAt: table.updatedAt,
|
|
97
|
+
};
|
|
98
|
+
return {
|
|
99
|
+
redirectUri,
|
|
100
|
+
start(userId, providerId, next = "/") {
|
|
101
|
+
const provider = providers.get(providerId);
|
|
102
|
+
if (!provider) {
|
|
103
|
+
return Response.json({ error: { code: "not_found", message: "Unknown provider." } }, { status: 404 });
|
|
104
|
+
}
|
|
105
|
+
// Checked here so a missing key fails before anyone approves anything at the provider.
|
|
106
|
+
key();
|
|
107
|
+
const nonce = randomBytes(16).toString("base64url");
|
|
108
|
+
const state = {
|
|
109
|
+
u: userId,
|
|
110
|
+
p: providerId,
|
|
111
|
+
n: nonce,
|
|
112
|
+
e: Math.floor(now() / 1000) + STATE_TTL_SECONDS,
|
|
113
|
+
x: safeNext(next),
|
|
114
|
+
};
|
|
115
|
+
const payload = Buffer.from(JSON.stringify(state)).toString("base64url");
|
|
116
|
+
const url = provider.authorizeUrl({
|
|
117
|
+
redirectUri: redirectUri(providerId),
|
|
118
|
+
state: `${payload}.${sign(payload)}`,
|
|
119
|
+
});
|
|
120
|
+
return redirect(url, cookie(nonce, STATE_TTL_SECONDS));
|
|
121
|
+
},
|
|
122
|
+
async callback(request, userId) {
|
|
123
|
+
const params = new URL(request.url).searchParams;
|
|
124
|
+
const clear = cookie("", 0);
|
|
125
|
+
const state = readState(params.get("state"));
|
|
126
|
+
const provider = state ? providers.get(state.p) : undefined;
|
|
127
|
+
if (!state || !provider)
|
|
128
|
+
return redirect(landing("/", "unknown", "invalid"), clear);
|
|
129
|
+
const done = (result) => redirect(landing(state.x, state.p, result), clear);
|
|
130
|
+
const nonce = readCookie(request, CONNECT_COOKIE);
|
|
131
|
+
if (state.e <= now() / 1000 || !nonce || !sameBytes(nonce, state.n))
|
|
132
|
+
return done("expired");
|
|
133
|
+
if (!userId || userId !== state.u)
|
|
134
|
+
return done("wrong_user");
|
|
135
|
+
const code = params.get("code");
|
|
136
|
+
if (!code)
|
|
137
|
+
return done("denied");
|
|
138
|
+
let account;
|
|
139
|
+
try {
|
|
140
|
+
account = await provider.exchange({
|
|
141
|
+
code,
|
|
142
|
+
redirectUri: redirectUri(provider.id),
|
|
143
|
+
fetch: fetchImpl,
|
|
144
|
+
});
|
|
145
|
+
}
|
|
146
|
+
catch (error) {
|
|
147
|
+
console.error(`[connections] ${provider.id} exchange failed: ${error.message}`);
|
|
148
|
+
return done("exchange");
|
|
149
|
+
}
|
|
150
|
+
const [holder] = await db
|
|
151
|
+
.select({ userId: table.userId })
|
|
152
|
+
.from(table)
|
|
153
|
+
.where(and(eq(table.provider, provider.id), eq(table.subject, account.subject)));
|
|
154
|
+
if (holder && holder.userId !== userId)
|
|
155
|
+
return done("taken");
|
|
156
|
+
const token = encryptToken(account.token, key());
|
|
157
|
+
try {
|
|
158
|
+
await db
|
|
159
|
+
.insert(table)
|
|
160
|
+
.values({
|
|
161
|
+
userId,
|
|
162
|
+
provider: provider.id,
|
|
163
|
+
subject: account.subject,
|
|
164
|
+
name: account.name,
|
|
165
|
+
token,
|
|
166
|
+
})
|
|
167
|
+
.onConflictDoUpdate({
|
|
168
|
+
target: [table.userId, table.provider],
|
|
169
|
+
set: { subject: account.subject, name: account.name, token, updatedAt: new Date() },
|
|
170
|
+
});
|
|
171
|
+
}
|
|
172
|
+
catch (error) {
|
|
173
|
+
// Someone else connected the same account between the check and the write.
|
|
174
|
+
if (isUniqueViolation(error, "connection_provider_subject"))
|
|
175
|
+
return done("taken");
|
|
176
|
+
throw error;
|
|
177
|
+
}
|
|
178
|
+
return done("connected");
|
|
179
|
+
},
|
|
180
|
+
async token(userId, providerId) {
|
|
181
|
+
const [row] = await db
|
|
182
|
+
.select({ token: table.token })
|
|
183
|
+
.from(table)
|
|
184
|
+
.where(and(eq(table.userId, userId), eq(table.provider, providerId)));
|
|
185
|
+
return row ? decryptToken(row.token, key()) : null;
|
|
186
|
+
},
|
|
187
|
+
async list(userId) {
|
|
188
|
+
return db
|
|
189
|
+
.select(publicColumns)
|
|
190
|
+
.from(table)
|
|
191
|
+
.where(eq(table.userId, userId))
|
|
192
|
+
.orderBy(asc(table.provider));
|
|
193
|
+
},
|
|
194
|
+
async connected(providerId) {
|
|
195
|
+
return db
|
|
196
|
+
.select({ ...publicColumns, userId: table.userId })
|
|
197
|
+
.from(table)
|
|
198
|
+
.where(eq(table.provider, providerId))
|
|
199
|
+
.orderBy(asc(table.createdAt));
|
|
200
|
+
},
|
|
201
|
+
async disconnect(userId, providerId) {
|
|
202
|
+
const removed = await db
|
|
203
|
+
.delete(table)
|
|
204
|
+
.where(and(eq(table.userId, userId), eq(table.provider, providerId)))
|
|
205
|
+
.returning({ id: table.id });
|
|
206
|
+
return removed.length > 0;
|
|
207
|
+
},
|
|
208
|
+
};
|
|
209
|
+
}
|
|
210
|
+
export { decryptToken, encryptToken, parseEncryptionKey, TokenKeyError } from "./crypto.js";
|
|
211
|
+
export { FOURSQUARE_API_VERSION, foursquare } from "./providers.js";
|
|
212
|
+
export { connectionTable } from "./table.js";
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A service people connect: how to send them to approve access, and how to turn the code it hands
|
|
3
|
+
* back into a token and the account it belongs to. Errors never carry the token, the code or a URL
|
|
4
|
+
* that holds either.
|
|
5
|
+
*/
|
|
6
|
+
export type ConnectionProvider = {
|
|
7
|
+
id: string;
|
|
8
|
+
authorizeUrl(opts: {
|
|
9
|
+
redirectUri: string;
|
|
10
|
+
state: string;
|
|
11
|
+
}): string;
|
|
12
|
+
exchange(opts: {
|
|
13
|
+
code: string;
|
|
14
|
+
redirectUri: string;
|
|
15
|
+
fetch: typeof fetch;
|
|
16
|
+
}): Promise<{
|
|
17
|
+
token: string;
|
|
18
|
+
subject: string;
|
|
19
|
+
name: string | null;
|
|
20
|
+
}>;
|
|
21
|
+
};
|
|
22
|
+
export declare const FOURSQUARE_API_VERSION = "20240101";
|
|
23
|
+
/**
|
|
24
|
+
* Foursquare (Swarm). Its tokens do not expire. `subject` is the Foursquare user id, read from the
|
|
25
|
+
* legacy v2 `users/self`, the endpoint family that also returns a person's own check-ins.
|
|
26
|
+
*/
|
|
27
|
+
export declare function foursquare(opts: {
|
|
28
|
+
clientId: string;
|
|
29
|
+
clientSecret: string;
|
|
30
|
+
}): ConnectionProvider;
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
const FOURSQUARE_OAUTH = "https://foursquare.com/oauth2";
|
|
2
|
+
const FOURSQUARE_API = "https://api.foursquare.com/v2";
|
|
3
|
+
export const FOURSQUARE_API_VERSION = "20240101";
|
|
4
|
+
/**
|
|
5
|
+
* Foursquare (Swarm). Its tokens do not expire. `subject` is the Foursquare user id, read from the
|
|
6
|
+
* legacy v2 `users/self`, the endpoint family that also returns a person's own check-ins.
|
|
7
|
+
*/
|
|
8
|
+
export function foursquare(opts) {
|
|
9
|
+
return {
|
|
10
|
+
id: "foursquare",
|
|
11
|
+
authorizeUrl({ redirectUri, state }) {
|
|
12
|
+
const params = new URLSearchParams({
|
|
13
|
+
client_id: opts.clientId,
|
|
14
|
+
response_type: "code",
|
|
15
|
+
redirect_uri: redirectUri,
|
|
16
|
+
state,
|
|
17
|
+
});
|
|
18
|
+
return `${FOURSQUARE_OAUTH}/authenticate?${params}`;
|
|
19
|
+
},
|
|
20
|
+
async exchange({ code, redirectUri, fetch }) {
|
|
21
|
+
const params = new URLSearchParams({
|
|
22
|
+
client_id: opts.clientId,
|
|
23
|
+
client_secret: opts.clientSecret,
|
|
24
|
+
grant_type: "authorization_code",
|
|
25
|
+
redirect_uri: redirectUri,
|
|
26
|
+
code,
|
|
27
|
+
});
|
|
28
|
+
const res = await fetch(`${FOURSQUARE_OAUTH}/access_token?${params}`);
|
|
29
|
+
const body = (await res.json().catch(() => null));
|
|
30
|
+
const token = typeof body?.access_token === "string" ? body.access_token : "";
|
|
31
|
+
if (!token) {
|
|
32
|
+
const reason = typeof body?.error === "string" ? body.error : "no token returned";
|
|
33
|
+
throw new Error(`Foursquare token exchange failed (HTTP ${res.status}): ${reason}`);
|
|
34
|
+
}
|
|
35
|
+
const self = new URLSearchParams({ oauth_token: token, v: FOURSQUARE_API_VERSION });
|
|
36
|
+
const me = await fetch(`${FOURSQUARE_API}/users/self?${self}`);
|
|
37
|
+
const user = (await me.json().catch(() => null))?.response?.user;
|
|
38
|
+
if (typeof user?.id !== "string" || !user.id) {
|
|
39
|
+
throw new Error(`Foursquare did not say who connected (HTTP ${me.status})`);
|
|
40
|
+
}
|
|
41
|
+
const name = [user.firstName, user.lastName]
|
|
42
|
+
.filter((part) => typeof part === "string" && part.length > 0)
|
|
43
|
+
.join(" ");
|
|
44
|
+
return { token, subject: user.id, name: name || null };
|
|
45
|
+
},
|
|
46
|
+
};
|
|
47
|
+
}
|