@soroi/auth 0.0.0-stage → 0.1.1

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.
Files changed (52) hide show
  1. package/AGENTS.md +154 -0
  2. package/LICENSE +21 -0
  3. package/README.md +26 -2
  4. package/dist/account.d.ts +52 -0
  5. package/dist/account.js +177 -0
  6. package/dist/adapters/next.d.ts +6 -0
  7. package/dist/adapters/next.js +35 -0
  8. package/dist/adapters/tanstack.d.ts +12 -0
  9. package/dist/adapters/tanstack.js +40 -0
  10. package/dist/cli.d.ts +2 -0
  11. package/dist/cli.js +76 -0
  12. package/dist/core.d.ts +122 -0
  13. package/dist/core.js +351 -0
  14. package/dist/crypto.d.ts +12 -0
  15. package/dist/crypto.js +69 -0
  16. package/dist/db.d.ts +29 -0
  17. package/dist/db.js +55 -0
  18. package/dist/email.d.ts +9 -0
  19. package/dist/email.js +64 -0
  20. package/dist/errors.d.ts +24 -0
  21. package/dist/errors.js +88 -0
  22. package/dist/index.d.ts +202 -0
  23. package/dist/index.js +255 -0
  24. package/dist/methods.d.ts +16 -0
  25. package/dist/methods.js +21 -0
  26. package/dist/migrations.d.ts +5 -0
  27. package/dist/migrations.js +154 -0
  28. package/dist/modules/oauth-server.d.ts +110 -0
  29. package/dist/modules/oauth-server.js +568 -0
  30. package/dist/modules/tokens.d.ts +31 -0
  31. package/dist/modules/tokens.js +107 -0
  32. package/dist/modules/two-factor.d.ts +41 -0
  33. package/dist/modules/two-factor.js +169 -0
  34. package/dist/modules/workspaces.d.ts +140 -0
  35. package/dist/modules/workspaces.js +297 -0
  36. package/dist/oauth/flow.d.ts +5 -0
  37. package/dist/oauth/flow.js +161 -0
  38. package/dist/oauth/providers.d.ts +29 -0
  39. package/dist/oauth/providers.js +124 -0
  40. package/dist/password-hash.d.ts +8 -0
  41. package/dist/password-hash.js +68 -0
  42. package/dist/password.d.ts +49 -0
  43. package/dist/password.js +181 -0
  44. package/dist/routes.d.ts +5 -0
  45. package/dist/routes.js +77 -0
  46. package/dist/sessions.d.ts +51 -0
  47. package/dist/sessions.js +184 -0
  48. package/dist/testing.d.ts +15 -0
  49. package/dist/testing.js +32 -0
  50. package/dist/types.d.ts +184 -0
  51. package/dist/types.js +1 -0
  52. package/package.json +75 -4
@@ -0,0 +1,21 @@
1
+ /** Google sign-in. Redirect URI: `<url>/auth/google/callback`. */
2
+ export function google(clientId, clientSecret, options = {}) {
3
+ return { kind: "oauth", id: "google", clientId: clientId ?? "", clientSecret: clientSecret ?? "", ...options };
4
+ }
5
+ /** GitHub sign-in. Callback URL: `<url>/auth/github/callback`. */
6
+ export function github(clientId, clientSecret, options = {}) {
7
+ return { kind: "oauth", id: "github", clientId: clientId ?? "", clientSecret: clientSecret ?? "", ...options };
8
+ }
9
+ export function password(options = {}) {
10
+ return { kind: "password", verifyEmail: options.verifyEmail ?? true, minLength: options.minLength ?? 10, ...options };
11
+ }
12
+ /**
13
+ * Allows only the listed e-mails. An entry that starts with "@" allows a whole domain.
14
+ * Accepts an array or a comma-separated string, e.g. `allowlist(env.ADMIN_EMAILS)`.
15
+ */
16
+ export function allowlist(entries) {
17
+ const list = (typeof entries === "string" ? entries.split(",") : (entries ?? []))
18
+ .map((entry) => entry.trim().toLowerCase())
19
+ .filter(Boolean);
20
+ return (email) => list.some((entry) => (entry.startsWith("@") ? email.endsWith(entry) : email === entry));
21
+ }
@@ -0,0 +1,5 @@
1
+ import type { Db } from "./db.js";
2
+ export declare const latestMigration: number;
3
+ export declare function appliedMigration(db: Db, s: string): Promise<number>;
4
+ /** Applies pending migrations in one transaction. The advisory lock lets several app instances start at once. */
5
+ export declare function migrate(db: Db, s: string): Promise<number[]>;
@@ -0,0 +1,154 @@
1
+ import { oauthServerTables } from "./modules/oauth-server.js";
2
+ // Append only. Never edit a migration that has shipped; add a new one.
3
+ const migrations = [
4
+ {
5
+ id: 1,
6
+ statements: (s) => [
7
+ `create table ${s}.users (
8
+ id uuid primary key default gen_random_uuid(),
9
+ email text not null unique,
10
+ email_verified_at timestamptz,
11
+ name text,
12
+ image text,
13
+ password_hash text,
14
+ created_at timestamptz not null default now(),
15
+ updated_at timestamptz not null default now()
16
+ )`,
17
+ `create table ${s}.accounts (
18
+ provider text not null,
19
+ provider_user_id text not null,
20
+ user_id uuid not null references ${s}.users(id) on delete cascade,
21
+ email text,
22
+ created_at timestamptz not null default now(),
23
+ primary key (provider, provider_user_id)
24
+ )`,
25
+ `create index accounts_user_id_idx on ${s}.accounts(user_id)`,
26
+ `create table ${s}.workspaces (
27
+ id uuid primary key default gen_random_uuid(),
28
+ name text not null,
29
+ created_at timestamptz not null default now()
30
+ )`,
31
+ `create table ${s}.members (
32
+ workspace_id uuid not null references ${s}.workspaces(id) on delete cascade,
33
+ user_id uuid not null references ${s}.users(id) on delete cascade,
34
+ role text not null,
35
+ created_at timestamptz not null default now(),
36
+ primary key (workspace_id, user_id)
37
+ )`,
38
+ `create index members_user_id_idx on ${s}.members(user_id)`,
39
+ `create table ${s}.invites (
40
+ id text primary key,
41
+ workspace_id uuid not null references ${s}.workspaces(id) on delete cascade,
42
+ email text not null,
43
+ role text not null,
44
+ invited_by uuid references ${s}.users(id) on delete set null,
45
+ expires_at timestamptz not null,
46
+ created_at timestamptz not null default now(),
47
+ unique (workspace_id, email)
48
+ )`,
49
+ `create table ${s}.sessions (
50
+ id text primary key,
51
+ user_id uuid not null references ${s}.users(id) on delete cascade,
52
+ method text not null,
53
+ workspace_id uuid references ${s}.workspaces(id) on delete set null,
54
+ ip text,
55
+ user_agent text,
56
+ created_at timestamptz not null default now(),
57
+ last_seen_at timestamptz not null default now(),
58
+ reauth_at timestamptz not null default now(),
59
+ expires_at timestamptz not null
60
+ )`,
61
+ `create index sessions_user_id_idx on ${s}.sessions(user_id)`,
62
+ `create table ${s}.email_tokens (
63
+ id text primary key,
64
+ kind text not null,
65
+ user_id uuid not null references ${s}.users(id) on delete cascade,
66
+ email text not null,
67
+ browser text,
68
+ expires_at timestamptz not null,
69
+ created_at timestamptz not null default now()
70
+ )`,
71
+ `create index email_tokens_user_id_idx on ${s}.email_tokens(user_id)`,
72
+ `create table ${s}.challenges (
73
+ id text primary key,
74
+ user_id uuid not null references ${s}.users(id) on delete cascade,
75
+ method text not null,
76
+ next text,
77
+ attempts int not null default 0,
78
+ expires_at timestamptz not null
79
+ )`,
80
+ `create table ${s}.rate_limits (
81
+ key text primary key,
82
+ window_start timestamptz not null,
83
+ count int not null
84
+ )`,
85
+ `create table ${s}.two_factor (
86
+ user_id uuid primary key references ${s}.users(id) on delete cascade,
87
+ secret text not null,
88
+ last_counter bigint not null default 0,
89
+ enabled_at timestamptz,
90
+ created_at timestamptz not null default now()
91
+ )`,
92
+ `create table ${s}.recovery_codes (
93
+ id text primary key,
94
+ user_id uuid not null references ${s}.users(id) on delete cascade,
95
+ used_at timestamptz
96
+ )`,
97
+ `create index recovery_codes_user_id_idx on ${s}.recovery_codes(user_id)`,
98
+ `create table ${s}.api_tokens (
99
+ id text primary key,
100
+ user_id uuid not null references ${s}.users(id) on delete cascade,
101
+ workspace_id uuid references ${s}.workspaces(id) on delete cascade,
102
+ name text not null,
103
+ prefix text not null,
104
+ scopes text not null default '',
105
+ created_at timestamptz not null default now(),
106
+ last_used_at timestamptz,
107
+ expires_at timestamptz
108
+ )`,
109
+ `create index api_tokens_user_id_idx on ${s}.api_tokens(user_id)`,
110
+ ],
111
+ },
112
+ {
113
+ id: 2,
114
+ statements: (s) => [
115
+ `alter table ${s}.sessions add column provider_email text`,
116
+ `alter table ${s}.challenges add column provider_email text`,
117
+ ],
118
+ },
119
+ { id: 3, statements: oauthServerTables },
120
+ {
121
+ // Apps that share the users table can tell who has a password without access to the hashes.
122
+ id: 4,
123
+ statements: (s) => [
124
+ `alter table ${s}.users add column has_password boolean not null generated always as (password_hash is not null) stored`,
125
+ ],
126
+ },
127
+ ];
128
+ export const latestMigration = migrations.at(-1).id;
129
+ export async function appliedMigration(db, s) {
130
+ const [row] = await db.query("select to_regclass($1) is not null as exists", [`${s}.migrations`]);
131
+ if (!row?.exists)
132
+ return 0;
133
+ const [last] = await db.query(`select max(id)::int as id from ${s}.migrations`);
134
+ return last?.id ?? 0;
135
+ }
136
+ /** Applies pending migrations in one transaction. The advisory lock lets several app instances start at once. */
137
+ export async function migrate(db, s) {
138
+ return db.transaction(async (tx) => {
139
+ await tx.query("select pg_advisory_xact_lock(hashtext($1))", [`soroi-auth:${s}`]);
140
+ await tx.query(`create schema if not exists ${s}`);
141
+ await tx.query(`create table if not exists ${s}.migrations (id int primary key, applied_at timestamptz not null default now())`);
142
+ const done = new Set((await tx.query(`select id from ${s}.migrations`)).map((r) => Number(r.id)));
143
+ const applied = [];
144
+ for (const migration of migrations) {
145
+ if (done.has(migration.id))
146
+ continue;
147
+ for (const statement of migration.statements(s))
148
+ await tx.query(statement);
149
+ await tx.query(`insert into ${s}.migrations (id) values ($1)`, [migration.id]);
150
+ applied.push(migration.id);
151
+ }
152
+ return applied;
153
+ });
154
+ }
@@ -0,0 +1,110 @@
1
+ import { type Db } from "../db.js";
2
+ export declare const ACCESS_TOKEN_SECONDS = 3600;
3
+ export declare const REFRESH_TOKEN_SECONDS: number;
4
+ export type OAuthServerError = "invalid_request" | "invalid_client" | "invalid_grant" | "invalid_target" | "unsupported_grant_type" | "invalid_redirect_uri" | "invalid_client_metadata";
5
+ /**
6
+ * Null when the URI may be a redirect target: https, http on a loopback host, or a private-use
7
+ * scheme of a native app (RFC 8252, e.g. cursor://). The consent page sends the browser there,
8
+ * so a script scheme would run as the signed-in user.
9
+ */
10
+ export declare function redirectUriProblem(value: unknown): string | null;
11
+ /** Exact match. Loopback redirects may use another port (RFC 8252 section 7.3). */
12
+ export declare function redirectUriMatches(registered: string, requested: string): boolean;
13
+ export type RedirectTarget = {
14
+ /** `loopback`: a program on the person's own computer. `app`: an installed app's own scheme. `web`: a website. */
15
+ kind: "loopback" | "app" | "web";
16
+ /** The host, or the scheme for `app`. */
17
+ label: string;
18
+ };
19
+ export declare function redirectTarget(uri: string): RedirectTarget;
20
+ /** Fixed-window counters in memory, per process. */
21
+ export declare function createRateLimit(max: number, windowMs: number): (key: string, now?: number) => boolean;
22
+ /** The SQL of the module's tables, for apps that keep them in their own migrations. `s` is a quoted schema. */
23
+ export declare const oauthServerTables: (s: string) => string[];
24
+ export type OAuthServerConfig = {
25
+ /** The app's public URL without a trailing slash. It is the issuer. */
26
+ url: string;
27
+ /** The URL that the tokens are for, e.g. `${url}/mcp`. Tokens of another resource do not work here. */
28
+ resource: string;
29
+ name: string;
30
+ /** A database URL (Bun only) or an adapter, e.g. `pg(pool)`. It may be another database than the one of `createAuth`. */
31
+ db: Db | string;
32
+ /** Postgres schema of the tables. Default "auth", where the package's migrations make them. */
33
+ schema?: string;
34
+ /** Paths of the endpoints. Default `/oauth/{authorize,token,register,revoke}`. */
35
+ paths?: Partial<{
36
+ authorize: string;
37
+ token: string;
38
+ register: string;
39
+ revoke: string;
40
+ }>;
41
+ /** The app's consent page. It gets `?consent_code=`. */
42
+ consentPage: string;
43
+ scopes?: string[];
44
+ /**
45
+ * The signed-in person, or null. Only a finished browser session counts: refuse API tokens.
46
+ * `@soroi/auth` makes a session only after the second factor, so `auth.session()` is enough.
47
+ */
48
+ viewer(request: Request): Promise<{
49
+ id: string;
50
+ } | null>;
51
+ /** The sign-in page link that comes back to `back`. */
52
+ signIn(back: string): string;
53
+ /** False when the person removed the connection. Checked before every token is issued. */
54
+ isConnected(db: Db, connection: {
55
+ userId: string;
56
+ clientId: string;
57
+ }): Promise<boolean>;
58
+ /** The client IP for rate limits. Default: the last `x-forwarded-for` entry, then `x-real-ip`. */
59
+ ip?: (request: Request) => string | null;
60
+ /** Default true. Counters live in memory, per process. */
61
+ rateLimit?: boolean;
62
+ headers?: Record<string, string>;
63
+ now?: () => Date;
64
+ };
65
+ export type PendingConsent = {
66
+ id: string;
67
+ clientId: string;
68
+ clientName: string | null;
69
+ expired: boolean;
70
+ redirect: RedirectTarget;
71
+ /** The client registered less than an hour ago. Nobody verified its name. */
72
+ justRegistered: boolean;
73
+ };
74
+ export declare function createOAuthServer(config: OAuthServerConfig): {
75
+ handlers: {
76
+ register(request: Request): Promise<Response>;
77
+ /** Checks the client first, then the sign-in. A signed-in person always lands on the consent page. */
78
+ authorize(request: Request): Promise<Response>;
79
+ token(request: Request): Promise<Response>;
80
+ /** Answers ok for unknown tokens too, so callers learn nothing. */
81
+ revoke(request: Request): Promise<Response>;
82
+ preflight: () => Response;
83
+ /** RFC 8414, for `/.well-known/oauth-authorization-server`. */
84
+ serverMetadata: () => Response;
85
+ /** RFC 9728, for `/.well-known/oauth-protected-resource`. */
86
+ resourceMetadata: () => Response;
87
+ };
88
+ pending: (input: {
89
+ consentCode: string;
90
+ userId: string;
91
+ }, db?: Db) => Promise<PendingConsent | null>;
92
+ approve: (input: {
93
+ consentCode: string;
94
+ userId: string;
95
+ }, db?: Db) => Promise<string | null>;
96
+ deny: (input: {
97
+ consentCode: string;
98
+ userId: string;
99
+ }, db?: Db) => Promise<string | null>;
100
+ verifyAccessToken: (token: string) => Promise<{
101
+ clientId: string;
102
+ userId: string;
103
+ scope: string;
104
+ } | null>;
105
+ revokeConnection: (input: {
106
+ clientId: string;
107
+ userId: string;
108
+ }, db?: Db) => Promise<void>;
109
+ };
110
+ export type OAuthServer = ReturnType<typeof createOAuthServer>;