direct-auth 0.0.0-stage → 0.1.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 +486 -2
- package/dist/accounts.d.ts +118 -0
- package/dist/accounts.js +314 -0
- package/dist/apps.d.ts +85 -0
- package/dist/apps.js +449 -0
- package/dist/auth.d.ts +396 -0
- package/dist/auth.js +699 -0
- package/dist/base64.d.ts +20 -0
- package/dist/base64.js +45 -0
- package/dist/cli.d.ts +2 -0
- package/dist/cli.js +463 -0
- package/dist/client.d.ts +170 -0
- package/dist/client.js +438 -0
- package/dist/codes.d.ts +81 -0
- package/dist/codes.js +91 -0
- package/dist/crypto.d.ts +11 -0
- package/dist/crypto.js +37 -0
- package/dist/d1.d.ts +2 -0
- package/dist/d1.js +2 -0
- package/dist/db/limits.d.ts +16 -0
- package/dist/db/limits.js +23 -0
- package/dist/db/schema.d.ts +25 -0
- package/dist/db/schema.js +136 -0
- package/dist/db/sql.d.ts +52 -0
- package/dist/db/sql.js +121 -0
- package/dist/dns.d.ts +48 -0
- package/dist/dns.js +133 -0
- package/dist/env.d.ts +39 -0
- package/dist/env.js +169 -0
- package/dist/index.d.ts +19 -0
- package/dist/index.js +14 -0
- package/dist/init.d.ts +134 -0
- package/dist/init.js +912 -0
- package/dist/jwks.d.ts +18 -0
- package/dist/jwks.js +63 -0
- package/dist/jwt.d.ts +90 -0
- package/dist/jwt.js +99 -0
- package/dist/keys.d.ts +33 -0
- package/dist/keys.js +54 -0
- package/dist/messages.d.ts +26 -0
- package/dist/messages.js +57 -0
- package/dist/migrate-cli.d.ts +82 -0
- package/dist/migrate-cli.js +564 -0
- package/dist/migrate.d.ts +99 -0
- package/dist/migrate.js +396 -0
- package/dist/node.d.ts +16 -0
- package/dist/node.js +63 -0
- package/dist/passkeys.d.ts +126 -0
- package/dist/passkeys.js +383 -0
- package/dist/passwords.d.ts +53 -0
- package/dist/passwords.js +326 -0
- package/dist/pgwire.d.ts +86 -0
- package/dist/pgwire.js +445 -0
- package/dist/phone.d.ts +11 -0
- package/dist/phone.js +18 -0
- package/dist/postgres.d.ts +2 -0
- package/dist/postgres.js +2 -0
- package/dist/providers/apple-revoke.d.ts +55 -0
- package/dist/providers/apple-revoke.js +113 -0
- package/dist/providers/apple.d.ts +28 -0
- package/dist/providers/apple.js +51 -0
- package/dist/providers/github.d.ts +28 -0
- package/dist/providers/github.js +67 -0
- package/dist/providers/google.d.ts +23 -0
- package/dist/providers/google.js +47 -0
- package/dist/providers/identity.d.ts +24 -0
- package/dist/providers/identity.js +3 -0
- package/dist/proxy.d.ts +19 -0
- package/dist/proxy.js +43 -0
- package/dist/records.d.ts +91 -0
- package/dist/records.js +264 -0
- package/dist/scrypt.d.ts +26 -0
- package/dist/scrypt.js +179 -0
- package/dist/senders/aws.d.ts +13 -0
- package/dist/senders/aws.js +47 -0
- package/dist/senders/dev.d.ts +6 -0
- package/dist/senders/dev.js +13 -0
- package/dist/senders/index.d.ts +5 -0
- package/dist/senders/index.js +4 -0
- package/dist/senders/mail.d.ts +26 -0
- package/dist/senders/mail.js +66 -0
- package/dist/senders/sms.d.ts +34 -0
- package/dist/senders/sms.js +69 -0
- package/dist/senders/smtp.d.ts +32 -0
- package/dist/senders/smtp.js +145 -0
- package/dist/senders/types.d.ts +31 -0
- package/dist/senders/types.js +25 -0
- package/dist/server.d.ts +67 -0
- package/dist/server.js +494 -0
- package/dist/sessions.d.ts +74 -0
- package/dist/sessions.js +146 -0
- package/dist/skill.d.ts +25 -0
- package/dist/skill.js +66 -0
- package/dist/sources.d.ts +138 -0
- package/dist/sources.js +931 -0
- package/dist/sqlite.d.ts +2 -0
- package/dist/sqlite.js +2 -0
- package/dist/stores/d1.d.ts +22 -0
- package/dist/stores/d1.js +23 -0
- package/dist/stores/postgres.d.ts +33 -0
- package/dist/stores/postgres.js +71 -0
- package/dist/stores/sqlite.d.ts +27 -0
- package/dist/stores/sqlite.js +55 -0
- package/dist/supabase.d.ts +71 -0
- package/dist/supabase.js +283 -0
- package/dist/tui.d.ts +178 -0
- package/dist/tui.js +537 -0
- package/package.json +90 -4
- package/skills/direct-auth/SKILL.md +101 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Guille Cura
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,487 @@
|
|
|
1
|
-
#
|
|
1
|
+
# direct-auth
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
<!-- header -->
|
|
4
|
+
<p align="center">
|
|
5
|
+
<a href="https://whitebear.io/en/oss/direct-auth"><img src="https://whitebear.io/og/oss/direct-auth.en.png" alt="direct-auth: sign-in from your own backend, with Apple, Google, GitHub, codes, passkeys and passwords" width="760"></a>
|
|
6
|
+
</p>
|
|
7
|
+
|
|
8
|
+
<p align="center">
|
|
9
|
+
<a href="https://www.npmjs.com/package/direct-auth"><img src="https://img.shields.io/npm/v/direct-auth?style=flat-square&color=111317&labelColor=111317" alt="npm version"></a>
|
|
10
|
+
<a href="LICENSE"><img src="https://img.shields.io/npm/l/direct-auth?style=flat-square&color=111317&labelColor=111317" alt="MIT license"></a>
|
|
11
|
+
<img src="https://img.shields.io/badge/dependencies-0-111317?style=flat-square&labelColor=111317" alt="zero dependencies">
|
|
12
|
+
</p>
|
|
13
|
+
|
|
14
|
+
<p align="center">
|
|
15
|
+
<a href="https://whitebear.io/en/oss/direct-auth"><b>Website</b></a> |
|
|
16
|
+
<a href="https://whitebear.io/en/oss/direct-auth/docs"><b>Docs</b></a> |
|
|
17
|
+
<a href="https://www.npmjs.com/package/direct-auth"><b>npm</b></a> |
|
|
18
|
+
<a href="https://github.com/guillecura/direct-auth"><b>GitHub</b></a>
|
|
19
|
+
</p>
|
|
20
|
+
<!-- /header -->
|
|
21
|
+
|
|
22
|
+
**Sign-in from your own backend.** Sign in with Apple, Google, GitHub, email and SMS codes, passwords, passkeys and guests, checked by your server with WebCrypto and fetch, with accounts and sessions on the database you already have: no Auth0, no Firebase Auth, no hosted auth service and zero dependencies. On Deno, Node, Bun and Workers, with clients for iOS, Android and the web.
|
|
23
|
+
|
|
24
|
+
```sh
|
|
25
|
+
npx direct-auth init
|
|
26
|
+
# → asks where the server runs, the address of your sign-in (auth.example.com) and which ways in; takes Apple's
|
|
27
|
+
# .p8 and checks it with Apple, the Google client IDs, the mail and SMS senders (and sends you a test code);
|
|
28
|
+
# shows the DNS records it all needs, makes them at Cloudflare if you like and waits until they answer; makes
|
|
29
|
+
# the signing key, writes it all to .env, and for Supabase or Cloudflare Workers runs the secrets command if you
|
|
30
|
+
# say so (no value is ever printed)
|
|
31
|
+
|
|
32
|
+
npx direct-auth app
|
|
33
|
+
# → in an app's folder: finds the web, Android and iOS/macOS projects and adds the client; the rest as steps
|
|
34
|
+
|
|
35
|
+
npx direct-auth dns example.com
|
|
36
|
+
# → SPF, DKIM and DMARC for the address the codes come from, and what is missing
|
|
37
|
+
|
|
38
|
+
npx direct-auth migrate
|
|
39
|
+
# → moves a Supabase project's users here, same ids: a dry run first (who moves, what needs a hand, by name),
|
|
40
|
+
# the way back written to a file, then the move in one transaction after you type move, once, and a check
|
|
41
|
+
|
|
42
|
+
npx direct-auth supabase-sql > move.sql
|
|
43
|
+
# → the same move as SQL, to read and run yourself
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
The tokens it gives out are standard: an ES256 JWT that anything trusting the server's published keys can check. That is what lets a Supabase project keep its data and its row level security while direct-auth signs people in (Supabase's Third-Party Auth: `auth.uid()` reads the token's `sub`), and what lets a project leave Supabase altogether and run it on its own server.
|
|
47
|
+
|
|
48
|
+
| Runtime | Server | From |
|
|
49
|
+
| --- | --- | --- |
|
|
50
|
+
| Deno, Supabase Edge Functions | `Deno.serve(server.fetch)` | `npm:direct-auth` |
|
|
51
|
+
| Node 22.18+, Bun (a server, a container, Vercel and Netlify functions with `trustProxy: true`) | `serve(server)`, or `Bun.serve({ fetch: server.fetch })` | `direct-auth`, `direct-auth/node` |
|
|
52
|
+
| Cloudflare Workers | `server.fetch` (SMTP isn't available: use an HTTP mail sender) | `direct-auth` |
|
|
53
|
+
| Browsers | the client | `direct-auth/client` |
|
|
54
|
+
|
|
55
|
+
| Database | Adapter |
|
|
56
|
+
| --- | --- |
|
|
57
|
+
| SQLite (a file: `node:sqlite`, `better-sqlite3`, `bun:sqlite`) | `direct-auth/sqlite` |
|
|
58
|
+
| Postgres (Supabase, Neon, Vercel Postgres, RDS, local, PGlite) | `direct-auth/postgres` |
|
|
59
|
+
| Cloudflare D1 | `direct-auth/d1` |
|
|
60
|
+
|
|
61
|
+
## Contents
|
|
62
|
+
|
|
63
|
+
- [What it does](#what-it-does)
|
|
64
|
+
- [Quick start](#quick-start): [Supabase](#on-supabase), [a server or container](#on-a-server-or-a-container), [Cloudflare](#on-cloudflare-workers)
|
|
65
|
+
- [Your own address](#your-own-address): why, and moving the server
|
|
66
|
+
- [Ways in](#ways-in): [Apple](#sign-in-with-apple), [Google](#google), [GitHub](#github), [email codes](#email-codes), [SMS codes](#sms-codes), [passwords](#passwords), [passkeys](#passkeys), [guests](#guests)
|
|
67
|
+
- [Linking and changing](#linking-and-changing)
|
|
68
|
+
- [Sessions and tokens](#sessions-and-tokens)
|
|
69
|
+
- [Accounts](#accounts)
|
|
70
|
+
- [The server](#the-server)
|
|
71
|
+
- [Connect an app](#connect-an-app): [iOS and macOS](#ios-and-macos), [Android](#android), [the web](#the-web)
|
|
72
|
+
- [Moving from Supabase Auth](#moving-from-supabase-auth), [and from elsewhere](#moving-from-firebase-authjs-better-auth-clerk-or-auth0)
|
|
73
|
+
- [Keys](#keys)
|
|
74
|
+
- [With an AI agent](#with-an-ai-agent)
|
|
75
|
+
- [Develop](#develop)
|
|
76
|
+
|
|
77
|
+
## What it does
|
|
78
|
+
|
|
79
|
+
- **Sign in with Apple**: the app's identity token, checked against Apple's keys. With the team's Sign in with Apple key on the server, the app's authorization code is kept (as Apple's refresh token, encrypted) so that deleting the account revokes it, as App Store guideline 5.1.1(v) asks; and Apple's server-to-server notices sign out a user who deleted their Apple account or stopped using it with the app.
|
|
80
|
+
- **Google**: the ID token from Credential Manager on Android, Google Sign-In on iOS or Google Identity Services on the web, checked against Google's keys.
|
|
81
|
+
- **GitHub**: GitHub's web sign-in in the browser, an in-app browser sheet or a Custom Tab; the server trades the code (PKCE) and keeps no GitHub token.
|
|
82
|
+
- **Email and SMS codes**: six digits, ten minutes, five tries, stored as an HMAC and never as they are. Limits per address or number, per IP and, for SMS, per country and per day, kept in the database so they hold across instances. SMS goes only to the countries you list.
|
|
83
|
+
- **Passwords**, if you want them: email and password, the address proved by a code before a password works, hashed with PBKDF2-SHA256 (600,000 rounds) through WebCrypto. Supabase's bcrypt hashes are taken as they are and replaced at each user's next sign-in. Limited per IP and per address, and a wrong password reads the same as an unknown address.
|
|
84
|
+
- **Passkeys**: WebAuthn registration and sign-in, checked with WebCrypto, for the web, iOS and Android. Supabase's passkeys move with the users.
|
|
85
|
+
- **Guests**: in first, signed up later. A guest links Apple, Google, an address or a password and keeps its id and everything stored under it; the token says `is_anonymous`, as Supabase's did.
|
|
86
|
+
- **Accounts**: one user, many ways in. An Apple or Google account and an email code with the same address the provider checked are one person; an address nobody checked never joins two accounts. (So whoever holds the mailbox holds the account, as with any email sign-in; and a phone number given up and handed to someone else takes its account with it, as with any SMS sign-in.) Deleting a user deletes everything here that was theirs and calls your hook.
|
|
87
|
+
- **Sessions**: an access token of one hour (an ES256 JWT) and a refresh token that changes at each use. A refresh token used again (copied off a device) ends the session; only a second use within ten seconds, two requests of one app racing, is let through.
|
|
88
|
+
- **An issuer**: `/.well-known/openid-configuration` and `/.well-known/jwks.json`, for Supabase, PostgREST, Hasura or your own API.
|
|
89
|
+
- **Senders included**: Resend, Postmark, Mailgun, SendGrid, Amazon SES and SMTP for mail; Twilio, Vonage, Amazon SNS and an Android phone with a SIM for SMS. Or any function of your own.
|
|
90
|
+
|
|
91
|
+
## Quick start
|
|
92
|
+
|
|
93
|
+
### On Supabase
|
|
94
|
+
|
|
95
|
+
The data stays where it is; direct-auth runs as an Edge Function and signs people in.
|
|
96
|
+
|
|
97
|
+
```sh
|
|
98
|
+
npx direct-auth init # the address: auth.example.com (or Enter for https://<project-ref>.supabase.co/functions/v1/auth)
|
|
99
|
+
supabase functions deploy auth --no-verify-jwt
|
|
100
|
+
```
|
|
101
|
+
|
|
102
|
+
```ts
|
|
103
|
+
// supabase/functions/auth/index.ts
|
|
104
|
+
import postgres from "npm:postgres@3";
|
|
105
|
+
import { authFromEnv, createAuthServer } from "npm:direct-auth@0";
|
|
106
|
+
import { postgresJsSql } from "npm:direct-auth@0/postgres";
|
|
107
|
+
|
|
108
|
+
const sql = postgres(Deno.env.get("SUPABASE_DB_URL")!, { prepare: false });
|
|
109
|
+
const server = await createAuthServer({ sql: postgresJsSql(sql), ...authFromEnv(Deno.env.toObject()) });
|
|
110
|
+
Deno.serve((req) => server.fetch(req));
|
|
111
|
+
```
|
|
112
|
+
|
|
113
|
+
Then the project trusts the issuer (Supabase's Third-Party Auth). The dashboard lists named providers only; a generic OpenID issuer goes in through the Management API, which `npx direct-auth supabase-trust --project <ref> --issuer <issuer>` calls for you (with `SUPABASE_ACCESS_TOKEN`, showing the change first):
|
|
114
|
+
|
|
115
|
+
```sh
|
|
116
|
+
curl -X POST https://api.supabase.com/v1/projects/<ref>/config/auth/third-party-auth \
|
|
117
|
+
-H "Authorization: Bearer $SUPABASE_ACCESS_TOKEN" -H "content-type: application/json" \
|
|
118
|
+
-d '{"oidc_issuer_url":"https://auth.example.com/auth"}'
|
|
119
|
+
```
|
|
120
|
+
|
|
121
|
+
From then on the project's Data API, Storage and Realtime accept direct-auth's access tokens, and `auth.uid()` in your policies is the user's id. The clients give the token to supabase-js, supabase-swift and supabase-kt through their `accessToken` option. The tables (`auth_users`, `auth_identities`…) go in `public`, with row level security on and no policies, so only the function's own connection reaches them.
|
|
122
|
+
|
|
123
|
+
### On a server or a container
|
|
124
|
+
|
|
125
|
+
```ts
|
|
126
|
+
// server.ts: node --env-file=.env server.ts
|
|
127
|
+
import { authFromEnv, createAuthServer } from "direct-auth";
|
|
128
|
+
import { openSqlite } from "direct-auth/sqlite";
|
|
129
|
+
import { serve } from "direct-auth/node";
|
|
130
|
+
|
|
131
|
+
const server = await createAuthServer({ sql: await openSqlite("auth.db"), ...authFromEnv(process.env) });
|
|
132
|
+
setInterval(() => void server.auth.prune(), 60 * 60 * 1000).unref(); // spent codes and old counters
|
|
133
|
+
serve(server, { port: 8787, behindProxy: true }); // behind Caddy, Traefik or nginx
|
|
134
|
+
```
|
|
135
|
+
|
|
136
|
+
For Postgres, `pgSql(new pg.Pool())` from `direct-auth/postgres` in place of `openSqlite`. [examples/docker](examples/docker) has a Dockerfile and a compose file with Postgres, for a VPS: the proxy in front terminates TLS and routes `https://api.example.com/auth` to it.
|
|
137
|
+
|
|
138
|
+
### On Cloudflare Workers
|
|
139
|
+
|
|
140
|
+
```ts
|
|
141
|
+
import { authFromEnv, createAuthServer } from "direct-auth";
|
|
142
|
+
import { d1Sql } from "direct-auth/d1";
|
|
143
|
+
|
|
144
|
+
let server;
|
|
145
|
+
export default {
|
|
146
|
+
async fetch(req, env) {
|
|
147
|
+
server ??= createAuthServer({ sql: d1Sql(env.DB), ...authFromEnv(env) });
|
|
148
|
+
return (await server).fetch(req);
|
|
149
|
+
},
|
|
150
|
+
};
|
|
151
|
+
```
|
|
152
|
+
|
|
153
|
+
See [examples/cloudflare](examples/cloudflare) for `wrangler.toml` and the hourly prune.
|
|
154
|
+
|
|
155
|
+
## Your own address
|
|
156
|
+
|
|
157
|
+
The issuer is in every access token, in every app's settings and in Supabase's trust setting. On a name of your own (`https://auth.example.com/auth`) it stays the same wherever the server runs, so moving the server is invisible to users: nobody signs in again, no app update, the same tokens keep working. On `<ref>.supabase.co` it is tied to that project.
|
|
158
|
+
|
|
159
|
+
`npx direct-auth init` asks one question, the address of your sign-in, and does the rest for where the server runs:
|
|
160
|
+
|
|
161
|
+
- **A server or a container**: the A record for the name, pointed at the server's IP, shown to copy (or made at Cloudflare with a token you give), and waited for until it answers.
|
|
162
|
+
- **Supabase**: a small Cloudflare Worker on the name (`auth-proxy/`) passes `/auth/...` to the Edge Function, and Cloudflare makes its DNS record and certificate. With wrangler signed in, the wizard deploys it. The Worker sends the caller's IP with a secret only it and the server share (`DIRECT_AUTH_PROXY_SECRET`), so the rate limits count the right IP. The name's DNS must be at Cloudflare.
|
|
163
|
+
- **Cloudflare Workers**: the `routes` line for the Worker's `wrangler.toml`.
|
|
164
|
+
|
|
165
|
+
Then it asks `https://auth.example.com/auth/.well-known/openid-configuration` whether it names that issuer (`npx direct-auth issuer https://auth.example.com/auth` asks again any time).
|
|
166
|
+
|
|
167
|
+
Moving the server later, from Supabase to a VPS say, with the same data and the same keys:
|
|
168
|
+
|
|
169
|
+
1. `pg_dump` the database (`--schema=public` holds direct-auth's tables beside the app's; dump it all if the app's data moves too) and restore it on the new Postgres.
|
|
170
|
+
2. Start the server there with the same env: the same `DIRECT_AUTH_ISSUER` and the same `DIRECT_AUTH_SIGNING_KEYS` (and the senders' keys). On a VPS, `DATABASE_URL` points at the new database.
|
|
171
|
+
3. Point the name at the new server (the A record), and remove the proxy Worker's route if there was one.
|
|
172
|
+
|
|
173
|
+
The refresh tokens are in the database and the signing keys in the env, so sessions carry on: apps refresh as before, against the same address.
|
|
174
|
+
|
|
175
|
+
## Ways in
|
|
176
|
+
|
|
177
|
+
Each is on when its options are given (`authFromEnv` reads them from the environment; the names are in [Keys](#keys)).
|
|
178
|
+
|
|
179
|
+
### Sign in with Apple
|
|
180
|
+
|
|
181
|
+
```ts
|
|
182
|
+
apple: {
|
|
183
|
+
clientIds: ["com.example.app", "com.example.web"], // bundle IDs and Services IDs
|
|
184
|
+
revoke: { teamId, keyId, privateKey }, // the Sign in with Apple key (.p8), to revoke on deletion
|
|
185
|
+
}
|
|
186
|
+
```
|
|
187
|
+
|
|
188
|
+
The app gives Apple the SHA-256 hex of a random nonce and sends the server the raw one (the clients do it; on the web, `appleNonce()` from `direct-auth/client` makes the pair for Sign in with Apple JS), with the identity token, the name Apple gives it the first time only, and the authorization code. Only the hash is in Apple's token, and each nonce works once, so a token seen somewhere can't be sent again. The code is exchanged for Apple's refresh token, kept encrypted under a key derived from the `.p8` (a replaced `.p8` stays listed in `previousPrivateKeys` to read the tokens kept before). Deleting the account revokes it. An account with no token kept (one moved from elsewhere) answers `409 apple_code_needed` to the deletion: the client runs Sign in with Apple again and sends the new code, which is revoked straight away.
|
|
189
|
+
|
|
190
|
+
Set `https://<issuer>/apple/notifications` as the server-to-server notification endpoint of the App ID in Apple's developer site: a user who deletes their Apple account or stops using it with the app is signed out everywhere (`onAppleNotice` for anything more).
|
|
191
|
+
|
|
192
|
+
### Google
|
|
193
|
+
|
|
194
|
+
```ts
|
|
195
|
+
google: { clientIds: ["123-web.apps.googleusercontent.com", "123-ios.apps.googleusercontent.com"], domains: ["example.com"] }
|
|
196
|
+
```
|
|
197
|
+
|
|
198
|
+
The client IDs whose tokens are accepted: on Android the token's audience is the web client ID given to Credential Manager, on iOS the iOS client ID, on the web the web client ID. `domains` only lets in accounts of those Google Workspace domains. A nonce given to Google is sent as it was given, and works once.
|
|
199
|
+
|
|
200
|
+
### GitHub
|
|
201
|
+
|
|
202
|
+
```ts
|
|
203
|
+
github: { clientId: "Ov23li…", clientSecret: process.env.GITHUB_CLIENT_SECRET }
|
|
204
|
+
```
|
|
205
|
+
|
|
206
|
+
An OAuth app (GitHub › Settings › Developer settings › OAuth Apps, or the organization's), its callback URL being where the app takes the way back: a page of the web app, or the mobile app's link (an App Link on Android, a scheme of its own on iOS). The app sends the browser to GitHub with a state and a PKCE challenge (the clients do it), checks the state on the way back and sends the server `{ code, redirectUri, codeVerifier }`; the server trades the code with the secret, reads `/user` and `/user/emails`, and forgets GitHub's token. The account is GitHub's numeric id (a renamed login stays the same person). An address joins an existing account only when it is the primary one and GitHub verified it; otherwise the user starts without an address. Limited per IP (`githubPerIp`). Env: `GITHUB_CLIENT_ID`, `GITHUB_CLIENT_SECRET`.
|
|
207
|
+
|
|
208
|
+
### Email codes
|
|
209
|
+
|
|
210
|
+
```ts
|
|
211
|
+
import { resend } from "direct-auth/senders";
|
|
212
|
+
email: { send: resend({ apiKey, from: "Example <hello@example.com>" }) }
|
|
213
|
+
```
|
|
214
|
+
|
|
215
|
+
`POST /email/start` sends a code and answers the same whether or not the address has an account; `POST /email/verify` signs in, making the user the first time. The message is in English, Spanish, Portuguese or German by the `locale` sent (`renderCode`), with the app's name. Limits: a code every 30 seconds per address, 5 an hour per address, 20 an hour per IP, and 60 tries an hour per IP across addresses (`limits` changes them).
|
|
216
|
+
|
|
217
|
+
Mail needs the domain set up to be delivered: SPF, DKIM and DMARC records, which the provider gives you when it verifies the domain. `npx direct-auth dns example.com` checks them. MX records on the domain are only for receiving mail and aren't needed to send codes (some providers ask for one on a subdomain of their own, for bounces).
|
|
218
|
+
|
|
219
|
+
### SMS codes
|
|
220
|
+
|
|
221
|
+
```ts
|
|
222
|
+
import { twilio } from "direct-auth/senders";
|
|
223
|
+
sms: { send: twilio({ accountSid, authToken, from: "+15550001234" }), countries: ["+598", "+54"], domain: "example.com" }
|
|
224
|
+
```
|
|
225
|
+
|
|
226
|
+
Numbers are cleaned into E.164 (`+59899123456`). SMS goes only to the calling codes in `countries`, and there is no default: SMS pumping (bots asking for codes to premium numbers you pay for) is stopped first by not sending where the app has no users, then by the limits: per number, per IP, 50 an hour per calling code and 500 a day in all. `domain` adds the line browsers and Android read to fill the code in by themselves (`@example.com #123456`); iOS finds the code on its own.
|
|
227
|
+
|
|
228
|
+
An Android phone with a SIM can be the gateway, so the phone's plan pays for the messages: install the open-source SMS Gateway for Android app, and give `smsGateway({ url, username, password })` its local address (`http://192.168.1.20:8080`) or its cloud relay (`https://api.sms-gate.app/3rdparty/v1`).
|
|
229
|
+
|
|
230
|
+
### Passwords
|
|
231
|
+
|
|
232
|
+
```ts
|
|
233
|
+
passwords: { minLength: 8 } // PASSWORDS=1, PASSWORD_MIN_LENGTH; needs email codes
|
|
234
|
+
```
|
|
235
|
+
|
|
236
|
+
`POST /email/start`, then `POST /password/signup` with the code and the password: the code proves the address before the password works, so nobody can sign up with an address that isn't theirs (or take over one that has an account). `POST /password/signin` signs in; a wrong password and an unknown address answer alike (`invalid_credentials`), in about the same time. `POST /password/reset` takes a new code and a new password and signs every other device out. `POST /password` sets or changes it from inside the app (a sign-in in the last 10 minutes).
|
|
237
|
+
|
|
238
|
+
New hashes are PBKDF2-SHA256 with WebCrypto, 600,000 rounds (100,000 on Workers, Cloudflare's limit), a salt each, in a versioned format (`$pbkdf2-sha256$i=600000$salt$hash`). Supabase's bcrypt hashes (`$2a$`, `$2b$`) are checked with a bcrypt written in TypeScript and replaced with PBKDF2 at that sign-in, as is a hash with another round count. A password works from any address the account has proven.
|
|
239
|
+
|
|
240
|
+
How long a check takes says nothing about whether the address has an account: each PBKDF2 check costs the highest round count stored, and an address with no hash does the work of one that has, bcrypt or PBKDF2, picked for that address by a keyed hash in the proportion of the stored hashes (the same each time it is tried). A bcrypt check (cost 10) is about 80 ms of CPU and gives way to other requests as it goes; on Workers that is past the free plan's 10 ms a request, so a Worker checking moved hashes needs the paid plan.
|
|
241
|
+
|
|
242
|
+
Ten tries an hour per IP on one address, thirty per IP in all, a hundred a day per address from anywhere (so nobody else can easily lock the owner out; a code still gets them in), and ten new passwords an hour per user (`limits.passwordPerIpAccount`, `passwordPerIp`, `passwordPerAccount`, `passwordSetPerUser`).
|
|
243
|
+
|
|
244
|
+
### Passkeys
|
|
245
|
+
|
|
246
|
+
```ts
|
|
247
|
+
passkeys: {
|
|
248
|
+
rpId: "example.com",
|
|
249
|
+
rpName: "Example",
|
|
250
|
+
origins: ["https://example.com", "android:apk-key-hash:<base64url SHA-256 of the app's signing certificate>"],
|
|
251
|
+
}
|
|
252
|
+
```
|
|
253
|
+
|
|
254
|
+
A user adds a passkey within ten minutes of signing in (`freshMinutes`; later the server answers `reauth_needed`, so a token taken from a device can't leave a way back in), and signs in with it later. The iOS app needs the associated domain `webcredentials:example.com` (and the site's `apple-app-site-association` listing it); the Android app needs the site's `/.well-known/assetlinks.json` with `get_login_creds`. Attestation isn't asked for: a passkey is trusted as the key the user's device made.
|
|
255
|
+
|
|
256
|
+
### Any sender of your own
|
|
257
|
+
|
|
258
|
+
A sender is a function: `(message) => Promise<{ ok: true } | { ok: false, reason }>`, where `message` has `channel`, `to`, `code`, `subject`, `text`, `html` and `locale`.
|
|
259
|
+
|
|
260
|
+
```ts
|
|
261
|
+
email: { send: async (m) => (await myMailer.send({ to: m.to, subject: m.subject, html: m.html })) ? { ok: true } : { ok: false, reason: "mailer" } }
|
|
262
|
+
```
|
|
263
|
+
|
|
264
|
+
`devSender()` writes the code to the server's log instead, and only runs with `DIRECT_AUTH_DEV=1` outside production.
|
|
265
|
+
|
|
266
|
+
### Guests
|
|
267
|
+
|
|
268
|
+
```ts
|
|
269
|
+
guests: { days: 30 } // GUESTS=1, GUEST_DAYS: guests unused that long are deleted by prune()
|
|
270
|
+
```
|
|
271
|
+
|
|
272
|
+
`POST /guest` makes a user with nothing to sign in with yet, for an app that lets people in first: `isGuest` on the user, `is_anonymous: true` in the token (Supabase's name for it, so policies written for Supabase's anonymous users keep working). Limited per IP, and `humanCheck` is asked with `"guest"`. When the guest links a way in, the id stays and so does everything stored under it.
|
|
273
|
+
|
|
274
|
+
## Linking and changing
|
|
275
|
+
|
|
276
|
+
A signed-in user, guest or not, adds Apple (`POST /link/apple`), Google (`/link/google`), GitHub (`/link/github`), an address (`/link/email`, with a code sent to it) or a password (`POST /password`) to their own account, and keeps their id. If that Apple or Google account, or that address, already signs another account in, or the Apple or Google account's checked address is another account's, the answer is `409 identity_in_use` and nothing changes: the app decides (warn, or offer to switch to that account). `DELETE /identity/<id>` removes a way in, never the last (`409 last_way_in`); removing Apple revokes its token. `POST /email/change` moves the account to a new address, with a code sent there.
|
|
277
|
+
|
|
278
|
+
Each of these needs a sign-in in the last 10 minutes (`reauth_needed` otherwise), so a token taken from a device can't add a way back in or lock the owner out; a guest isn't asked. They answer the user as it is now and a new access token for the same session.
|
|
279
|
+
|
|
280
|
+
## Sessions and tokens
|
|
281
|
+
|
|
282
|
+
Every sign-in answers a session:
|
|
283
|
+
|
|
284
|
+
```json
|
|
285
|
+
{ "user": { "id": "…", "email": "ana@example.com", "phone": null, "name": "Ana", "picture": null, "createdAt": 1764700000000 },
|
|
286
|
+
"accessToken": "eyJ…", "refreshToken": "…", "expiresIn": 3600, "tokenType": "Bearer", "sessionId": "…", "created": false }
|
|
287
|
+
```
|
|
288
|
+
|
|
289
|
+
The access token is an ES256 JWT: `iss` the issuer, `sub` the user's id (a UUID), `aud` and `role` `authenticated`, `sid` the session, `email` and `phone` when known, and whatever `claims(user)` adds (never anything secret: anyone holding the token can read it). It lasts an hour (`accessTtl`). The clients refresh it a minute before it ends.
|
|
290
|
+
|
|
291
|
+
The refresh token is random, stored as a hash, and replaced at every `/refresh`. A replaced one used again more than a few seconds later (a copy used by someone else, or the device's own after the copy was used) ends the whole session. A session ends after 60 days unused (`idleDays`) or a year in all (`maxDays`).
|
|
292
|
+
|
|
293
|
+
An API of your own checks the access token with the issuer's JWKS, or beside the server with `server.auth.verifyAccessToken(token)`.
|
|
294
|
+
|
|
295
|
+
## Accounts
|
|
296
|
+
|
|
297
|
+
`createAuth` (which `createAuthServer` wraps) has the account's functions for your own code: `getUser`, `identities`, `sessions`, `signOut(sessionId)`, `signOutEverywhere(userId)`, `deleteUser(userId)`. `onDelete(user)` runs after a user is deleted, for your own rows (on Postgres, a foreign key with `on delete cascade` to `auth_users(id)` does it too).
|
|
298
|
+
|
|
299
|
+
The tables, under the prefix `auth_` (`tablePrefix`): `users`, `identities`, `sessions`, `refresh`, `codes`, `limits`, `passkeys`, `challenges` and `meta`. They are made on the first start; the schema only grows. A user's id is a `uuid` on Postgres, so your tables can point at `auth_users(id)`.
|
|
300
|
+
|
|
301
|
+
## The server
|
|
302
|
+
|
|
303
|
+
`createAuthServer(options)` answers the routes under `basePath` (`/auth`): the sign-ins, `/refresh`, `/user`, `/signout`, `DELETE /user`, the passkey routes, Apple's notifications and the issuer's two documents. [docs/API.md](docs/API.md) has each route, body, answer and error.
|
|
304
|
+
|
|
305
|
+
| Option | |
|
|
306
|
+
| --- | --- |
|
|
307
|
+
| `sql` | The database. |
|
|
308
|
+
| `issuer` | The server's public URL with the base path. It is in every token and in Supabase's setting: pick it once. |
|
|
309
|
+
| `keys` | `DIRECT_AUTH_SIGNING_KEYS`: the signing keys. |
|
|
310
|
+
| `app` | The name the codes' messages say. |
|
|
311
|
+
| `apple`, `google`, `github`, `email`, `sms`, `passkeys` | The ways in, above. |
|
|
312
|
+
| `origins` | Browser origins allowed to call it (CORS). |
|
|
313
|
+
| `ip(req)` | The caller's IP for the limits. By default only what a client can't set: `cf-connecting-ip` on Workers; on Supabase Edge Functions the last `x-forwarded-for` hop (the one Supabase's gateway adds: an assumption about its gateway, so for strict per-IP limits put the proxy Worker in front, with `trustProxy` off); under `Deno.serve(server.fetch)` and `Bun.serve({ fetch: server.fetch })` the connection's address, which they pass `fetch` (so pass `server.fetch` itself, or `(req, info) => server.fetch(req, info)`); under `serve()` the socket's. A server of your own behind Cloudflare's proxy gives `(req) => req.headers.get("cf-connecting-ip")`. Without an IP the per-IP limits don't apply. IPv6 counts by its /64, IPv4 written as IPv6 (`::ffff:203.0.113.7`) as itself, an address with a port (`203.0.113.7:51234`) without it. |
|
|
314
|
+
| `trustProxy` | A proxy in front sets `x-forwarded-for` (nginx or Caddy in front of Deno or Bun; Vercel; Netlify): its last hop is the caller's IP, then `x-real-ip`. Off by default, since without one in front a client writes those headers itself. `serve()` has its own `behindProxy`. |
|
|
315
|
+
| `humanCheck(req, body, channel)` | A check before a code is sent (a Turnstile token in the body, say); false answers `human_check_failed`. Worth it for SMS. |
|
|
316
|
+
| `passwords`, `guests` | Email and password; guests. Above. |
|
|
317
|
+
| `freshMinutes` | Minutes after signing in within which a way in, a password or the address may be changed (10). |
|
|
318
|
+
| `proxySecret` | The secret a proxy of your own sends (the Worker in front on Supabase), so its `x-direct-auth-ip` counts. |
|
|
319
|
+
| `claims(user)` | More claims for the access token. |
|
|
320
|
+
| `accessTtl`, `idleDays`, `maxDays` | Seconds an access token lasts (3600); days a session lives unused (60), and at most (365). |
|
|
321
|
+
| `limits` | The code limits. |
|
|
322
|
+
| `onDelete`, `onAppleNotice`, `observe` | Hooks: a deleted user, Apple's notices, failures worth a look (never with a token or code). |
|
|
323
|
+
|
|
324
|
+
Web apps on the same site as the server can keep the refresh token in an `HttpOnly` cookie instead of the page: the client's `cookie: true` sends `X-Direct-Auth-Cookie: 1`, and the server sets and reads `__Host-direct_auth_refresh`, which only that host can set.
|
|
325
|
+
|
|
326
|
+
The routes for a signed-in user take the access token only while its session is on: signing out, here or everywhere, ends its tokens at once. Bodies over 64 KB are refused.
|
|
327
|
+
|
|
328
|
+
## Connect an app
|
|
329
|
+
|
|
330
|
+
`npx direct-auth app` adds the client to the projects in an app's folder. By hand:
|
|
331
|
+
|
|
332
|
+
### iOS and macOS
|
|
333
|
+
|
|
334
|
+
Swift Package Manager: `https://github.com/guillecura/direct-auth`, product `DirectAuth` (iOS 16, macOS 13, tvOS 16, visionOS 1).
|
|
335
|
+
|
|
336
|
+
```swift
|
|
337
|
+
import DirectAuth
|
|
338
|
+
|
|
339
|
+
let auth = DirectAuth(url: URL(string: "https://api.example.com/auth")!)
|
|
340
|
+
|
|
341
|
+
let signIn = try await auth.signInWithApple(presentationAnchor: window) // or SignInWithAppleButton → signInWithApple(idToken:…)
|
|
342
|
+
try await auth.startEmail("ana@example.com")
|
|
343
|
+
let byCode = try await auth.verifyEmail("ana@example.com", code: code)
|
|
344
|
+
let passkey = try await auth.registerPasskey(anchor: window)
|
|
345
|
+
|
|
346
|
+
let guest = try await auth.signInAsGuest() // in first; later, the same id:
|
|
347
|
+
try await auth.linkEmail("ana@example.com", code: code) // or linkApple, linkGoogle, setPassword
|
|
348
|
+
let byPassword = try await auth.signInWithPassword(email: "ana@example.com", password: password)
|
|
349
|
+
|
|
350
|
+
// supabase-swift, with direct-auth as the project's Third-Party Auth issuer:
|
|
351
|
+
let supabase = SupabaseClient(supabaseURL: url, supabaseKey: anonKey,
|
|
352
|
+
options: .init(auth: .init(accessToken: { try await auth.accessToken() })))
|
|
353
|
+
|
|
354
|
+
try await auth.deleteAccount(anchor: window) // runs Sign in with Apple again when the server asks for a code
|
|
355
|
+
```
|
|
356
|
+
|
|
357
|
+
The session is kept in the Keychain (this device only), `auth.changes()` streams the user, and `accessToken()` refreshes a minute early, once for every caller at the same time. Sign in with Apple needs the capability; passkeys the associated domain `webcredentials:<rpId>`. Google: get the ID token with Google's own SDK and call `signInWithGoogle(idToken:nonce:)`. GitHub: `signInWithGitHub(clientID:redirectURI:anchor:)` runs it in an `ASWebAuthenticationSession`, the callback URL in a scheme of the app (`myapp://github`).
|
|
358
|
+
|
|
359
|
+
### Android
|
|
360
|
+
|
|
361
|
+
JitPack: `maven("https://jitpack.io")` in the repositories, and `implementation("com.github.guillecura:direct-auth:0.1.0")`.
|
|
362
|
+
|
|
363
|
+
```kotlin
|
|
364
|
+
val auth = DirectAuth(context, "https://api.example.com/auth")
|
|
365
|
+
|
|
366
|
+
auth.signInWithGoogle(activity, webClientId = "123-web.apps.googleusercontent.com")
|
|
367
|
+
auth.startEmail("ana@example.com"); auth.verifyEmail("ana@example.com", code)
|
|
368
|
+
auth.registerPasskey(activity); auth.signInWithPasskey(activity)
|
|
369
|
+
auth.signInAsGuest(); auth.linkEmail("ana@example.com", code) // linkGoogle, linkApple, setPassword, unlink
|
|
370
|
+
auth.signInWithPassword("ana@example.com", password)
|
|
371
|
+
|
|
372
|
+
// supabase-kt, with direct-auth as the project's Third-Party Auth issuer:
|
|
373
|
+
val supabase = createSupabaseClient(url, anonKey) { accessToken = { auth.accessToken() } }
|
|
374
|
+
```
|
|
375
|
+
|
|
376
|
+
Google and passkeys go through Credential Manager. The session is encrypted with a key in the Android Keystore; `auth.user` is a `StateFlow`. Sign in with Apple has no Android API: an Android app that offers it opens Apple's web flow and sends the token to `/apple`. GitHub: `startGitHub(activity, clientId, redirectUri)` opens a Custom Tab; the activity the callback App Link opens calls `finishGitHub(intent.data)` (or `linkGitHub`).
|
|
377
|
+
|
|
378
|
+
### The web
|
|
379
|
+
|
|
380
|
+
```ts
|
|
381
|
+
import { createAuthClient } from "direct-auth/client";
|
|
382
|
+
|
|
383
|
+
const auth = createAuthClient({ url: "https://api.example.com/auth", cookie: true });
|
|
384
|
+
await auth.startEmail("ana@example.com");
|
|
385
|
+
await auth.verifyEmail("ana@example.com", code);
|
|
386
|
+
await auth.signInWithPasskey();
|
|
387
|
+
await auth.signInAsGuest(); // then linkEmail, linkApple, linkGoogle, setPassword
|
|
388
|
+
await auth.signInWithPassword("ana@example.com", password); // signUpWithPassword, resetPassword with a code
|
|
389
|
+
|
|
390
|
+
const supabase = createClient(url, anonKey, { accessToken: () => auth.accessToken() });
|
|
391
|
+
```
|
|
392
|
+
|
|
393
|
+
With `cookie: true` (the server on the same site), the refresh token lives in an `HttpOnly` cookie and the access token only in memory. Without it, the session is kept in `localStorage`. Sign in with Apple JS and Google Identity Services give the ID token; hand it to `signInWithApple` or `signInWithGoogle`. GitHub: `location.assign(await auth.startGitHub({ clientId, redirectUri }))`, then on the callback page `await auth.finishGitHub()` (or `linkGitHub()`); the state and PKCE verifier wait in the tab's `sessionStorage`.
|
|
394
|
+
|
|
395
|
+
## Moving from Supabase Auth
|
|
396
|
+
|
|
397
|
+
A hard stop, not a period of both, in this order: Supabase Auth's sign-ins go off, the users move, then the app's new version signs in with direct-auth and older versions are made to update. Everyone signs in once more, as the same user (same id, same data). No Supabase session comes over, except a guest's, claimed once.
|
|
398
|
+
|
|
399
|
+
1. `npx direct-auth init`, then deploy the function ([On Supabase](#on-supabase)). With passwords, guests or passkeys in the project, turn those on too (and the same `PASSKEY_RP_ID` Supabase's passkeys used). From `migrate`'s dry run (step 3) until the move, the server makes nobody: a sign-in answers `503 migration_pending`, so an account made early can't take a moved user's address. The dry run turns this on with a note in `auth_meta` (`supabase_pending`); any finished move takes it out.
|
|
400
|
+
2. Build the app's new version with the direct-auth client, but don't release it yet. Turn Supabase Auth's sign-ins and sign-ups off (Authentication › Sign In / Providers): a user made there after the move is one direct-auth never gets.
|
|
401
|
+
3. `npx direct-auth migrate`, with the database URL (asked, hidden as you type, or `DATABASE_URL`). Nothing is sent until the server proves it is the database: either its certificate is checked (download Supabase's CA from Database Settings › SSL Configuration and add `?sslrootcert=prod-ca-2021.crt` to the URL: that is `verify-full`), or the sign-in is SCRAM bound to the TLS channel (SCRAM-SHA-256-PLUS), which the direct connection (`db.<ref>.supabase.co`) offers and the pooler doesn't. Without either it stops and says which to add.
|
|
402
|
+
1. **A dry run**: the users by provider, guests, passwords, passkeys, the banned and deleted left out; an address, number, Apple, Google or GitHub account two accounts share (the older keeps it); SSO (SAML) users, whose address only their company's identity provider vouched for, so it moves as unconfirmed; email sign-ups confirmed within two seconds (Confirm email off): nobody proved those addresses; the foreign keys on `auth.users` it will point at `auth_users`; each trigger, function, policy and view that reads `auth.users` or the metadata, by name, with what to do about it. Counts and names only, never an address. Users with a second factor (`auth.mfa_factors`) stop the move: direct-auth doesn't check one, so they would sign in with the first alone. `--without-mfa` goes ahead knowing it.
|
|
403
|
+
2. **The move**: the way back is written to a file first (`--rollback`), then, once you type `move`, one transaction copies the users with the same ids (the anonymous ones as guests), their Apple, Google and GitHub identities, their confirmed addresses and numbers, the password hashes (bcrypt, checked as they are and made PBKDF2 at each one's first sign-in) and the passkeys (their COSE keys read on first use), and points the foreign keys at `auth_users(id)` with all they said (`on delete`, `on update`, deferrable). A key whose table has rows of users left out is added `NOT VALID`. It runs once: a second run is refused. The way back puts the keys on `auth.users` again and takes the moved users out; then the move can run again.
|
|
404
|
+
3. **A check**: every user here, every way in, guests and their claims, passwords and passkeys, no address split between two accounts (one made here before the move: the check fails, and the way back is the answer), a few users at random as themselves (ids masked), no foreign key left on `auth.users`.
|
|
405
|
+
4. **What's next**: the trust setting, the env, each app's swap with the snippets, and the steps below.
|
|
406
|
+
|
|
407
|
+
`npx direct-auth supabase-sql > move.sql` is the same move as SQL, to read and run yourself.
|
|
408
|
+
4. `npx direct-auth supabase-trust` (or the curl above). Policies with `auth.uid()` keep working, with the same ids.
|
|
409
|
+
5. The app's own trigger on `auth.users` (a `handle_new_user`): nobody is made there anymore, so make it a trigger after insert on `auth_users` (`new.id`, `new.email`, `new.phone`, `new.name`, `new.picture`) and drop the one on `auth.users`.
|
|
410
|
+
6. Release the new version and make it the minimum version, so older ones ask to update.
|
|
411
|
+
7. Once the update is out, revoke the JWT signing key Supabase Auth signed with (Project Settings › JWT Keys), so its access tokens still out stop working in the Data API, Storage and Realtime at once rather than within the hour. A project still on the legacy JWT secret changes its `anon` and `service_role` keys when that secret changes: move the apps to the publishable and secret keys first.
|
|
412
|
+
|
|
413
|
+
Apple and Google users sign in as themselves; email and phone users get a code as before; password users sign in with their password (a moved bcrypt hash is a password like any: `hasPassword`, and it can be removed; GoTrue gives users made without a password a random one, so it only counts as a way in once it has signed someone in). A guest has nothing to sign in with, so the move keeps the hash of each guest's live Supabase refresh token for 180 days: at the new version's first start, before anything else, an app holding Supabase's anonymous session calls `claimGuest(supabaseRefreshToken)` once (web, Swift, Kotlin), then forgets the Supabase session. It answers a session for the same user, with the same data. Claims work until the claim window ends (180 days), even if an older version of the app refreshed its Supabase session after the move (Supabase Auth still trades refresh tokens with its sign-ins off: a token it hasn't revoked counts too). Once claimed, or once the guest has linked a way in, the token gets nobody in. A guest whose app holds no session starts over as a new guest.
|
|
414
|
+
|
|
415
|
+
A password whose address was confirmed the moment it signed up (Confirm email off) was set by whoever typed that address, so it stays behind: the address's owner gets in with an email code. `--keep-unproven-passwords` moves those too.
|
|
416
|
+
|
|
417
|
+
Accounts moved this way have no Apple token kept, so deleting one asks the app for a new Apple code (the clients do it).
|
|
418
|
+
|
|
419
|
+
A manual for each source, with the order, what moves, what users notice, the way back and a checklist: [Supabase](docs/migrate/supabase.md), [Firebase](docs/migrate/firebase.md), [Auth.js](docs/migrate/authjs.md), [Better Auth](docs/migrate/better-auth.md), [Clerk](docs/migrate/clerk.md), [Auth0](docs/migrate/auth0.md).
|
|
420
|
+
|
|
421
|
+
## Moving from Firebase, Auth.js, Better Auth, Clerk or Auth0
|
|
422
|
+
|
|
423
|
+
`npx direct-auth migrate` with no flags asks where the users are, then only what that source needs: the export file (checked as you give it), Firebase's password hash parameters (the key hidden), Auth0's hashes file if you have one, and the database URL. Then the same four steps: a dry run, the way back written first, the move after you type `move`, the checks, and the next steps. Flags do the same for a script: `--from firebase --file users.json --hash-config hash.txt`, `--from clerk --file users.csv`, `--from auth0 --file users.json --hashes hashes.json`, `--from authjs`, `--from better-auth`.
|
|
424
|
+
|
|
425
|
+
The same hard stop as from Supabase: the old service's sign-ups off, the move, then the app's new version as the minimum, and everyone signs in once more. Every source is read into one shape and written by one transaction, once:
|
|
426
|
+
|
|
427
|
+
| From | Read from | Passwords | Ids |
|
|
428
|
+
| --- | --- | --- | --- |
|
|
429
|
+
| Firebase Auth | `firebase auth:export` JSON | its scrypt, with the project's hash parameters | new; the uid in `source_id` |
|
|
430
|
+
| Auth.js | its tables, same database | none kept (email codes) | new unless UUIDs; the old in `source_id` |
|
|
431
|
+
| Better Auth | its tables, same database | its scrypt | kept when UUIDs; else new, the old in `source_id` |
|
|
432
|
+
| Clerk | the dashboard's CSV | bcrypt digests | new; the Clerk id in `source_id` |
|
|
433
|
+
| Auth0 | the bulk export (NDJSON) | bcrypt, from the hashes file Auth0's support gives | new; the Auth0 id in `source_id` |
|
|
434
|
+
|
|
435
|
+
Checked addresses and numbers, Apple, Google and GitHub accounts, and anonymous users (as guests, with no claim) move; a password moves only with an address the service verified (`--keep-unproven-passwords` moves unverified ones as checked). Users with a second factor there stop the move, as with Supabase: direct-auth doesn't check one (`--without-mfa` goes ahead knowing it). Moved scrypt and bcrypt hashes are checked as they are and made PBKDF2 at the first sign-in. A scrypt check holds 16 MB while it runs with Firebase's usual parameters (32 MB with Better Auth's); on Workers, whose isolates have 128 MB, at most two run at once in one isolate and the others wait their turn. That lasts only until each moved user has signed in once. The app's own tables keep the old ids: `select id, source_id from auth_users` maps them. The way back takes the moved users out (or drops the tables the move made).
|
|
436
|
+
|
|
437
|
+
## Keys
|
|
438
|
+
|
|
439
|
+
`npx direct-auth init` asks for all of these and writes them to `.env`; they belong on the server only.
|
|
440
|
+
|
|
441
|
+
| Variable | |
|
|
442
|
+
| --- | --- |
|
|
443
|
+
| `DIRECT_AUTH_ISSUER` | The address of your sign-in, with its base path (`https://auth.example.com/auth`). |
|
|
444
|
+
| `DIRECT_AUTH_SIGNING_KEYS` | The signing keys: `npx direct-auth keys` makes one; `keys --add .env` puts a new one first, to rotate (drop the old one an hour later). |
|
|
445
|
+
| `DIRECT_AUTH_APP_NAME`, `DIRECT_AUTH_ORIGINS` | The name the codes say; the browser origins allowed. |
|
|
446
|
+
| `DIRECT_AUTH_PROXY_SECRET`, `DIRECT_AUTH_TABLE_PREFIX`, `DIRECT_AUTH_BASE_PATH` | The proxy's shared secret; the tables' prefix (`auth_`); the routes' path when it isn't the issuer's (on Supabase, `/functions/v1` is left out on its own). |
|
|
447
|
+
| `PASSWORDS`, `PASSWORD_MIN_LENGTH`, `PASSWORD_ITERATIONS` | `1` for email and password (needs `MAIL_SENDER`); the shortest allowed (8); PBKDF2's rounds. |
|
|
448
|
+
| `GUESTS`, `GUEST_DAYS` | `1` for guests; days an unused guest is kept. |
|
|
449
|
+
| `APPLE_CLIENT_IDS` | Bundle IDs and Services IDs, comma separated. |
|
|
450
|
+
| `APPLE_TEAM_ID`, `APPLE_KEY_ID`, `APPLE_PRIVATE_KEY` | A key with Sign in with Apple on (**Certificates, Identifiers & Profiles › Keys**), and its `.p8`'s text. |
|
|
451
|
+
| `GOOGLE_CLIENT_IDS`, `GOOGLE_DOMAINS` | OAuth client IDs; Workspace domains allowed. |
|
|
452
|
+
| `PASSKEY_RP_ID`, `PASSKEY_RP_NAME`, `PASSKEY_ORIGINS` | The passkeys' domain, name and origins. |
|
|
453
|
+
| `MAIL_SENDER`, `MAIL_FROM` | `resend`, `postmark`, `mailgun`, `sendgrid`, `ses`, `smtp` or `dev`; the sender's address. Then `RESEND_API_KEY`, `POSTMARK_SERVER_TOKEN`, `MAILGUN_API_KEY` and `MAILGUN_DOMAIN`, `SENDGRID_API_KEY`, `AWS_REGION` and its keys, or `SMTP_HOST`, `SMTP_PORT`, `SMTP_USER`, `SMTP_PASS`. |
|
|
454
|
+
| `SMS_SENDER`, `SMS_COUNTRIES`, `SMS_DOMAIN` | `twilio`, `vonage`, `sns`, `sms-gateway` or `dev`; the calling codes allowed; the autofill domain. Then `TWILIO_*`, `VONAGE_*`, `AWS_*` or `SMS_GATEWAY_URL`, `SMS_GATEWAY_USERNAME`, `SMS_GATEWAY_PASSWORD`. |
|
|
455
|
+
|
|
456
|
+
## With an AI agent
|
|
457
|
+
|
|
458
|
+
The package ships a [skill for coding agents](skills/direct-auth/SKILL.md): where it runs, the wizards, and the rules that keep keys out of code and SMS from going everywhere. Put it in the project and Claude Code reads it when the task calls for it:
|
|
459
|
+
|
|
460
|
+
```sh
|
|
461
|
+
npx direct-auth skill # into .claude/skills/direct-auth (a copy there that differs is replaced only after a yes)
|
|
462
|
+
npx direct-auth skill --dir .agents/skills # another agent's folder
|
|
463
|
+
```
|
|
464
|
+
|
|
465
|
+
`init` and `app` offer it as their last step. With the [skills CLI](https://github.com/vercel-labs/skills), from this repository: `npx skills add guillecura/direct-auth`. Other agents can read the same file, or this README at `node_modules/direct-auth/README.md`.
|
|
466
|
+
|
|
467
|
+
## Develop
|
|
468
|
+
|
|
469
|
+
```sh
|
|
470
|
+
npm install
|
|
471
|
+
npm test # the providers, codes, senders, sessions, passkeys and the server, on SQLite and Postgres (PGlite)
|
|
472
|
+
npm run typecheck
|
|
473
|
+
npm run build
|
|
474
|
+
deno check --no-lock src/index.ts src/server.ts src/client.ts
|
|
475
|
+
swift test # the Swift client
|
|
476
|
+
cd clients/android && ./gradlew testDebugUnitTest # the Android client (JDK 17 and the Android SDK)
|
|
477
|
+
```
|
|
478
|
+
|
|
479
|
+
A release is a version in `package.json` (and the Kotlin line above) and a `vX.Y.Z` tag pushed: [the release workflow](.github/workflows/release.yml) publishes to npm with provenance, and Swift Package Manager and JitPack read the tag.
|
|
480
|
+
|
|
481
|
+
## Credits
|
|
482
|
+
|
|
483
|
+
Made by [Guille Cura](https://github.com/guillecura) at [Whitebear](https://whitebear.io).
|
|
484
|
+
|
|
485
|
+
## License
|
|
486
|
+
|
|
487
|
+
MIT
|