@wwchen/stack 0.1.0 → 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/README.md CHANGED
@@ -20,7 +20,9 @@ Requires Node 24. The peer dependencies are exact pins: `next`, `react`, `react-
20
20
  | `@wwchen/stack/auth` | `createAuth`: sessions, sign-in and sign-out, the hourly sign-in limit, safe redirect targets |
21
21
  | `@wwchen/stack/auth/better-auth` | the Better Auth provider (magic link, optional Google for existing users, opt-in `emailAndPassword` reached in-process through `provider.instance`) |
22
22
  | `@wwchen/stack/auth/proxy` | the `proxy.ts` helpers and `proxyMatcher` |
23
- | `@wwchen/stack/next` | `withStack(appConfig)` for `next.config.ts`, `apiHandler` and `readJson`, `cronRoute` and `healthRoute` |
23
+ | `@wwchen/stack/next` | `withStack(appConfig)` for `next.config.ts`, `apiHandler` and `readJson`, `cronRoute` (answers 500 when the job returns `alerting: true`) and `healthRoute` |
24
+ | `@wwchen/stack/connections` | connected accounts (not sign-in): `connectionTable`, `createConnections` (start and callback route handlers, `token`, `list`, `connected`, `disconnect`), the `foursquare` provider, AES-256-GCM token encryption under `TOKEN_ENCRYPTION_KEY` |
25
+ | `@wwchen/stack/jobs` | multi-person scheduled jobs: `failingSince` and `isNewFailure` (alert on a failure's first 24 hours only), `mapLimit` |
24
26
  | `@wwchen/stack/ui`, `/ui/icons`, `/ui/globals.css`, `/ui/app.css` | lew-ds wiring, theme cookie, icon sprite and its usage check, and the CSS partials |
25
27
  | `@wwchen/stack/configs/tsconfig.next.json`, `/configs/biome.json`, `/configs/vitest` | shared tool configs, consumed with `extends` or an import |
26
28
  | `@wwchen/stack/testing/next` | tests only: `inServerAction` runs a function in a real Next server-action scope, `thrownBy` reads a `redirect()`/`notFound()` |
@@ -28,6 +30,36 @@ Requires Node 24. The peer dependencies are exact pins: `next`, `react`, `react-
28
30
  Sign-in never creates users: every user is added first (`stack user:create`), has an email, and the
29
31
  email is unique, trimmed and lower-cased.
30
32
 
33
+ ### Connected accounts
34
+
35
+ An app that works on someone's behalf at another service (ifttt reads Foursquare check-ins) has the
36
+ person connect that account after signing in. A connection never signs anyone in and never creates
37
+ a user. Wiring, with `TOKEN_ENCRYPTION_KEY` set (`openssl rand -base64 32`, and kept forever: a new
38
+ key makes every stored token unreadable):
39
+
40
+ ```ts
41
+ // src/db/schema.ts
42
+ export const connection = connectionTable(appUser);
43
+
44
+ // src/lib/connections.ts
45
+ export const connections = createConnections({
46
+ db, table: connection, providers: [foursquare({ clientId, clientSecret })],
47
+ secret: env.BETTER_AUTH_SECRET, encryptionKey: env.TOKEN_ENCRYPTION_KEY, baseURL: env.APP_URL,
48
+ });
49
+
50
+ // app/api/connections/[provider]/start/route.ts — signed-in only
51
+ // return connections.start(session.user.id, provider, url.searchParams.get("next") ?? "/");
52
+ // app/api/connections/[provider]/callback/route.ts
53
+ // return connections.callback(request, session?.user.id ?? null);
54
+ ```
55
+
56
+ The callback lands on `next` with `?connection=<provider>&result=<code>`, where the code is one of
57
+ `connected`, `invalid`, `expired`, `wrong_user`, `denied`, `exchange` or `taken`. It accepts a code
58
+ only when the signed state holds, has not expired (10 minutes), this browser started the flow (a
59
+ one-off HttpOnly cookie) and the same person is still signed in. Register
60
+ `<APP_URL>/api/connections/<provider>/callback` as the provider's redirect URL. One account at a
61
+ provider can be connected to one person here; removing a person removes their connections.
62
+
31
63
  ## The `stack` command
32
64
 
33
65
  | Command | Does |
@@ -19,6 +19,8 @@ EMAIL_FROM=
19
19
  MAGIC_LINK_SINK_PATH=
20
20
  # Bearer secret for scheduled jobs only
21
21
  CRON_SECRET=
22
+ # Encrypts connected-account tokens: openssl rand -base64 32. Keep it forever (a new key orphans every token)
23
+ TOKEN_ENCRYPTION_KEY=
22
24
  # Bearer token for the health route's database probe
23
25
  HEALTH_TOKEN=
24
26
  # Sign in with Google: set both or neither
@@ -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
+ }
@@ -0,0 +1,156 @@
1
+ import type { AuthTables } from "../auth/better-auth/tables.ts";
2
+ /**
3
+ * The `connection` table: an account at another service that a signed-in person connected so the
4
+ * app can work on their behalf (ifttt's Foursquare). The app re-exports it from its schema next to
5
+ * the auth tables, so drizzle-kit generates it into the app's own migrations.
6
+ *
7
+ * - One connection per person per provider (reconnecting replaces the token).
8
+ * - One person per provider account (`subject`): an account already connected to someone else is
9
+ * refused, so two people can never share one account's data.
10
+ * - Removing the person removes their connections (the foreign key cascades in the same statement).
11
+ * - `token` is only ever ciphertext (`crypto.ts`).
12
+ */
13
+ export declare function connectionTable(appUser: AuthTables["appUser"]): import("drizzle-orm/pg-core").PgTableWithColumns<{
14
+ name: "connection";
15
+ schema: undefined;
16
+ columns: {
17
+ id: import("drizzle-orm/pg-core").PgColumn<{
18
+ name: "id";
19
+ tableName: "connection";
20
+ dataType: "string";
21
+ columnType: "PgUUID";
22
+ data: string;
23
+ driverParam: string;
24
+ notNull: true;
25
+ hasDefault: true;
26
+ isPrimaryKey: true;
27
+ isAutoincrement: false;
28
+ hasRuntimeDefault: false;
29
+ enumValues: undefined;
30
+ baseColumn: never;
31
+ identity: undefined;
32
+ generated: undefined;
33
+ }, {}, {}>;
34
+ userId: import("drizzle-orm/pg-core").PgColumn<{
35
+ name: "user_id";
36
+ tableName: "connection";
37
+ dataType: "string";
38
+ columnType: "PgUUID";
39
+ data: string;
40
+ driverParam: string;
41
+ notNull: true;
42
+ hasDefault: false;
43
+ isPrimaryKey: false;
44
+ isAutoincrement: false;
45
+ hasRuntimeDefault: false;
46
+ enumValues: undefined;
47
+ baseColumn: never;
48
+ identity: undefined;
49
+ generated: undefined;
50
+ }, {}, {}>;
51
+ provider: import("drizzle-orm/pg-core").PgColumn<{
52
+ name: "provider";
53
+ tableName: "connection";
54
+ dataType: "string";
55
+ columnType: "PgText";
56
+ data: string;
57
+ driverParam: string;
58
+ notNull: true;
59
+ hasDefault: false;
60
+ isPrimaryKey: false;
61
+ isAutoincrement: false;
62
+ hasRuntimeDefault: false;
63
+ enumValues: [string, ...string[]];
64
+ baseColumn: never;
65
+ identity: undefined;
66
+ generated: undefined;
67
+ }, {}, {}>;
68
+ subject: import("drizzle-orm/pg-core").PgColumn<{
69
+ name: "subject";
70
+ tableName: "connection";
71
+ dataType: "string";
72
+ columnType: "PgText";
73
+ data: string;
74
+ driverParam: string;
75
+ notNull: true;
76
+ hasDefault: false;
77
+ isPrimaryKey: false;
78
+ isAutoincrement: false;
79
+ hasRuntimeDefault: false;
80
+ enumValues: [string, ...string[]];
81
+ baseColumn: never;
82
+ identity: undefined;
83
+ generated: undefined;
84
+ }, {}, {}>;
85
+ name: import("drizzle-orm/pg-core").PgColumn<{
86
+ name: "name";
87
+ tableName: "connection";
88
+ dataType: "string";
89
+ columnType: "PgText";
90
+ data: string;
91
+ driverParam: string;
92
+ notNull: false;
93
+ hasDefault: false;
94
+ isPrimaryKey: false;
95
+ isAutoincrement: false;
96
+ hasRuntimeDefault: false;
97
+ enumValues: [string, ...string[]];
98
+ baseColumn: never;
99
+ identity: undefined;
100
+ generated: undefined;
101
+ }, {}, {}>;
102
+ token: import("drizzle-orm/pg-core").PgColumn<{
103
+ name: "token";
104
+ tableName: "connection";
105
+ dataType: "string";
106
+ columnType: "PgText";
107
+ data: string;
108
+ driverParam: string;
109
+ notNull: true;
110
+ hasDefault: false;
111
+ isPrimaryKey: false;
112
+ isAutoincrement: false;
113
+ hasRuntimeDefault: false;
114
+ enumValues: [string, ...string[]];
115
+ baseColumn: never;
116
+ identity: undefined;
117
+ generated: undefined;
118
+ }, {}, {}>;
119
+ createdAt: import("drizzle-orm/pg-core").PgColumn<{
120
+ name: "created_at";
121
+ tableName: "connection";
122
+ dataType: "date";
123
+ columnType: "PgTimestamp";
124
+ data: Date;
125
+ driverParam: string;
126
+ notNull: true;
127
+ hasDefault: true;
128
+ isPrimaryKey: false;
129
+ isAutoincrement: false;
130
+ hasRuntimeDefault: false;
131
+ enumValues: undefined;
132
+ baseColumn: never;
133
+ identity: undefined;
134
+ generated: undefined;
135
+ }, {}, {}>;
136
+ updatedAt: import("drizzle-orm/pg-core").PgColumn<{
137
+ name: "updated_at";
138
+ tableName: "connection";
139
+ dataType: "date";
140
+ columnType: "PgTimestamp";
141
+ data: Date;
142
+ driverParam: string;
143
+ notNull: true;
144
+ hasDefault: true;
145
+ isPrimaryKey: false;
146
+ isAutoincrement: false;
147
+ hasRuntimeDefault: false;
148
+ enumValues: undefined;
149
+ baseColumn: never;
150
+ identity: undefined;
151
+ generated: undefined;
152
+ }, {}, {}>;
153
+ };
154
+ dialect: "pg";
155
+ }>;
156
+ export type ConnectionTable = ReturnType<typeof connectionTable>;
@@ -0,0 +1,29 @@
1
+ import { pgTable, text, timestamp, unique, uuid } from "drizzle-orm/pg-core";
2
+ /**
3
+ * The `connection` table: an account at another service that a signed-in person connected so the
4
+ * app can work on their behalf (ifttt's Foursquare). The app re-exports it from its schema next to
5
+ * the auth tables, so drizzle-kit generates it into the app's own migrations.
6
+ *
7
+ * - One connection per person per provider (reconnecting replaces the token).
8
+ * - One person per provider account (`subject`): an account already connected to someone else is
9
+ * refused, so two people can never share one account's data.
10
+ * - Removing the person removes their connections (the foreign key cascades in the same statement).
11
+ * - `token` is only ever ciphertext (`crypto.ts`).
12
+ */
13
+ export function connectionTable(appUser) {
14
+ return pgTable("connection", {
15
+ id: uuid("id").primaryKey().defaultRandom(),
16
+ userId: uuid("user_id")
17
+ .notNull()
18
+ .references(() => appUser.id, { onDelete: "cascade" }),
19
+ provider: text("provider").notNull(),
20
+ subject: text("subject").notNull(),
21
+ name: text("name"),
22
+ token: text("token").notNull(),
23
+ createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
24
+ updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(),
25
+ }, (t) => [
26
+ unique("connection_user_provider").on(t.userId, t.provider),
27
+ unique("connection_provider_subject").on(t.provider, t.subject),
28
+ ]);
29
+ }
@@ -20,6 +20,7 @@ export declare const stackEnvSchema: {
20
20
  EMAIL_FROM: z.ZodDefault<z.ZodString>;
21
21
  MAGIC_LINK_SINK_PATH: z.ZodDefault<z.ZodString>;
22
22
  CRON_SECRET: z.ZodOptional<z.ZodString>;
23
+ TOKEN_ENCRYPTION_KEY: z.ZodOptional<z.ZodString>;
23
24
  HEALTH_TOKEN: z.ZodOptional<z.ZodString>;
24
25
  GOOGLE_CLIENT_ID: z.ZodOptional<z.ZodString>;
25
26
  GOOGLE_CLIENT_SECRET: z.ZodOptional<z.ZodString>;
@@ -22,6 +22,14 @@ export const stackEnvSchema = {
22
22
  EMAIL_FROM: z.string().default("App <no-reply@example.invalid>"),
23
23
  MAGIC_LINK_SINK_PATH: z.string().default(".magic-links.log"),
24
24
  CRON_SECRET: z.string().optional(),
25
+ // Encrypts connected-account tokens (`@wwchen/stack/connections`): 32 bytes, base64
26
+ // (`openssl rand -base64 32`). Keep it forever: a new key makes every stored token unreadable.
27
+ TOKEN_ENCRYPTION_KEY: z
28
+ .string()
29
+ .refine((v) => Buffer.from(v, "base64").length === 32, {
30
+ message: "must be 32 bytes, base64-encoded (openssl rand -base64 32)",
31
+ })
32
+ .optional(),
25
33
  HEALTH_TOKEN: z.string().optional(),
26
34
  // Sign in with Google. Both or neither (group `google`).
27
35
  GOOGLE_CLIENT_ID: z.string().optional(),
@@ -0,0 +1,37 @@
1
+ /**
2
+ * Helpers for scheduled jobs that work for many people (ifttt syncs everyone's check-ins).
3
+ *
4
+ * **Alert on new failures only.** An uptime monitor that calls the job alerts when it answers 500.
5
+ * If every failure answered 500, one person whose sync is broken would hold the monitor down for
6
+ * good, and the next person to break would raise no alert. So a failure counts as *new* for its
7
+ * first `ALERT_FOR_HOURS` (24h) and the job answers 500 only while someone's failure is new
8
+ * (`cronRoute` does that when the job returns `alerting: true`). The person stays marked failing in
9
+ * the app until fixed; the monitor recovers and is free to alert on the next streak.
10
+ */
11
+ export declare const ALERT_FOR_HOURS = 24;
12
+ type Timestamp = string | Date;
13
+ export type RunOutcome = {
14
+ ok: boolean;
15
+ startedAt: Timestamp;
16
+ /** When the failure streak this run belongs to began; carried from run to run. */
17
+ failingSince?: Timestamp | null;
18
+ };
19
+ /**
20
+ * When `run`'s failure streak began: the previous run's streak start when that one failed too,
21
+ * otherwise `run` itself. Null for a successful run. `previous` is the person's last real (not
22
+ * dry-run) run before this one.
23
+ */
24
+ export declare function failingSince(run: {
25
+ ok: boolean;
26
+ startedAt: Timestamp;
27
+ }, previous: RunOutcome | null | undefined): string | null;
28
+ /** A failed run whose streak began less than `alertForHours` ago. */
29
+ export declare function isNewFailure(run: RunOutcome, now?: number, alertForHours?: number): boolean;
30
+ /**
31
+ * `fn` over `items`, at most `limit` at a time, results in input order. A job that works for many
32
+ * people shares one external quota (ifttt: one Google service account) and one function timeout,
33
+ * so it neither runs them one by one nor all at once. A rejection rejects the whole call: `fn`
34
+ * catches its own per-person failures.
35
+ */
36
+ export declare function mapLimit<T, R>(items: readonly T[], limit: number, fn: (item: T, index: number) => Promise<R>): Promise<R[]>;
37
+ export {};
@@ -0,0 +1,51 @@
1
+ /**
2
+ * Helpers for scheduled jobs that work for many people (ifttt syncs everyone's check-ins).
3
+ *
4
+ * **Alert on new failures only.** An uptime monitor that calls the job alerts when it answers 500.
5
+ * If every failure answered 500, one person whose sync is broken would hold the monitor down for
6
+ * good, and the next person to break would raise no alert. So a failure counts as *new* for its
7
+ * first `ALERT_FOR_HOURS` (24h) and the job answers 500 only while someone's failure is new
8
+ * (`cronRoute` does that when the job returns `alerting: true`). The person stays marked failing in
9
+ * the app until fixed; the monitor recovers and is free to alert on the next streak.
10
+ */
11
+ export const ALERT_FOR_HOURS = 24;
12
+ const ms = (t) => (typeof t === "string" ? Date.parse(t) : t.getTime());
13
+ const iso = (t) => (typeof t === "string" ? t : t.toISOString());
14
+ /**
15
+ * When `run`'s failure streak began: the previous run's streak start when that one failed too,
16
+ * otherwise `run` itself. Null for a successful run. `previous` is the person's last real (not
17
+ * dry-run) run before this one.
18
+ */
19
+ export function failingSince(run, previous) {
20
+ if (run.ok)
21
+ return null;
22
+ if (previous && !previous.ok)
23
+ return iso(previous.failingSince ?? previous.startedAt);
24
+ return iso(run.startedAt);
25
+ }
26
+ /** A failed run whose streak began less than `alertForHours` ago. */
27
+ export function isNewFailure(run, now = Date.now(), alertForHours = ALERT_FOR_HOURS) {
28
+ if (run.ok)
29
+ return false;
30
+ return now - ms(run.failingSince ?? run.startedAt) < alertForHours * 3_600_000;
31
+ }
32
+ /**
33
+ * `fn` over `items`, at most `limit` at a time, results in input order. A job that works for many
34
+ * people shares one external quota (ifttt: one Google service account) and one function timeout,
35
+ * so it neither runs them one by one nor all at once. A rejection rejects the whole call: `fn`
36
+ * catches its own per-person failures.
37
+ */
38
+ export async function mapLimit(items, limit, fn) {
39
+ if (!Number.isInteger(limit) || limit < 1)
40
+ throw new Error("mapLimit: limit must be at least 1");
41
+ const results = new Array(items.length);
42
+ let next = 0;
43
+ const worker = async () => {
44
+ while (next < items.length) {
45
+ const i = next++;
46
+ results[i] = await fn(items[i], i);
47
+ }
48
+ };
49
+ await Promise.all(Array.from({ length: Math.min(limit, items.length) }, worker));
50
+ return results;
51
+ }
@@ -4,6 +4,9 @@
4
4
  * refused (an empty bearer is not accepted), and the response is whatever `fn` returned, which
5
5
  * must be counts. No row data, no ids, no messages.
6
6
  *
7
+ * A job that returns `alerting: true` answers 500 with the same counts, so an uptime monitor calling
8
+ * it alerts: a multi-person job sets it while someone's failure is new (`@wwchen/stack/jobs`).
9
+ *
7
10
  * `export const GET = cronRoute(tick, { secret: env.CRON_SECRET })`.
8
11
  */
9
12
  export declare function cronRoute(fn: (req: Request) => Promise<unknown>, opts: {
package/dist/next/cron.js CHANGED
@@ -6,6 +6,9 @@ import { apiError } from "./api.js";
6
6
  * refused (an empty bearer is not accepted), and the response is whatever `fn` returned, which
7
7
  * must be counts. No row data, no ids, no messages.
8
8
  *
9
+ * A job that returns `alerting: true` answers 500 with the same counts, so an uptime monitor calling
10
+ * it alerts: a multi-person job sets it while someone's failure is new (`@wwchen/stack/jobs`).
11
+ *
9
12
  * `export const GET = cronRoute(tick, { secret: env.CRON_SECRET })`.
10
13
  */
11
14
  export function cronRoute(fn, opts) {
@@ -22,7 +25,11 @@ export function cronRoute(fn, opts) {
22
25
  }
23
26
  try {
24
27
  const counts = await fn(req);
25
- return Response.json(counts ?? {}, { headers: { "cache-control": "no-store" } });
28
+ const alerting = counts?.alerting === true;
29
+ return Response.json(counts ?? {}, {
30
+ status: alerting ? 500 : 200,
31
+ headers: { "cache-control": "no-store" },
32
+ });
26
33
  }
27
34
  catch (error) {
28
35
  // A short-lived function can be frozen before a logger drains, so this is the one line.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@wwchen/stack",
3
- "version": "0.1.0",
3
+ "version": "0.2.0",
4
4
  "description": "Shared Next.js, Neon, Better Auth, Resend and lew-ds building blocks.",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -57,6 +57,14 @@
57
57
  "types": "./dist/auth/proxy.d.ts",
58
58
  "default": "./dist/auth/proxy.js"
59
59
  },
60
+ "./connections": {
61
+ "types": "./dist/connections/index.d.ts",
62
+ "default": "./dist/connections/index.js"
63
+ },
64
+ "./jobs": {
65
+ "types": "./dist/jobs/index.d.ts",
66
+ "default": "./dist/jobs/index.js"
67
+ },
60
68
  "./next": {
61
69
  "types": "./dist/next/index.d.ts",
62
70
  "default": "./dist/next/index.js"