@appgrowstack/app-auth 0.0.0-stage → 0.7.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/CHANGELOG.md +142 -0
- package/LICENSE +21 -0
- package/README.md +332 -2
- package/dist/apple-revoke.d.ts +23 -0
- package/dist/apple-revoke.js +100 -0
- package/dist/apple-web.d.ts +33 -0
- package/dist/apple-web.js +92 -0
- package/dist/authenticate.d.ts +29 -0
- package/dist/authenticate.js +64 -0
- package/dist/config.d.ts +94 -0
- package/dist/config.js +5 -0
- package/dist/contract.d.ts +98 -0
- package/dist/contract.js +0 -0
- package/dist/d1.d.ts +17 -0
- package/dist/d1.js +0 -0
- package/dist/delete-user.d.ts +14 -0
- package/dist/delete-user.js +17 -0
- package/dist/device-routes.d.ts +9 -0
- package/dist/device-routes.js +144 -0
- package/dist/device.d.ts +31 -0
- package/dist/device.js +88 -0
- package/dist/firebase-refresh.d.ts +14 -0
- package/dist/firebase-refresh.js +33 -0
- package/dist/http.d.ts +25 -0
- package/dist/http.js +32 -0
- package/dist/index.d.ts +11 -0
- package/dist/index.js +10 -0
- package/dist/providers.d.ts +24 -0
- package/dist/providers.js +74 -0
- package/dist/routes.d.ts +6 -0
- package/dist/routes.js +373 -0
- package/dist/store.d.ts +35 -0
- package/dist/store.js +135 -0
- package/dist/tokens.d.ts +34 -0
- package/dist/tokens.js +105 -0
- package/migrations/0001_app_auth.sql +25 -0
- package/migrations/0002_app_auth_apple_web.sql +7 -0
- package/migrations/0003_app_auth_device.sql +12 -0
- package/package.json +47 -4
- package/scripts/import-firebase-users.ts +117 -0
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
import { SignJWT, importPKCS8 } from "jose";
|
|
2
|
+
export const APPLE_TOKEN_URL = "https://appleid.apple.com/auth/token";
|
|
3
|
+
export const APPLE_REVOKE_URL = "https://appleid.apple.com/auth/revoke";
|
|
4
|
+
export function missingRevokeSettings(config) {
|
|
5
|
+
if (!config)
|
|
6
|
+
return ["apple.revoke"];
|
|
7
|
+
const missing = [];
|
|
8
|
+
if (!config.teamId)
|
|
9
|
+
missing.push("teamId");
|
|
10
|
+
if (!config.keyId)
|
|
11
|
+
missing.push("keyId");
|
|
12
|
+
if (!config.clientId)
|
|
13
|
+
missing.push("clientId");
|
|
14
|
+
if (!config.privateKey)
|
|
15
|
+
missing.push("APPLE_SIGN_IN_PRIVATE_KEY");
|
|
16
|
+
return missing;
|
|
17
|
+
}
|
|
18
|
+
export async function revokeAppleAuthorization(config, authorizationCode, options = {}) {
|
|
19
|
+
const missing = missingRevokeSettings(config);
|
|
20
|
+
if (!config || missing.length > 0)
|
|
21
|
+
return { status: "skipped_not_configured", missing };
|
|
22
|
+
const send = options.fetch ?? fetch;
|
|
23
|
+
const now = options.now ?? Date.now();
|
|
24
|
+
let clientSecret;
|
|
25
|
+
try {
|
|
26
|
+
clientSecret = await appleClientSecret(config, now);
|
|
27
|
+
}
|
|
28
|
+
catch (error) {
|
|
29
|
+
return { status: "failed", step: "client_secret", message: error instanceof Error ? error.message : String(error) };
|
|
30
|
+
}
|
|
31
|
+
const tokenResponse = await postForm(send, APPLE_TOKEN_URL, {
|
|
32
|
+
client_id: config.clientId,
|
|
33
|
+
client_secret: clientSecret,
|
|
34
|
+
code: authorizationCode,
|
|
35
|
+
grant_type: "authorization_code",
|
|
36
|
+
});
|
|
37
|
+
if (!tokenResponse.ok)
|
|
38
|
+
return { status: "failed", step: "token", ...tokenResponse.failure };
|
|
39
|
+
const tokens = tokenResponse.body;
|
|
40
|
+
const [token, hint] = typeof tokens.refresh_token === "string"
|
|
41
|
+
? [tokens.refresh_token, "refresh_token"]
|
|
42
|
+
: typeof tokens.access_token === "string"
|
|
43
|
+
? [tokens.access_token, "access_token"]
|
|
44
|
+
: [null, null];
|
|
45
|
+
if (!token || !hint)
|
|
46
|
+
return { status: "failed", step: "token", message: "Apple returned no refresh_token or access_token" };
|
|
47
|
+
const revokeResponse = await postForm(send, APPLE_REVOKE_URL, {
|
|
48
|
+
client_id: config.clientId,
|
|
49
|
+
client_secret: clientSecret,
|
|
50
|
+
token,
|
|
51
|
+
token_type_hint: hint,
|
|
52
|
+
});
|
|
53
|
+
if (!revokeResponse.ok)
|
|
54
|
+
return { status: "failed", step: "revoke", ...revokeResponse.failure };
|
|
55
|
+
return { status: "revoked" };
|
|
56
|
+
}
|
|
57
|
+
export async function appleClientSecret(config, now) {
|
|
58
|
+
const pem = (config.privateKey ?? "").replace(/\\n/g, "\n");
|
|
59
|
+
const key = await importPKCS8(pem, "ES256");
|
|
60
|
+
const iat = Math.floor(now / 1000);
|
|
61
|
+
return new SignJWT({})
|
|
62
|
+
.setProtectedHeader({ alg: "ES256", kid: config.keyId })
|
|
63
|
+
.setIssuer(config.teamId)
|
|
64
|
+
.setSubject(config.clientId)
|
|
65
|
+
.setAudience("https://appleid.apple.com")
|
|
66
|
+
.setIssuedAt(iat)
|
|
67
|
+
.setExpirationTime(iat + 300)
|
|
68
|
+
.sign(key);
|
|
69
|
+
}
|
|
70
|
+
async function postForm(send, url, form) {
|
|
71
|
+
let response;
|
|
72
|
+
try {
|
|
73
|
+
response = await send(url, {
|
|
74
|
+
method: "POST",
|
|
75
|
+
headers: { "content-type": "application/x-www-form-urlencoded" },
|
|
76
|
+
body: new URLSearchParams(form),
|
|
77
|
+
});
|
|
78
|
+
}
|
|
79
|
+
catch (error) {
|
|
80
|
+
return { ok: false, failure: { message: error instanceof Error ? error.message : String(error) } };
|
|
81
|
+
}
|
|
82
|
+
const text = await response.text();
|
|
83
|
+
if (!response.ok)
|
|
84
|
+
return { ok: false, failure: { httpStatus: response.status, message: appleErrorCode(text) } };
|
|
85
|
+
try {
|
|
86
|
+
return { ok: true, body: text ? JSON.parse(text) : {} };
|
|
87
|
+
}
|
|
88
|
+
catch {
|
|
89
|
+
return { ok: true, body: {} };
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
function appleErrorCode(text) {
|
|
93
|
+
try {
|
|
94
|
+
const error = JSON.parse(text).error;
|
|
95
|
+
return typeof error === "string" ? error : "unknown_error";
|
|
96
|
+
}
|
|
97
|
+
catch {
|
|
98
|
+
return "unknown_error";
|
|
99
|
+
}
|
|
100
|
+
}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import type { AppleWebConfig } from "./config.js";
|
|
2
|
+
import type { AppleWebPlatform, AppleWebReturnError } from "./contract.js";
|
|
3
|
+
import type { D1Like } from "./d1.js";
|
|
4
|
+
import { type TokenKeyring } from "./tokens.js";
|
|
5
|
+
export declare const APPLE_AUTHORIZE_URL = "https://appleid.apple.com/auth/authorize";
|
|
6
|
+
export declare const APPLE_WEB_STATE_TTL_MS: number;
|
|
7
|
+
export declare const APPLE_WEB_CODE_TTL_MS: number;
|
|
8
|
+
export interface AppleWebState {
|
|
9
|
+
installId: string;
|
|
10
|
+
platform: AppleWebPlatform;
|
|
11
|
+
nonce: string;
|
|
12
|
+
codeChallenge: string;
|
|
13
|
+
}
|
|
14
|
+
export declare function isCodeChallenge(value: unknown): value is string;
|
|
15
|
+
export declare function codeChallengeFor(verifier: unknown): Promise<string | null>;
|
|
16
|
+
export declare function signAppleWebState(keyring: TokenKeyring, app: string, state: AppleWebState, now: number): Promise<string>;
|
|
17
|
+
export declare function verifyAppleWebState(keyring: TokenKeyring, app: string, token: string, now: number): Promise<AppleWebState | null>;
|
|
18
|
+
export declare function newNonce(): string;
|
|
19
|
+
export declare function appleAuthorizeUrl(web: AppleWebConfig, state: string, nonce: string): string;
|
|
20
|
+
export declare function appleWebReturnUrl(web: AppleWebConfig, query: {
|
|
21
|
+
code: string;
|
|
22
|
+
} | {
|
|
23
|
+
error: AppleWebReturnError;
|
|
24
|
+
}): string;
|
|
25
|
+
export declare function appleWebErrorFrom(value: unknown): AppleWebReturnError;
|
|
26
|
+
export declare function createAppleWebCode(db: D1Like, subject: string, installId: string, codeChallenge: string, now: number): Promise<string>;
|
|
27
|
+
export interface AppleWebCode {
|
|
28
|
+
codeHash: string;
|
|
29
|
+
subject: string;
|
|
30
|
+
installId: string;
|
|
31
|
+
}
|
|
32
|
+
export declare function findAppleWebCode(db: D1Like, code: string, codeChallenge: string, now: number): Promise<AppleWebCode | null>;
|
|
33
|
+
export declare function consumeAppleWebCode(db: D1Like, codeHash: string): Promise<boolean>;
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
import { SignJWT, jwtVerify } from "jose";
|
|
2
|
+
import { base64url, hashSecret, newRefreshSecret } from "./tokens.js";
|
|
3
|
+
export const APPLE_AUTHORIZE_URL = "https://appleid.apple.com/auth/authorize";
|
|
4
|
+
export const APPLE_WEB_STATE_TTL_MS = 5 * 60 * 1000;
|
|
5
|
+
export const APPLE_WEB_CODE_TTL_MS = 60 * 1000;
|
|
6
|
+
const CODE_CHALLENGE = /^[A-Za-z0-9_-]{43}$/;
|
|
7
|
+
const CODE_VERIFIER = /^[A-Za-z0-9._~-]{43,128}$/;
|
|
8
|
+
export function isCodeChallenge(value) {
|
|
9
|
+
return typeof value === "string" && CODE_CHALLENGE.test(value);
|
|
10
|
+
}
|
|
11
|
+
export async function codeChallengeFor(verifier) {
|
|
12
|
+
if (typeof verifier !== "string" || !CODE_VERIFIER.test(verifier))
|
|
13
|
+
return null;
|
|
14
|
+
return base64url(new Uint8Array(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(verifier))));
|
|
15
|
+
}
|
|
16
|
+
const stateAudience = (app) => `${app}:apple_web_state`;
|
|
17
|
+
export async function signAppleWebState(keyring, app, state, now) {
|
|
18
|
+
const iat = Math.floor(now / 1000);
|
|
19
|
+
return new SignJWT({ iid: state.installId, plt: state.platform, nonce: state.nonce, cch: state.codeChallenge })
|
|
20
|
+
.setProtectedHeader({ alg: "HS256", typ: "JWT", kid: keyring.signing.kid })
|
|
21
|
+
.setIssuer(app)
|
|
22
|
+
.setAudience(stateAudience(app))
|
|
23
|
+
.setIssuedAt(iat)
|
|
24
|
+
.setExpirationTime(Math.floor((now + APPLE_WEB_STATE_TTL_MS) / 1000))
|
|
25
|
+
.sign(keyring.signing.key);
|
|
26
|
+
}
|
|
27
|
+
export async function verifyAppleWebState(keyring, app, token, now) {
|
|
28
|
+
try {
|
|
29
|
+
const { payload } = await jwtVerify(token, (header) => {
|
|
30
|
+
const key = header.kid ? keyring.byKid.get(header.kid) : undefined;
|
|
31
|
+
if (!key)
|
|
32
|
+
throw new Error("unknown kid");
|
|
33
|
+
return key;
|
|
34
|
+
}, { issuer: app, audience: stateAudience(app), algorithms: ["HS256"], requiredClaims: ["exp"], currentDate: new Date(now) });
|
|
35
|
+
const { iid, plt, nonce, cch } = payload;
|
|
36
|
+
if (typeof iid !== "string" || plt !== "android" || typeof nonce !== "string" || !isCodeChallenge(cch))
|
|
37
|
+
return null;
|
|
38
|
+
return { installId: iid, platform: plt, nonce, codeChallenge: cch };
|
|
39
|
+
}
|
|
40
|
+
catch {
|
|
41
|
+
return null;
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
export function newNonce() {
|
|
45
|
+
const bytes = new Uint8Array(16);
|
|
46
|
+
crypto.getRandomValues(bytes);
|
|
47
|
+
return base64url(bytes);
|
|
48
|
+
}
|
|
49
|
+
export function appleAuthorizeUrl(web, state, nonce) {
|
|
50
|
+
const url = new URL(APPLE_AUTHORIZE_URL);
|
|
51
|
+
url.searchParams.set("client_id", web.servicesId);
|
|
52
|
+
url.searchParams.set("redirect_uri", web.redirectUri);
|
|
53
|
+
url.searchParams.set("response_type", "code id_token");
|
|
54
|
+
url.searchParams.set("response_mode", "form_post");
|
|
55
|
+
url.searchParams.set("state", state);
|
|
56
|
+
url.searchParams.set("nonce", nonce);
|
|
57
|
+
return url.toString();
|
|
58
|
+
}
|
|
59
|
+
export function appleWebReturnUrl(web, query) {
|
|
60
|
+
const url = new URL(web.returnUrl);
|
|
61
|
+
if ("code" in query)
|
|
62
|
+
url.searchParams.set("code", query.code);
|
|
63
|
+
else
|
|
64
|
+
url.searchParams.set("error", query.error);
|
|
65
|
+
return url.toString();
|
|
66
|
+
}
|
|
67
|
+
export function appleWebErrorFrom(value) {
|
|
68
|
+
return value === "user_cancelled_authorize" ? "user_cancelled_authorize" : "apple_error";
|
|
69
|
+
}
|
|
70
|
+
const codeHashOf = (code, codeChallenge) => hashSecret(`${code}.${codeChallenge}`);
|
|
71
|
+
export async function createAppleWebCode(db, subject, installId, codeChallenge, now) {
|
|
72
|
+
const code = newRefreshSecret();
|
|
73
|
+
await db.batch([
|
|
74
|
+
db.prepare("DELETE FROM auth_apple_web_codes WHERE expires_at <= ?").bind(now),
|
|
75
|
+
db
|
|
76
|
+
.prepare("INSERT INTO auth_apple_web_codes (code_hash, subject, install_id, created_at, expires_at) VALUES (?, ?, ?, ?, ?)")
|
|
77
|
+
.bind(await codeHashOf(code, codeChallenge), subject, installId, now, now + APPLE_WEB_CODE_TTL_MS),
|
|
78
|
+
]);
|
|
79
|
+
return code;
|
|
80
|
+
}
|
|
81
|
+
export async function findAppleWebCode(db, code, codeChallenge, now) {
|
|
82
|
+
const codeHash = await codeHashOf(code, codeChallenge);
|
|
83
|
+
const row = await db
|
|
84
|
+
.prepare("SELECT subject, install_id AS installId FROM auth_apple_web_codes WHERE code_hash = ? AND expires_at > ?")
|
|
85
|
+
.bind(codeHash, now)
|
|
86
|
+
.first();
|
|
87
|
+
return row ? { codeHash, ...row } : null;
|
|
88
|
+
}
|
|
89
|
+
export async function consumeAppleWebCode(db, codeHash) {
|
|
90
|
+
const result = await db.prepare("DELETE FROM auth_apple_web_codes WHERE code_hash = ?").bind(codeHash).run();
|
|
91
|
+
return result.meta.changes === 1;
|
|
92
|
+
}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import type { MiddlewareHandler } from "hono";
|
|
2
|
+
import { type AppAuthConfig } from "./config.js";
|
|
3
|
+
import type { AuthKind } from "./contract.js";
|
|
4
|
+
export interface AuthVariables {
|
|
5
|
+
userId: string;
|
|
6
|
+
auth_kind: AuthKind;
|
|
7
|
+
}
|
|
8
|
+
export type AuthEnv<E> = {
|
|
9
|
+
Bindings: E;
|
|
10
|
+
Variables: AuthVariables;
|
|
11
|
+
};
|
|
12
|
+
export declare function authenticate<E extends object>(config: AppAuthConfig<E>): MiddlewareHandler<AuthEnv<E>>;
|
|
13
|
+
export type ResolvedBearer = {
|
|
14
|
+
kind: AuthKind;
|
|
15
|
+
userId: string;
|
|
16
|
+
deviceId?: string;
|
|
17
|
+
} | {
|
|
18
|
+
kind: "invalid";
|
|
19
|
+
} | {
|
|
20
|
+
kind: "deleted";
|
|
21
|
+
};
|
|
22
|
+
export declare function ownsAccount(current: ResolvedBearer): current is {
|
|
23
|
+
kind: "session" | "legacy_access_token";
|
|
24
|
+
userId: string;
|
|
25
|
+
deviceId?: string;
|
|
26
|
+
};
|
|
27
|
+
export declare function resolveBearer<E>(config: AppAuthConfig<E>, env: E, token: string, options?: {
|
|
28
|
+
allowLegacy: boolean;
|
|
29
|
+
}): Promise<ResolvedBearer>;
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
import { decodeProtectedHeader } from "jose";
|
|
2
|
+
import { fromEnv } from "./config.js";
|
|
3
|
+
import { bearerToken, fail } from "./http.js";
|
|
4
|
+
import { verifyFirebaseToken } from "./providers.js";
|
|
5
|
+
import { sessionIsLive, userState } from "./store.js";
|
|
6
|
+
import { parseTokenSecrets, verifyAccessToken, verifyLegacyAccessToken } from "./tokens.js";
|
|
7
|
+
export function authenticate(config) {
|
|
8
|
+
return async (c, next) => {
|
|
9
|
+
const token = bearerToken(c);
|
|
10
|
+
if (!token)
|
|
11
|
+
return fail(c, 401, "missing_token", "Authorization: Bearer <token> is required");
|
|
12
|
+
const resolved = await resolveBearer(config, c.env, token);
|
|
13
|
+
if (resolved.kind === "invalid")
|
|
14
|
+
return fail(c, 401, "invalid_token", "access token is not valid");
|
|
15
|
+
if (resolved.kind === "deleted")
|
|
16
|
+
return fail(c, 410, "account_deleted", "account was deleted");
|
|
17
|
+
c.set("userId", resolved.userId);
|
|
18
|
+
c.set("auth_kind", resolved.kind);
|
|
19
|
+
await next();
|
|
20
|
+
};
|
|
21
|
+
}
|
|
22
|
+
export function ownsAccount(current) {
|
|
23
|
+
return current.kind === "session" || current.kind === "legacy_access_token";
|
|
24
|
+
}
|
|
25
|
+
export async function resolveBearer(config, env, token, options = { allowLegacy: true }) {
|
|
26
|
+
const now = config.now?.() ?? Date.now();
|
|
27
|
+
const db = config.db(env);
|
|
28
|
+
let alg;
|
|
29
|
+
let kid;
|
|
30
|
+
try {
|
|
31
|
+
;
|
|
32
|
+
({ alg, kid } = decodeProtectedHeader(token));
|
|
33
|
+
}
|
|
34
|
+
catch {
|
|
35
|
+
return { kind: "invalid" };
|
|
36
|
+
}
|
|
37
|
+
if (alg === "HS256" && kid === undefined) {
|
|
38
|
+
const legacy = fromEnv(config.legacyAccessToken, env);
|
|
39
|
+
const userId = legacy ? await verifyLegacyAccessToken(legacy, token, now) : null;
|
|
40
|
+
if (!userId)
|
|
41
|
+
return { kind: "invalid" };
|
|
42
|
+
const state = await userState(db, userId);
|
|
43
|
+
if (state === "deleted")
|
|
44
|
+
return { kind: "deleted" };
|
|
45
|
+
return state === "missing" ? { kind: "invalid" } : { kind: "legacy_access_token", userId };
|
|
46
|
+
}
|
|
47
|
+
if (alg === "HS256") {
|
|
48
|
+
const claims = await verifyAccessToken(parseTokenSecrets(config.tokenSecrets(env)), config.app, token, now);
|
|
49
|
+
if (!claims)
|
|
50
|
+
return { kind: "invalid" };
|
|
51
|
+
if (await sessionIsLive(db, claims.userId, claims.deviceId))
|
|
52
|
+
return { kind: "session", userId: claims.userId, deviceId: claims.deviceId };
|
|
53
|
+
return (await userState(db, claims.userId)) === "deleted" ? { kind: "deleted" } : { kind: "invalid" };
|
|
54
|
+
}
|
|
55
|
+
const firebase = fromEnv(config.legacyFirebase, env);
|
|
56
|
+
if (!options.allowLegacy || !firebase?.acceptLegacyBearer || alg !== "RS256")
|
|
57
|
+
return { kind: "invalid" };
|
|
58
|
+
const identity = await verifyFirebaseToken(firebase, token, now);
|
|
59
|
+
if (!identity)
|
|
60
|
+
return { kind: "invalid" };
|
|
61
|
+
if ((await userState(db, identity.uid)) === "deleted")
|
|
62
|
+
return { kind: "deleted" };
|
|
63
|
+
return { kind: "legacy_firebase", userId: identity.uid };
|
|
64
|
+
}
|
package/dist/config.d.ts
ADDED
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
import type { JWTVerifyGetKey } from "jose";
|
|
2
|
+
import type { LinkableProvider, SessionPerson } from "./contract.js";
|
|
3
|
+
import type { D1Like } from "./d1.js";
|
|
4
|
+
export type FromEnv<E, T> = T | ((env: E) => T);
|
|
5
|
+
export type KeySource = string | JWTVerifyGetKey;
|
|
6
|
+
export interface AppleConfig {
|
|
7
|
+
audience: string | string[];
|
|
8
|
+
keys?: KeySource;
|
|
9
|
+
revoke?: AppleRevokeConfig;
|
|
10
|
+
web?: AppleWebConfig;
|
|
11
|
+
}
|
|
12
|
+
export interface AppleWebConfig {
|
|
13
|
+
servicesId: string;
|
|
14
|
+
redirectUri: string;
|
|
15
|
+
returnUrl: string;
|
|
16
|
+
}
|
|
17
|
+
export interface DeviceAuthConfig {
|
|
18
|
+
verificationUri: string;
|
|
19
|
+
}
|
|
20
|
+
export interface AppleRevokeConfig {
|
|
21
|
+
teamId: string;
|
|
22
|
+
keyId: string;
|
|
23
|
+
clientId: string;
|
|
24
|
+
privateKey: string | undefined;
|
|
25
|
+
}
|
|
26
|
+
export interface GoogleConfig {
|
|
27
|
+
clientIds: string[];
|
|
28
|
+
keys?: KeySource;
|
|
29
|
+
}
|
|
30
|
+
export interface LegacyFirebaseConfig {
|
|
31
|
+
projectId: string;
|
|
32
|
+
acceptLegacyBearer: boolean;
|
|
33
|
+
keys?: KeySource;
|
|
34
|
+
webApiKey?: string;
|
|
35
|
+
}
|
|
36
|
+
export interface LegacyAccessTokenConfig {
|
|
37
|
+
secret: string | undefined;
|
|
38
|
+
issuer: string;
|
|
39
|
+
audience: string;
|
|
40
|
+
}
|
|
41
|
+
export interface RateLimiterLike {
|
|
42
|
+
limit(options: {
|
|
43
|
+
key: string;
|
|
44
|
+
}): Promise<{
|
|
45
|
+
success: boolean;
|
|
46
|
+
}>;
|
|
47
|
+
}
|
|
48
|
+
export interface RateLimitConfig {
|
|
49
|
+
anonymous?: RateLimiterLike | {
|
|
50
|
+
byIp?: RateLimiterLike;
|
|
51
|
+
byInstall?: RateLimiterLike;
|
|
52
|
+
};
|
|
53
|
+
refresh?: RateLimiterLike | {
|
|
54
|
+
byIp?: RateLimiterLike;
|
|
55
|
+
byDevice?: RateLimiterLike;
|
|
56
|
+
};
|
|
57
|
+
firebase?: RateLimiterLike;
|
|
58
|
+
deviceStart?: RateLimiterLike;
|
|
59
|
+
deviceVerify?: RateLimiterLike | {
|
|
60
|
+
byIp?: RateLimiterLike;
|
|
61
|
+
byUser?: RateLimiterLike;
|
|
62
|
+
};
|
|
63
|
+
}
|
|
64
|
+
export interface IssuedSession {
|
|
65
|
+
userId: string;
|
|
66
|
+
installId: string;
|
|
67
|
+
previousUserId: string | null;
|
|
68
|
+
}
|
|
69
|
+
export interface AuthHooks<E> {
|
|
70
|
+
onSessionIssued?: (issued: IssuedSession, env: E) => SessionPerson | void | Promise<SessionPerson | void>;
|
|
71
|
+
onUserCreated?: (userId: string, env: E) => void | Promise<void>;
|
|
72
|
+
onIdentityLinked?: (userId: string, provider: LinkableProvider, env: E) => void | Promise<void>;
|
|
73
|
+
}
|
|
74
|
+
export interface AppAuthConfig<E> {
|
|
75
|
+
app: string;
|
|
76
|
+
db: (env: E) => D1Like;
|
|
77
|
+
tokenSecrets: (env: E) => string | undefined;
|
|
78
|
+
apple?: FromEnv<E, AppleConfig | undefined>;
|
|
79
|
+
google?: FromEnv<E, GoogleConfig | undefined>;
|
|
80
|
+
legacyFirebase?: FromEnv<E, LegacyFirebaseConfig | undefined>;
|
|
81
|
+
legacyAccessToken?: FromEnv<E, LegacyAccessTokenConfig | undefined>;
|
|
82
|
+
device?: FromEnv<E, DeviceAuthConfig | undefined>;
|
|
83
|
+
anonymous?: FromEnv<E, boolean | undefined>;
|
|
84
|
+
requireNonce?: FromEnv<E, boolean | undefined>;
|
|
85
|
+
hooks?: AuthHooks<E>;
|
|
86
|
+
rateLimit?: FromEnv<E, RateLimitConfig | undefined>;
|
|
87
|
+
accessTokenTtlMs?: number;
|
|
88
|
+
refreshTokenIdleTtlMs?: number;
|
|
89
|
+
now?: () => number;
|
|
90
|
+
fetch?: typeof fetch;
|
|
91
|
+
}
|
|
92
|
+
export declare const DEFAULT_ACCESS_TOKEN_TTL_MS: number;
|
|
93
|
+
export declare const DEFAULT_REFRESH_TOKEN_IDLE_TTL_MS: number;
|
|
94
|
+
export declare function fromEnv<E, T>(value: FromEnv<E, T> | undefined, env: E): T | undefined;
|
package/dist/config.js
ADDED
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
export type ProviderId = "apple" | "google" | "anonymous";
|
|
2
|
+
export type LinkableProvider = Exclude<ProviderId, "anonymous">;
|
|
3
|
+
export type IdentityProvider = LinkableProvider | "firebase";
|
|
4
|
+
export type EpochMs = number;
|
|
5
|
+
export interface SessionUser {
|
|
6
|
+
id: string;
|
|
7
|
+
linkedProviders: ProviderId[];
|
|
8
|
+
createdAt: EpochMs;
|
|
9
|
+
}
|
|
10
|
+
export interface SessionPerson {
|
|
11
|
+
person_id: string;
|
|
12
|
+
merged: boolean;
|
|
13
|
+
}
|
|
14
|
+
export interface Session {
|
|
15
|
+
user: SessionUser;
|
|
16
|
+
accessToken: string;
|
|
17
|
+
accessTokenExpiresAt: EpochMs;
|
|
18
|
+
refreshToken: string;
|
|
19
|
+
appgrowstack?: SessionPerson;
|
|
20
|
+
}
|
|
21
|
+
export interface AnonymousRequest {
|
|
22
|
+
installId: string;
|
|
23
|
+
}
|
|
24
|
+
export interface RefreshRequest {
|
|
25
|
+
refreshToken: string;
|
|
26
|
+
}
|
|
27
|
+
export type SignInMode = "link_or_sign_in" | "sign_in_existing";
|
|
28
|
+
export interface AppleRequest {
|
|
29
|
+
identityToken: string;
|
|
30
|
+
installId: string;
|
|
31
|
+
nonce?: string;
|
|
32
|
+
mode?: SignInMode;
|
|
33
|
+
}
|
|
34
|
+
export interface GoogleRequest {
|
|
35
|
+
idToken: string;
|
|
36
|
+
installId: string;
|
|
37
|
+
nonce?: string;
|
|
38
|
+
mode?: SignInMode;
|
|
39
|
+
}
|
|
40
|
+
export interface AppleWebStartQuery {
|
|
41
|
+
installId: string;
|
|
42
|
+
platform: AppleWebPlatform;
|
|
43
|
+
codeChallenge: string;
|
|
44
|
+
}
|
|
45
|
+
export type AppleWebPlatform = "android";
|
|
46
|
+
export type AppleWebReturnQuery = {
|
|
47
|
+
code: string;
|
|
48
|
+
} | {
|
|
49
|
+
error: AppleWebReturnError;
|
|
50
|
+
};
|
|
51
|
+
export type AppleWebReturnError = "invalid_state" | "invalid_apple_token" | "user_cancelled_authorize" | "apple_error";
|
|
52
|
+
export interface AppleWebExchangeRequest {
|
|
53
|
+
code: string;
|
|
54
|
+
installId: string;
|
|
55
|
+
codeVerifier: string;
|
|
56
|
+
mode?: SignInMode;
|
|
57
|
+
}
|
|
58
|
+
export type UnlinkResponse = SessionUser;
|
|
59
|
+
export type FirebaseExchangeRequest = {
|
|
60
|
+
idToken: string;
|
|
61
|
+
installId: string;
|
|
62
|
+
} | {
|
|
63
|
+
refreshToken: string;
|
|
64
|
+
installId: string;
|
|
65
|
+
};
|
|
66
|
+
export interface DeviceStartRequest {
|
|
67
|
+
installId: string;
|
|
68
|
+
deviceName: string;
|
|
69
|
+
}
|
|
70
|
+
export interface DeviceStartResponse {
|
|
71
|
+
deviceCode: string;
|
|
72
|
+
userCode: string;
|
|
73
|
+
verificationUri: string;
|
|
74
|
+
verificationUriComplete: string;
|
|
75
|
+
expiresIn: number;
|
|
76
|
+
interval: number;
|
|
77
|
+
}
|
|
78
|
+
export interface DeviceLookupResponse {
|
|
79
|
+
deviceName: string;
|
|
80
|
+
createdAt: EpochMs;
|
|
81
|
+
}
|
|
82
|
+
export interface DeviceDecisionRequest {
|
|
83
|
+
userCode: string;
|
|
84
|
+
}
|
|
85
|
+
export interface DeviceTokenRequest {
|
|
86
|
+
deviceCode: string;
|
|
87
|
+
installId: string;
|
|
88
|
+
}
|
|
89
|
+
export type FirebaseRefreshRejection = "TOKEN_EXPIRED" | "USER_DISABLED" | "USER_NOT_FOUND" | "INVALID_REFRESH_TOKEN";
|
|
90
|
+
export type ErrorReason = "invalid_json" | "body_too_large" | "bad_request" | "missing_token" | "invalid_token" | "invalid_refresh_token" | "invalid_apple_token" | "invalid_google_token" | "invalid_nonce" | "invalid_firebase_token" | "legacy_credential_rejected" | "firebase_unavailable" | "rate_limited" | "credential_already_in_use" | "identity_not_linked" | "last_identity" | "account_not_found" | "invalid_code" | "provider_not_enabled" | "account_deleted" | "invalid_user_code" | "authorization_pending" | "slow_down" | "expired_token" | "access_denied";
|
|
91
|
+
export interface ErrorBody {
|
|
92
|
+
error: {
|
|
93
|
+
reason: ErrorReason;
|
|
94
|
+
message: string;
|
|
95
|
+
details?: Record<string, unknown>;
|
|
96
|
+
};
|
|
97
|
+
}
|
|
98
|
+
export type AuthKind = "session" | "legacy_firebase" | "legacy_access_token";
|
package/dist/contract.js
ADDED
|
File without changes
|
package/dist/d1.d.ts
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
export interface D1RunResult {
|
|
2
|
+
meta: {
|
|
3
|
+
changes: number;
|
|
4
|
+
};
|
|
5
|
+
}
|
|
6
|
+
export interface D1StatementLike {
|
|
7
|
+
bind(...values: unknown[]): D1StatementLike;
|
|
8
|
+
first<T = Record<string, unknown>>(): Promise<T | null>;
|
|
9
|
+
all<T = Record<string, unknown>>(): Promise<{
|
|
10
|
+
results: T[];
|
|
11
|
+
}>;
|
|
12
|
+
run(): Promise<D1RunResult>;
|
|
13
|
+
}
|
|
14
|
+
export interface D1Like {
|
|
15
|
+
prepare(sql: string): D1StatementLike;
|
|
16
|
+
batch(statements: D1StatementLike[]): Promise<D1RunResult[]>;
|
|
17
|
+
}
|
package/dist/d1.js
ADDED
|
File without changes
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import { type AppleRevocation } from "./apple-revoke.js";
|
|
2
|
+
import { type AppAuthConfig, type AppleRevokeConfig } from "./config.js";
|
|
3
|
+
import type { D1Like } from "./d1.js";
|
|
4
|
+
export interface DeleteUserOptions {
|
|
5
|
+
appleAuthorizationCode?: string;
|
|
6
|
+
appleRevoke?: AppleRevokeConfig | undefined;
|
|
7
|
+
fetch?: typeof fetch;
|
|
8
|
+
now?: number;
|
|
9
|
+
}
|
|
10
|
+
export interface DeleteUserResult {
|
|
11
|
+
apple: AppleRevocation;
|
|
12
|
+
}
|
|
13
|
+
export declare function deleteUser(db: D1Like, userId: string, options?: DeleteUserOptions): Promise<DeleteUserResult>;
|
|
14
|
+
export declare function appleRevokeConfig<E>(config: AppAuthConfig<E>, env: E): AppleRevokeConfig | undefined;
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import { revokeAppleAuthorization } from "./apple-revoke.js";
|
|
2
|
+
import { fromEnv } from "./config.js";
|
|
3
|
+
import { deleteAuthRows } from "./store.js";
|
|
4
|
+
export async function deleteUser(db, userId, options = {}) {
|
|
5
|
+
const now = options.now ?? Date.now();
|
|
6
|
+
const apple = options.appleAuthorizationCode
|
|
7
|
+
? await revokeAppleAuthorization(options.appleRevoke, options.appleAuthorizationCode, {
|
|
8
|
+
now,
|
|
9
|
+
...(options.fetch ? { fetch: options.fetch } : {}),
|
|
10
|
+
})
|
|
11
|
+
: { status: "not_requested" };
|
|
12
|
+
await deleteAuthRows(db, userId, now);
|
|
13
|
+
return { apple };
|
|
14
|
+
}
|
|
15
|
+
export function appleRevokeConfig(config, env) {
|
|
16
|
+
return fromEnv(config.apple, env)?.revoke;
|
|
17
|
+
}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import { Hono } from "hono";
|
|
2
|
+
import { type AuthEnv } from "./authenticate.js";
|
|
3
|
+
import { type AppAuthConfig } from "./config.js";
|
|
4
|
+
import type { Session } from "./contract.js";
|
|
5
|
+
export interface DeviceRouteDeps<E> {
|
|
6
|
+
now: () => number;
|
|
7
|
+
newSession: (env: E, userId: string, installId: string, at: number) => Promise<Session>;
|
|
8
|
+
}
|
|
9
|
+
export declare function deviceRoutes<E extends object>(config: AppAuthConfig<E>, deps: DeviceRouteDeps<E>): Hono<AuthEnv<E>>;
|