@allodium/auth 0.0.1 → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +103 -0
- package/dist/access.d.ts +105 -0
- package/dist/access.d.ts.map +1 -0
- package/dist/access.js +101 -0
- package/dist/access.js.map +1 -0
- package/dist/actAs.d.ts +100 -0
- package/dist/actAs.d.ts.map +1 -0
- package/dist/actAs.js +127 -0
- package/dist/actAs.js.map +1 -0
- package/dist/cookies.d.ts +51 -0
- package/dist/cookies.d.ts.map +1 -0
- package/dist/cookies.js +47 -0
- package/dist/cookies.js.map +1 -0
- package/dist/grants.d.ts +53 -0
- package/dist/grants.d.ts.map +1 -0
- package/dist/grants.js +84 -0
- package/dist/grants.js.map +1 -0
- package/dist/index.d.ts +19 -26
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +19 -20
- package/dist/index.js.map +1 -1
- package/dist/ip.d.ts +7 -0
- package/dist/ip.d.ts.map +1 -0
- package/dist/ip.js +10 -0
- package/dist/ip.js.map +1 -0
- package/dist/passwords.d.ts +20 -0
- package/dist/passwords.d.ts.map +1 -0
- package/dist/passwords.js +32 -0
- package/dist/passwords.js.map +1 -0
- package/dist/rateLimit.d.ts +23 -0
- package/dist/rateLimit.d.ts.map +1 -0
- package/dist/rateLimit.js +48 -0
- package/dist/rateLimit.js.map +1 -0
- package/dist/routes.d.ts +93 -0
- package/dist/routes.d.ts.map +1 -0
- package/dist/routes.js +201 -0
- package/dist/routes.js.map +1 -0
- package/dist/sessions.d.ts +92 -0
- package/dist/sessions.d.ts.map +1 -0
- package/dist/sessions.js +109 -0
- package/dist/sessions.js.map +1 -0
- package/dist/signedTokens.d.ts +45 -0
- package/dist/signedTokens.d.ts.map +1 -0
- package/dist/signedTokens.js +111 -0
- package/dist/signedTokens.js.map +1 -0
- package/package.json +25 -5
package/dist/cookies.js
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Session-cookie triple: access token, refresh token, and a readable expiry timestamp.
|
|
3
|
+
*
|
|
4
|
+
* Every setter AND deleter must use the same attributes: a cookie set with a Domain can
|
|
5
|
+
* only be cleared by a deletion carrying the same Domain, which is why deletion is
|
|
6
|
+
* set-empty-with-maxAge-0 rather than a delete() call.
|
|
7
|
+
*
|
|
8
|
+
* Framework-free: anything with a `set(name, value, options)` method works — both
|
|
9
|
+
* Next.js cookie stores (`await cookies()` and `NextResponse.cookies`) already do.
|
|
10
|
+
*/
|
|
11
|
+
/**
|
|
12
|
+
* `secure` and `domain` take thunks so deployments that read them from env keep
|
|
13
|
+
* call-time semantics (e.g. `() => process.env.NODE_ENV === 'production'`).
|
|
14
|
+
* `maxAgeSec` should equal the refresh-token TTL — one config value, not three copies.
|
|
15
|
+
*/
|
|
16
|
+
export function createSessionCookies(opts) {
|
|
17
|
+
const secure = typeof opts.secure === 'function' ? opts.secure : () => opts.secure;
|
|
18
|
+
const domain = typeof opts.domain === 'function' ? opts.domain : () => opts.domain;
|
|
19
|
+
const base = () => {
|
|
20
|
+
const d = domain();
|
|
21
|
+
return {
|
|
22
|
+
httpOnly: true,
|
|
23
|
+
secure: secure(),
|
|
24
|
+
sameSite: 'lax',
|
|
25
|
+
path: '/',
|
|
26
|
+
maxAge: opts.maxAgeSec,
|
|
27
|
+
...(d ? { domain: d } : {}),
|
|
28
|
+
};
|
|
29
|
+
};
|
|
30
|
+
return {
|
|
31
|
+
names: opts.names,
|
|
32
|
+
base,
|
|
33
|
+
set(store, tokens) {
|
|
34
|
+
const b = base();
|
|
35
|
+
store.set(opts.names.access, tokens.accessToken, b);
|
|
36
|
+
store.set(opts.names.refresh, tokens.refreshToken, b);
|
|
37
|
+
store.set(opts.names.expires, String(tokens.expiresAtMs), b);
|
|
38
|
+
},
|
|
39
|
+
clear(store) {
|
|
40
|
+
const b = { ...base(), maxAge: 0 };
|
|
41
|
+
for (const name of [opts.names.access, opts.names.refresh, opts.names.expires]) {
|
|
42
|
+
store.set(name, '', b);
|
|
43
|
+
}
|
|
44
|
+
},
|
|
45
|
+
};
|
|
46
|
+
}
|
|
47
|
+
//# sourceMappingURL=cookies.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"cookies.js","sourceRoot":"","sources":["../src/cookies.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AAiCH;;;;GAIG;AACH,MAAM,UAAU,oBAAoB,CAAC,IAKpC;IACC,MAAM,MAAM,GAAG,OAAO,IAAI,CAAC,MAAM,KAAK,UAAU,CAAC,CAAC,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC,CAAC,GAAG,EAAE,CAAC,IAAI,CAAC,MAAiB,CAAC;IAC9F,MAAM,MAAM,GAAG,OAAO,IAAI,CAAC,MAAM,KAAK,UAAU,CAAC,CAAC,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC,CAAC,GAAG,EAAE,CAAC,IAAI,CAAC,MAA4B,CAAC;IAEzG,MAAM,IAAI,GAAG,GAAsB,EAAE;QACnC,MAAM,CAAC,GAAG,MAAM,EAAE,CAAC;QACnB,OAAO;YACL,QAAQ,EAAE,IAAI;YACd,MAAM,EAAE,MAAM,EAAE;YAChB,QAAQ,EAAE,KAAK;YACf,IAAI,EAAE,GAAG;YACT,MAAM,EAAE,IAAI,CAAC,SAAS;YACtB,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;SAC5B,CAAC;IACJ,CAAC,CAAC;IAEF,OAAO;QACL,KAAK,EAAE,IAAI,CAAC,KAAK;QACjB,IAAI;QACJ,GAAG,CAAC,KAAK,EAAE,MAAM;YACf,MAAM,CAAC,GAAG,IAAI,EAAE,CAAC;YACjB,KAAK,CAAC,GAAG,CAAC,IAAI,CAAC,KAAK,CAAC,MAAM,EAAE,MAAM,CAAC,WAAW,EAAE,CAAC,CAAC,CAAC;YACpD,KAAK,CAAC,GAAG,CAAC,IAAI,CAAC,KAAK,CAAC,OAAO,EAAE,MAAM,CAAC,YAAY,EAAE,CAAC,CAAC,CAAC;YACtD,KAAK,CAAC,GAAG,CAAC,IAAI,CAAC,KAAK,CAAC,OAAO,EAAE,MAAM,CAAC,MAAM,CAAC,WAAW,CAAC,EAAE,CAAC,CAAC,CAAC;QAC/D,CAAC;QACD,KAAK,CAAC,KAAK;YACT,MAAM,CAAC,GAAG,EAAE,GAAG,IAAI,EAAE,EAAE,MAAM,EAAE,CAAC,EAAE,CAAC;YACnC,KAAK,MAAM,IAAI,IAAI,CAAC,IAAI,CAAC,KAAK,CAAC,MAAM,EAAE,IAAI,CAAC,KAAK,CAAC,OAAO,EAAE,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,EAAE,CAAC;gBAC/E,KAAK,CAAC,GAAG,CAAC,IAAI,EAAE,EAAE,EAAE,CAAC,CAAC,CAAC;YACzB,CAAC;QACH,CAAC;KACF,CAAC;AACJ,CAAC"}
|
package/dist/grants.d.ts
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
import { type AccessPolicy, type Actor, type Grant } from './access.js';
|
|
2
|
+
/**
|
|
3
|
+
* Reading grants out of a database, and building the actor a request runs as.
|
|
4
|
+
*
|
|
5
|
+
* Separate from the gate itself because the gate must stay pure: rules you can
|
|
6
|
+
* read back without standing up Postgres. This half is the opinionated one — it
|
|
7
|
+
* assumes the roles / user_roles / role_permissions shape Allodium's own seed
|
|
8
|
+
* defines. Every table name is an option, and an application with a different
|
|
9
|
+
* schema can skip this file entirely and hand `createAccessPolicy` its own
|
|
10
|
+
* grants; the gate does not care where they came from.
|
|
11
|
+
*
|
|
12
|
+
* Grants are cached, because otherwise every request pays three queries to learn
|
|
13
|
+
* a matrix that changes when somebody edits it in the console — which is rare
|
|
14
|
+
* and, when it happens, is a `refresh()` away.
|
|
15
|
+
*/
|
|
16
|
+
/** Anything pg-shaped: a Pool, a Client, a proxy. Same duck as the admin runtime's. */
|
|
17
|
+
export interface Queryable {
|
|
18
|
+
query(text: string, values?: unknown[]): Promise<{
|
|
19
|
+
rows: unknown[];
|
|
20
|
+
rowCount: number | null;
|
|
21
|
+
}>;
|
|
22
|
+
}
|
|
23
|
+
export interface GrantLoaderOptions {
|
|
24
|
+
/** Table holding role keys. Default "roles", keyed by "key". */
|
|
25
|
+
rolesTable?: string;
|
|
26
|
+
/** Table holding the matrix. Default "role_permissions". */
|
|
27
|
+
grantsTable?: string;
|
|
28
|
+
/** Join table of users to roles. Default "user_roles". */
|
|
29
|
+
userRolesTable?: string;
|
|
30
|
+
/** Roles that bypass the model. Passed straight to the policy. */
|
|
31
|
+
superuserRoles?: string[];
|
|
32
|
+
/** How long a loaded matrix stays good. Default 30s. */
|
|
33
|
+
ttlMs?: number;
|
|
34
|
+
}
|
|
35
|
+
export interface GrantLoader {
|
|
36
|
+
/** The matrix, cached. */
|
|
37
|
+
grants(): Promise<Grant[]>;
|
|
38
|
+
/** A policy over the current matrix. */
|
|
39
|
+
policy(): Promise<AccessPolicy>;
|
|
40
|
+
/** Role keys a user holds. Empty for an unknown user — which denies, it does not throw. */
|
|
41
|
+
rolesFor(userId: string): Promise<string[]>;
|
|
42
|
+
/**
|
|
43
|
+
* The actor for a signed-in user. `claims` are the app's to supply: which
|
|
44
|
+
* column identifies "this person's rows" is domain knowledge — a customer id
|
|
45
|
+
* here, a chapter id in ChapterHub — and a library that guessed would be wrong
|
|
46
|
+
* in a way nobody notices until it leaks.
|
|
47
|
+
*/
|
|
48
|
+
actorFor(userId: string, claims?: Record<string, unknown>): Promise<Actor>;
|
|
49
|
+
/** Drop the cache — call after editing the matrix. */
|
|
50
|
+
refresh(): void;
|
|
51
|
+
}
|
|
52
|
+
export declare function createGrantLoader(db: Queryable, opts?: GrantLoaderOptions): GrantLoader;
|
|
53
|
+
//# sourceMappingURL=grants.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"grants.d.ts","sourceRoot":"","sources":["../src/grants.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DED
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
import { createAccessPolicy } from './access.js';
|
|
2
|
+
const ident = (n) => '"' + n.replaceAll('"', '""') + '"';
|
|
3
|
+
/** row_filter arrives as jsonb; anything that is not an array of predicates is ignored loudly. */
|
|
4
|
+
function parseFilter(raw, where, problems) {
|
|
5
|
+
if (raw === null || raw === undefined)
|
|
6
|
+
return undefined;
|
|
7
|
+
const value = typeof raw === 'string' ? safeParse(raw) : raw;
|
|
8
|
+
if (!Array.isArray(value)) {
|
|
9
|
+
problems.push(`${where}: row_filter is not an array of predicates — ignored, so this grant covers EVERY row.`);
|
|
10
|
+
return undefined;
|
|
11
|
+
}
|
|
12
|
+
const out = [];
|
|
13
|
+
for (const p of value) {
|
|
14
|
+
if (!p || typeof p !== 'object' || typeof p.column !== 'string') {
|
|
15
|
+
problems.push(`${where}: a row_filter entry has no "column" — ignored.`);
|
|
16
|
+
continue;
|
|
17
|
+
}
|
|
18
|
+
out.push(p);
|
|
19
|
+
}
|
|
20
|
+
return out.length ? out : undefined;
|
|
21
|
+
}
|
|
22
|
+
function safeParse(s) {
|
|
23
|
+
try {
|
|
24
|
+
return JSON.parse(s);
|
|
25
|
+
}
|
|
26
|
+
catch {
|
|
27
|
+
return null;
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
export function createGrantLoader(db, opts = {}) {
|
|
31
|
+
const rolesTable = opts.rolesTable ?? 'roles';
|
|
32
|
+
const grantsTable = opts.grantsTable ?? 'role_permissions';
|
|
33
|
+
const userRolesTable = opts.userRolesTable ?? 'user_roles';
|
|
34
|
+
const ttl = opts.ttlMs ?? 30_000;
|
|
35
|
+
let cache = null;
|
|
36
|
+
async function load() {
|
|
37
|
+
if (cache && Date.now() - cache.at < ttl)
|
|
38
|
+
return cache;
|
|
39
|
+
const res = await db.query(`select r.key as role, g.table_name, g.can_create, g.can_read, g.can_update, g.can_delete,
|
|
40
|
+
${ /* row_filter is newer than the table; tolerate its absence */''}
|
|
41
|
+
to_jsonb(g) -> 'row_filter' as row_filter
|
|
42
|
+
from ${ident(grantsTable)} g
|
|
43
|
+
join ${ident(rolesTable)} r on r.id = g.role_id
|
|
44
|
+
order by r.key, g.table_name`);
|
|
45
|
+
const problems = [];
|
|
46
|
+
const grants = res.rows.map((row) => ({
|
|
47
|
+
role: String(row.role),
|
|
48
|
+
table: String(row.table_name),
|
|
49
|
+
create: !!row.can_create,
|
|
50
|
+
read: !!row.can_read,
|
|
51
|
+
update: !!row.can_update,
|
|
52
|
+
delete: !!row.can_delete,
|
|
53
|
+
...(() => {
|
|
54
|
+
const f = parseFilter(row.row_filter, `${row.role} on ${row.table_name}`, problems);
|
|
55
|
+
return f ? { rowFilter: f } : {};
|
|
56
|
+
})(),
|
|
57
|
+
}));
|
|
58
|
+
cache = { at: Date.now(), grants, problems };
|
|
59
|
+
return cache;
|
|
60
|
+
}
|
|
61
|
+
return {
|
|
62
|
+
async grants() {
|
|
63
|
+
return (await load()).grants;
|
|
64
|
+
},
|
|
65
|
+
async policy() {
|
|
66
|
+
const { grants, problems } = await load();
|
|
67
|
+
const policy = createAccessPolicy(grants, { superuserRoles: opts.superuserRoles });
|
|
68
|
+
// Loading problems and configuration problems are the same kind of thing to
|
|
69
|
+
// whoever has to fix them, so they arrive in one list.
|
|
70
|
+
return { ...policy, problems: [...problems, ...policy.problems] };
|
|
71
|
+
},
|
|
72
|
+
async rolesFor(userId) {
|
|
73
|
+
const res = await db.query(`select r.key from ${ident(userRolesTable)} ur join ${ident(rolesTable)} r on r.id = ur.role_id where ur.user_id = $1`, [userId]);
|
|
74
|
+
return res.rows.map((r) => r.key);
|
|
75
|
+
},
|
|
76
|
+
async actorFor(userId, claims = {}) {
|
|
77
|
+
return { userId, roles: await this.rolesFor(userId), claims };
|
|
78
|
+
},
|
|
79
|
+
refresh() {
|
|
80
|
+
cache = null;
|
|
81
|
+
},
|
|
82
|
+
};
|
|
83
|
+
}
|
|
84
|
+
//# sourceMappingURL=grants.js.map
|
|
@@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AE;YAChC,OAAO,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,IAAI,CAAC,QAAQ,CAAC,MAAM,CAAC,EAAE,MAAM,EAAE,CAAC;QAChE,CAAC;QACD,OAAO;YACL,KAAK,GAAG,IAAI,CAAC;QACf,CAAC;KACF,CAAC;AACJ,CAAC"}
|
package/dist/index.d.ts
CHANGED
|
@@ -1,32 +1,25 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* @allodium/auth — first-party authentication you own outright.
|
|
3
3
|
*
|
|
4
|
-
*
|
|
5
|
-
*
|
|
6
|
-
*
|
|
4
|
+
* Extracted from a production Next.js SaaS as its headless-CMS migration completed:
|
|
5
|
+
* argon2id passwords (Directus-hash compatible — zero password resets), a session store
|
|
6
|
+
* with single-use atomic refresh rotation and cross-surface origin scoping, stateless
|
|
7
|
+
* HMAC reset tokens that self-invalidate on password change, sliding-window rate
|
|
8
|
+
* limiting, and the session-cookie triple with Domain-correct clearing.
|
|
7
9
|
*
|
|
8
|
-
*
|
|
9
|
-
*
|
|
10
|
-
*
|
|
11
|
-
*
|
|
12
|
-
* httpOnly cookies, multiple concurrent sessions per user.
|
|
13
|
-
* - Refresh: short-lived access + rotating single-use refresh, with single-flight
|
|
14
|
-
* middleware guidance for the rotation race (or sliding sessions — your choice).
|
|
15
|
-
* - OIDC: provider-agnostic authorization-code flow (Google first), same-domain
|
|
16
|
-
* callbacks, one-identity-per-provider policy hooks.
|
|
17
|
-
* - Passkeys: @simplewebauthn-based ceremonies; credentials in your Postgres.
|
|
18
|
-
* - Reset: single-use hashed tokens + your SMTP; anti-enumeration (always-200) contract.
|
|
19
|
-
* - Tenancy: membership/role helpers for the org-per-row multi-tenant pattern.
|
|
10
|
+
* Everything is a factory taking explicit config — no env vars are read in here, no
|
|
11
|
+
* framework imports. Your app binds names, secrets, and tables once and re-exports;
|
|
12
|
+
* plus an "act as" user switcher that hooks your one identity seam.
|
|
13
|
+
* OIDC and WebAuthn ceremony helpers arrive in a later minor.
|
|
20
14
|
*/
|
|
21
|
-
export
|
|
22
|
-
|
|
23
|
-
export
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
}
|
|
30
|
-
|
|
31
|
-
export declare function version(): string;
|
|
15
|
+
export { hashPassword, verifyPassword, DUMMY_ARGON2ID_HASH } from './passwords.js';
|
|
16
|
+
export { createRateLimiter, type RateLimiter } from './rateLimit.js';
|
|
17
|
+
export { signPayload, verifySignedPayload, createResetTokens, makeStateToken, readStateToken, type ResetTokenPayload, type ResetTokens, } from './signedTokens.js';
|
|
18
|
+
export { createSessionCookies, type SessionCookieNames, type SessionCookieBase, type CookieSetter, type SessionCookies, } from './cookies.js';
|
|
19
|
+
export { createSessionStore, type SessionStore, type MintedSession, type OriginScope, } from './sessions.js';
|
|
20
|
+
export { createActAs, type ActAs, type ActAsState, type ActAsMode, type ActAsRefusal, type ActAsAuditEvent, type CreateActAsOptions, } from './actAs.js';
|
|
21
|
+
export { firstForwardedIp } from './ip.js';
|
|
22
|
+
export { createAccessPolicy, PUBLIC_ACTOR, PUBLIC_ROLE, ACTIONS, type Actor, type Action, type Grant, type GrantPredicate, type AccessDecision, type AccessPolicy, type AccessPolicyOptions, } from './access.js';
|
|
23
|
+
export { createGrantLoader, type GrantLoader, type GrantLoaderOptions, } from './grants.js';
|
|
24
|
+
export { createAuthRoutes, headerCookieSetter, readCookie, type AuthRoutes, type AuthRoutesOptions, type AuthUserRow, } from './routes.js';
|
|
32
25
|
//# sourceMappingURL=index.d.ts.map
|
package/dist/index.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;GAaG;AAEH,OAAO,EAAE,YAAY,EAAE,cAAc,EAAE,mBAAmB,EAAE,MAAM,gBAAgB,CAAC;AACnF,OAAO,EAAE,iBAAiB,EAAE,KAAK,WAAW,EAAE,MAAM,gBAAgB,CAAC;AACrE,OAAO,EACL,WAAW,EACX,mBAAmB,EACnB,iBAAiB,EACjB,cAAc,EACd,cAAc,EACd,KAAK,iBAAiB,EACtB,KAAK,WAAW,GACjB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EACL,oBAAoB,EACpB,KAAK,kBAAkB,EACvB,KAAK,iBAAiB,EACtB,KAAK,YAAY,EACjB,KAAK,cAAc,GACpB,MAAM,cAAc,CAAC;AACtB,OAAO,EACL,kBAAkB,EAClB,KAAK,YAAY,EACjB,KAAK,aAAa,EAClB,KAAK,WAAW,GACjB,MAAM,eAAe,CAAC;AACvB,OAAO,EACL,WAAW,EACX,KAAK,KAAK,EACV,KAAK,UAAU,EACf,KAAK,SAAS,EACd,KAAK,YAAY,EACjB,KAAK,eAAe,EACpB,KAAK,kBAAkB,GACxB,MAAM,YAAY,CAAC;AACpB,OAAO,EAAE,gBAAgB,EAAE,MAAM,SAAS,CAAC;AAC3C,OAAO,EACL,kBAAkB,EAClB,YAAY,EACZ,WAAW,EACX,OAAO,EACP,KAAK,KAAK,EACV,KAAK,MAAM,EACX,KAAK,KAAK,EACV,KAAK,cAAc,EACnB,KAAK,cAAc,EACnB,KAAK,YAAY,EACjB,KAAK,mBAAmB,GACzB,MAAM,aAAa,CAAC;AACrB,OAAO,EACL,iBAAiB,EACjB,KAAK,WAAW,EAChB,KAAK,kBAAkB,GACxB,MAAM,aAAa,CAAC;AACrB,OAAO,EACL,gBAAgB,EAChB,kBAAkB,EAClB,UAAU,EACV,KAAK,UAAU,EACf,KAAK,iBAAiB,EACtB,KAAK,WAAW,GACjB,MAAM,aAAa,CAAC"}
|
package/dist/index.js
CHANGED
|
@@ -1,26 +1,25 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* @allodium/auth — first-party authentication you own outright.
|
|
3
3
|
*
|
|
4
|
-
*
|
|
5
|
-
*
|
|
6
|
-
*
|
|
4
|
+
* Extracted from a production Next.js SaaS as its headless-CMS migration completed:
|
|
5
|
+
* argon2id passwords (Directus-hash compatible — zero password resets), a session store
|
|
6
|
+
* with single-use atomic refresh rotation and cross-surface origin scoping, stateless
|
|
7
|
+
* HMAC reset tokens that self-invalidate on password change, sliding-window rate
|
|
8
|
+
* limiting, and the session-cookie triple with Domain-correct clearing.
|
|
7
9
|
*
|
|
8
|
-
*
|
|
9
|
-
*
|
|
10
|
-
*
|
|
11
|
-
*
|
|
12
|
-
* httpOnly cookies, multiple concurrent sessions per user.
|
|
13
|
-
* - Refresh: short-lived access + rotating single-use refresh, with single-flight
|
|
14
|
-
* middleware guidance for the rotation race (or sliding sessions — your choice).
|
|
15
|
-
* - OIDC: provider-agnostic authorization-code flow (Google first), same-domain
|
|
16
|
-
* callbacks, one-identity-per-provider policy hooks.
|
|
17
|
-
* - Passkeys: @simplewebauthn-based ceremonies; credentials in your Postgres.
|
|
18
|
-
* - Reset: single-use hashed tokens + your SMTP; anti-enumeration (always-200) contract.
|
|
19
|
-
* - Tenancy: membership/role helpers for the org-per-row multi-tenant pattern.
|
|
10
|
+
* Everything is a factory taking explicit config — no env vars are read in here, no
|
|
11
|
+
* framework imports. Your app binds names, secrets, and tables once and re-exports;
|
|
12
|
+
* plus an "act as" user switcher that hooks your one identity seam.
|
|
13
|
+
* OIDC and WebAuthn ceremony helpers arrive in a later minor.
|
|
20
14
|
*/
|
|
21
|
-
export
|
|
22
|
-
|
|
23
|
-
export
|
|
24
|
-
|
|
25
|
-
}
|
|
15
|
+
export { hashPassword, verifyPassword, DUMMY_ARGON2ID_HASH } from './passwords.js';
|
|
16
|
+
export { createRateLimiter } from './rateLimit.js';
|
|
17
|
+
export { signPayload, verifySignedPayload, createResetTokens, makeStateToken, readStateToken, } from './signedTokens.js';
|
|
18
|
+
export { createSessionCookies, } from './cookies.js';
|
|
19
|
+
export { createSessionStore, } from './sessions.js';
|
|
20
|
+
export { createActAs, } from './actAs.js';
|
|
21
|
+
export { firstForwardedIp } from './ip.js';
|
|
22
|
+
export { createAccessPolicy, PUBLIC_ACTOR, PUBLIC_ROLE, ACTIONS, } from './access.js';
|
|
23
|
+
export { createGrantLoader, } from './grants.js';
|
|
24
|
+
export { createAuthRoutes, headerCookieSetter, readCookie, } from './routes.js';
|
|
26
25
|
//# sourceMappingURL=index.js.map
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;GAaG;AAEH,OAAO,EAAE,YAAY,EAAE,cAAc,EAAE,mBAAmB,EAAE,MAAM,gBAAgB,CAAC;AACnF,OAAO,EAAE,iBAAiB,EAAoB,MAAM,gBAAgB,CAAC;AACrE,OAAO,EACL,WAAW,EACX,mBAAmB,EACnB,iBAAiB,EACjB,cAAc,EACd,cAAc,GAGf,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EACL,oBAAoB,GAKrB,MAAM,cAAc,CAAC;AACtB,OAAO,EACL,kBAAkB,GAInB,MAAM,eAAe,CAAC;AACvB,OAAO,EACL,WAAW,GAOZ,MAAM,YAAY,CAAC;AACpB,OAAO,EAAE,gBAAgB,EAAE,MAAM,SAAS,CAAC;AAC3C,OAAO,EACL,kBAAkB,EAClB,YAAY,EACZ,WAAW,EACX,OAAO,GAQR,MAAM,aAAa,CAAC;AACrB,OAAO,EACL,iBAAiB,GAGlB,MAAM,aAAa,CAAC;AACrB,OAAO,EACL,gBAAgB,EAChB,kBAAkB,EAClB,UAAU,GAIX,MAAM,aAAa,CAAC"}
|
package/dist/ip.d.ts
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* First-hop client IP from an `x-forwarded-for` header value (the leftmost entry is the
|
|
3
|
+
* original client when your proxy chain appends). Null when the header is absent/empty —
|
|
4
|
+
* callers pick their own fallback ('unknown', null, …).
|
|
5
|
+
*/
|
|
6
|
+
export declare function firstForwardedIp(headerValue: string | null | undefined): string | null;
|
|
7
|
+
//# sourceMappingURL=ip.d.ts.map
|
package/dist/ip.d.ts.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"ip.d.ts","sourceRoot":"","sources":["../src/ip.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,wBAAgB,gBAAgB,CAAC,WAAW,EAAE,MAAM,GAAG,IAAI,GAAG,SAAS,GAAG,MAAM,GAAG,IAAI,CAGtF"}
|
package/dist/ip.js
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* First-hop client IP from an `x-forwarded-for` header value (the leftmost entry is the
|
|
3
|
+
* original client when your proxy chain appends). Null when the header is absent/empty —
|
|
4
|
+
* callers pick their own fallback ('unknown', null, …).
|
|
5
|
+
*/
|
|
6
|
+
export function firstForwardedIp(headerValue) {
|
|
7
|
+
const first = headerValue?.split(',')[0]?.trim();
|
|
8
|
+
return first || null;
|
|
9
|
+
}
|
|
10
|
+
//# sourceMappingURL=ip.js.map
|
package/dist/ip.js.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"ip.js","sourceRoot":"","sources":["../src/ip.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,MAAM,UAAU,gBAAgB,CAAC,WAAsC;IACrE,MAAM,KAAK,GAAG,WAAW,EAAE,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,EAAE,IAAI,EAAE,CAAC;IACjD,OAAO,KAAK,IAAI,IAAI,CAAC;AACvB,CAAC"}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Password hashing: argon2id via node-argon2's defaults (m=65536, t=3, p=4).
|
|
3
|
+
*
|
|
4
|
+
* These parameters are deliberately the same ones Directus uses, in both directions:
|
|
5
|
+
* hashes produced by a Directus deployment verify here unchanged (parameters are read
|
|
6
|
+
* from the hash string), and hashes created here verify in Directus during a parallel
|
|
7
|
+
* run — so a migration needs zero password resets. Audited in production during the
|
|
8
|
+
* reference deployment's cutover: 21/21 users verified.
|
|
9
|
+
*/
|
|
10
|
+
export declare function hashPassword(password: string): Promise<string>;
|
|
11
|
+
/** False on mismatch, malformed hash, or null hash — never throws on the login path. */
|
|
12
|
+
export declare function verifyPassword(hash: string | null | undefined, password: string): Promise<boolean>;
|
|
13
|
+
/**
|
|
14
|
+
* A real argon2id hash of a random throwaway string, for timing equalization: when the
|
|
15
|
+
* looked-up user doesn't exist (or is ineligible), verify the submitted password against
|
|
16
|
+
* this instead of skipping the verify, so response timing can't distinguish "no such
|
|
17
|
+
* account" from "wrong password".
|
|
18
|
+
*/
|
|
19
|
+
export declare const DUMMY_ARGON2ID_HASH = "$argon2id$v=19$m=65536,p=4,t=3$r5/l4lj1fHcz+2n6zW5Hqw$Mbkf6TySpCkDsNHd4UqC6jloSlRnLBgnJT82XC/ChHA";
|
|
20
|
+
//# sourceMappingURL=passwords.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"passwords.d.ts","sourceRoot":"","sources":["../src/passwords.ts"],"names":[],"mappings":"AAEA;;;;;;;;GAQG;AAEH,wBAAsB,YAAY,CAAC,QAAQ,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,CAEpE;AAED,wFAAwF;AACxF,wBAAsB,cAAc,CAAC,IAAI,EAAE,MAAM,GAAG,IAAI,GAAG,SAAS,EAAE,QAAQ,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC,CAOxG;AAED;;;;;GAKG;AACH,eAAO,MAAM,mBAAmB,sGACqE,CAAC"}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import argon2 from 'argon2';
|
|
2
|
+
/**
|
|
3
|
+
* Password hashing: argon2id via node-argon2's defaults (m=65536, t=3, p=4).
|
|
4
|
+
*
|
|
5
|
+
* These parameters are deliberately the same ones Directus uses, in both directions:
|
|
6
|
+
* hashes produced by a Directus deployment verify here unchanged (parameters are read
|
|
7
|
+
* from the hash string), and hashes created here verify in Directus during a parallel
|
|
8
|
+
* run — so a migration needs zero password resets. Audited in production during the
|
|
9
|
+
* reference deployment's cutover: 21/21 users verified.
|
|
10
|
+
*/
|
|
11
|
+
export async function hashPassword(password) {
|
|
12
|
+
return argon2.hash(password);
|
|
13
|
+
}
|
|
14
|
+
/** False on mismatch, malformed hash, or null hash — never throws on the login path. */
|
|
15
|
+
export async function verifyPassword(hash, password) {
|
|
16
|
+
if (!hash || !hash.startsWith('$argon2'))
|
|
17
|
+
return false;
|
|
18
|
+
try {
|
|
19
|
+
return await argon2.verify(hash, password);
|
|
20
|
+
}
|
|
21
|
+
catch {
|
|
22
|
+
return false;
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
/**
|
|
26
|
+
* A real argon2id hash of a random throwaway string, for timing equalization: when the
|
|
27
|
+
* looked-up user doesn't exist (or is ineligible), verify the submitted password against
|
|
28
|
+
* this instead of skipping the verify, so response timing can't distinguish "no such
|
|
29
|
+
* account" from "wrong password".
|
|
30
|
+
*/
|
|
31
|
+
export const DUMMY_ARGON2ID_HASH = '$argon2id$v=19$m=65536,p=4,t=3$r5/l4lj1fHcz+2n6zW5Hqw$Mbkf6TySpCkDsNHd4UqC6jloSlRnLBgnJT82XC/ChHA';
|
|
32
|
+
//# sourceMappingURL=passwords.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"passwords.js","sourceRoot":"","sources":["../src/passwords.ts"],"names":[],"mappings":"AAAA,OAAO,MAAM,MAAM,QAAQ,CAAC;AAE5B;;;;;;;;GAQG;AAEH,MAAM,CAAC,KAAK,UAAU,YAAY,CAAC,QAAgB;IACjD,OAAO,MAAM,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC;AAC/B,CAAC;AAED,wFAAwF;AACxF,MAAM,CAAC,KAAK,UAAU,cAAc,CAAC,IAA+B,EAAE,QAAgB;IACpF,IAAI,CAAC,IAAI,IAAI,CAAC,IAAI,CAAC,UAAU,CAAC,SAAS,CAAC;QAAE,OAAO,KAAK,CAAC;IACvD,IAAI,CAAC;QACH,OAAO,MAAM,MAAM,CAAC,MAAM,CAAC,IAAI,EAAE,QAAQ,CAAC,CAAC;IAC7C,CAAC;IAAC,MAAM,CAAC;QACP,OAAO,KAAK,CAAC;IACf,CAAC;AACH,CAAC;AAED;;;;;GAKG;AACH,MAAM,CAAC,MAAM,mBAAmB,GAC9B,mGAAmG,CAAC"}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* In-memory sliding-window rate limiter for auth endpoints.
|
|
3
|
+
*
|
|
4
|
+
* SINGLE-PROCESS ASSUMPTION: a process-local Map only sees this process's requests.
|
|
5
|
+
* Counters reset on restart or deploy (fail-open) and are NOT shared across instances —
|
|
6
|
+
* correct for the one-Next-process-per-box deployment shape; if you scale past one
|
|
7
|
+
* instance, put a shared store (Postgres/Redis) behind the same signature.
|
|
8
|
+
*
|
|
9
|
+
* Callers pick their own key namespace (e.g. 'login:ip:1.2.3.4', 'pwreq:email:a@b.c')
|
|
10
|
+
* and limits; the limiter itself is policy-free.
|
|
11
|
+
*/
|
|
12
|
+
export type RateLimiter = (key: string, max: number, windowMs: number) => boolean;
|
|
13
|
+
/**
|
|
14
|
+
* Create a limiter. The returned function is a sliding-window check: it returns true
|
|
15
|
+
* and RECORDS the hit when `key` has had fewer than `max` recorded hits in the trailing
|
|
16
|
+
* `windowMs`; it returns false (nothing recorded) when the key is over the limit — so a
|
|
17
|
+
* hammering client still gets at most `max` accepted attempts per window, and backing
|
|
18
|
+
* off actually helps.
|
|
19
|
+
*/
|
|
20
|
+
export declare function createRateLimiter(opts?: {
|
|
21
|
+
sweepIntervalMs?: number;
|
|
22
|
+
}): RateLimiter;
|
|
23
|
+
//# sourceMappingURL=rateLimit.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"rateLimit.d.ts","sourceRoot":"","sources":["../src/rateLimit.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AASH,MAAM,MAAM,WAAW,GAAG,CAAC,GAAG,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,KAAK,OAAO,CAAC;AAElF;;;;;;GAMG;AACH,wBAAgB,iBAAiB,CAAC,IAAI,GAAE;IAAE,eAAe,CAAC,EAAE,MAAM,CAAA;CAAO,GAAG,WAAW,CA+BtF"}
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* In-memory sliding-window rate limiter for auth endpoints.
|
|
3
|
+
*
|
|
4
|
+
* SINGLE-PROCESS ASSUMPTION: a process-local Map only sees this process's requests.
|
|
5
|
+
* Counters reset on restart or deploy (fail-open) and are NOT shared across instances —
|
|
6
|
+
* correct for the one-Next-process-per-box deployment shape; if you scale past one
|
|
7
|
+
* instance, put a shared store (Postgres/Redis) behind the same signature.
|
|
8
|
+
*
|
|
9
|
+
* Callers pick their own key namespace (e.g. 'login:ip:1.2.3.4', 'pwreq:email:a@b.c')
|
|
10
|
+
* and limits; the limiter itself is policy-free.
|
|
11
|
+
*/
|
|
12
|
+
/**
|
|
13
|
+
* Create a limiter. The returned function is a sliding-window check: it returns true
|
|
14
|
+
* and RECORDS the hit when `key` has had fewer than `max` recorded hits in the trailing
|
|
15
|
+
* `windowMs`; it returns false (nothing recorded) when the key is over the limit — so a
|
|
16
|
+
* hammering client still gets at most `max` accepted attempts per window, and backing
|
|
17
|
+
* off actually helps.
|
|
18
|
+
*/
|
|
19
|
+
export function createRateLimiter(opts = {}) {
|
|
20
|
+
const sweepIntervalMs = opts.sweepIntervalMs ?? 5 * 60_000;
|
|
21
|
+
const buckets = new Map();
|
|
22
|
+
let lastSweep = Date.now();
|
|
23
|
+
/** Opportunistic prune: drop buckets whose newest hit fell out of their own window. */
|
|
24
|
+
function sweep(now) {
|
|
25
|
+
if (now - lastSweep < sweepIntervalMs)
|
|
26
|
+
return;
|
|
27
|
+
lastSweep = now;
|
|
28
|
+
for (const [key, bucket] of buckets) {
|
|
29
|
+
const newest = bucket.times[bucket.times.length - 1];
|
|
30
|
+
if (newest === undefined || newest <= now - bucket.windowMs)
|
|
31
|
+
buckets.delete(key);
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
return function limit(key, max, windowMs) {
|
|
35
|
+
const now = Date.now();
|
|
36
|
+
sweep(now);
|
|
37
|
+
const cutoff = now - windowMs;
|
|
38
|
+
const times = (buckets.get(key)?.times ?? []).filter((t) => t > cutoff);
|
|
39
|
+
if (times.length >= max) {
|
|
40
|
+
buckets.set(key, { windowMs, times });
|
|
41
|
+
return false;
|
|
42
|
+
}
|
|
43
|
+
times.push(now);
|
|
44
|
+
buckets.set(key, { windowMs, times });
|
|
45
|
+
return true;
|
|
46
|
+
};
|
|
47
|
+
}
|
|
48
|
+
//# sourceMappingURL=rateLimit.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"rateLimit.js","sourceRoot":"","sources":["../src/rateLimit.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAWH;;;;;;GAMG;AACH,MAAM,UAAU,iBAAiB,CAAC,OAAqC,EAAE;IACvE,MAAM,eAAe,GAAG,IAAI,CAAC,eAAe,IAAI,CAAC,GAAG,MAAM,CAAC;IAC3D,MAAM,OAAO,GAAG,IAAI,GAAG,EAAkB,CAAC;IAC1C,IAAI,SAAS,GAAG,IAAI,CAAC,GAAG,EAAE,CAAC;IAE3B,uFAAuF;IACvF,SAAS,KAAK,CAAC,GAAW;QACxB,IAAI,GAAG,GAAG,SAAS,GAAG,eAAe;YAAE,OAAO;QAC9C,SAAS,GAAG,GAAG,CAAC;QAChB,KAAK,MAAM,CAAC,GAAG,EAAE,MAAM,CAAC,IAAI,OAAO,EAAE,CAAC;YACpC,MAAM,MAAM,GAAG,MAAM,CAAC,KAAK,CAAC,MAAM,CAAC,KAAK,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC;YACrD,IAAI,MAAM,KAAK,SAAS,IAAI,MAAM,IAAI,GAAG,GAAG,MAAM,CAAC,QAAQ;gBAAE,OAAO,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC;QACnF,CAAC;IACH,CAAC;IAED,OAAO,SAAS,KAAK,CAAC,GAAW,EAAE,GAAW,EAAE,QAAgB;QAC9D,MAAM,GAAG,GAAG,IAAI,CAAC,GAAG,EAAE,CAAC;QACvB,KAAK,CAAC,GAAG,CAAC,CAAC;QAEX,MAAM,MAAM,GAAG,GAAG,GAAG,QAAQ,CAAC;QAC9B,MAAM,KAAK,GAAG,CAAC,OAAO,CAAC,GAAG,CAAC,GAAG,CAAC,EAAE,KAAK,IAAI,EAAE,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,GAAG,MAAM,CAAC,CAAC;QAExE,IAAI,KAAK,CAAC,MAAM,IAAI,GAAG,EAAE,CAAC;YACxB,OAAO,CAAC,GAAG,CAAC,GAAG,EAAE,EAAE,QAAQ,EAAE,KAAK,EAAE,CAAC,CAAC;YACtC,OAAO,KAAK,CAAC;QACf,CAAC;QAED,KAAK,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;QAChB,OAAO,CAAC,GAAG,CAAC,GAAG,EAAE,EAAE,QAAQ,EAAE,KAAK,EAAE,CAAC,CAAC;QACtC,OAAO,IAAI,CAAC;IACd,CAAC,CAAC;AACJ,CAAC"}
|
package/dist/routes.d.ts
ADDED
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
import type { SessionStore } from './sessions.js';
|
|
2
|
+
import type { SessionCookies, CookieSetter } from './cookies.js';
|
|
3
|
+
import type { RateLimiter } from './rateLimit.js';
|
|
4
|
+
/**
|
|
5
|
+
* The four endpoints every app rewrites, written once.
|
|
6
|
+
*
|
|
7
|
+
* Login, logout, refresh and me are not interesting — which is exactly why they
|
|
8
|
+
* are worth shipping. Each one has two or three details that are easy to get
|
|
9
|
+
* wrong and silent when you do: a login that reveals which emails exist by
|
|
10
|
+
* returning faster for unknown ones; a /me that hands back the raw user row with
|
|
11
|
+
* its password hash; a refresh that clears the session on a network blip.
|
|
12
|
+
*
|
|
13
|
+
* Framework-free, like the rest of this package: these take a Web `Request` and
|
|
14
|
+
* return a Web `Response`, which is what a Next route handler, Hono, and a plain
|
|
15
|
+
* Node server with an adapter all speak. No env vars are read here.
|
|
16
|
+
*/
|
|
17
|
+
/** The row your user lookup returns. Nothing else about your schema is assumed. */
|
|
18
|
+
export interface AuthUserRow {
|
|
19
|
+
id: string;
|
|
20
|
+
/** argon2id digest. Null for an account with no password (SSO-only) — always refused here. */
|
|
21
|
+
passwordHash: string | null;
|
|
22
|
+
/** Anything non-active refuses with a DISTINGUISHABLE reason; see the note on login. */
|
|
23
|
+
status?: string | null;
|
|
24
|
+
}
|
|
25
|
+
export interface AuthRoutesOptions {
|
|
26
|
+
sessions: SessionStore;
|
|
27
|
+
cookies: SessionCookies;
|
|
28
|
+
/**
|
|
29
|
+
* The surface these sessions belong to — "site", "admin". Stored on the session
|
|
30
|
+
* and used to scope resolution, so a cookie moved between surfaces resolves to
|
|
31
|
+
* nothing. This is the whole reason `origin` exists on the store.
|
|
32
|
+
*/
|
|
33
|
+
origin: string;
|
|
34
|
+
/** Look up by email. Return null for unknown — the timing is equalised for you. */
|
|
35
|
+
findUserByEmail(email: string): Promise<AuthUserRow | null>;
|
|
36
|
+
/**
|
|
37
|
+
* What /me puts on the wire. REQUIRED, and required to be explicit.
|
|
38
|
+
*
|
|
39
|
+
* `resolveUser` hands back the raw database row, which on a users table means
|
|
40
|
+
* the password hash. Defaulting to "the row" would leak it from an endpoint
|
|
41
|
+
* whose entire job is to be called by a browser; defaulting to a guessed subset
|
|
42
|
+
* would be this library deciding what your users may see about themselves.
|
|
43
|
+
*/
|
|
44
|
+
toPublicUser(row: Record<string, unknown>): unknown;
|
|
45
|
+
/** Statuses allowed to sign in. Defaults to ['active']. */
|
|
46
|
+
activeStatuses?: string[];
|
|
47
|
+
/** Optional: attach roles and claims to /me, from the grant loader. */
|
|
48
|
+
actorFor?(userId: string): Promise<unknown>;
|
|
49
|
+
/** Optional login throttle. Keyed per email AND per IP — see below. */
|
|
50
|
+
rateLimit?: RateLimiter;
|
|
51
|
+
limits?: {
|
|
52
|
+
perEmail?: number;
|
|
53
|
+
perIp?: number;
|
|
54
|
+
windowMs?: number;
|
|
55
|
+
};
|
|
56
|
+
/**
|
|
57
|
+
* Origins allowed to call these endpoints with credentials.
|
|
58
|
+
*
|
|
59
|
+
* A cross-origin browser client cannot read a response without
|
|
60
|
+
* Access-Control-Allow-Origin naming its exact origin, and cannot send cookies
|
|
61
|
+
* without Allow-Credentials — and the wildcard is forbidden in combination with
|
|
62
|
+
* credentials, so this must be an allowlist. Omit it for a same-origin app.
|
|
63
|
+
*/
|
|
64
|
+
allowOrigins?: string[] | ((origin: string) => boolean);
|
|
65
|
+
}
|
|
66
|
+
export interface AuthRoutes {
|
|
67
|
+
/** POST — { email, password } */
|
|
68
|
+
login(request: Request): Promise<Response>;
|
|
69
|
+
/** POST — revokes whatever the cookie jar holds, always succeeds. */
|
|
70
|
+
logout(request: Request): Promise<Response>;
|
|
71
|
+
/** POST — single-use rotation of the refresh cookie. */
|
|
72
|
+
refresh(request: Request): Promise<Response>;
|
|
73
|
+
/** GET — the current user, or 401. */
|
|
74
|
+
me(request: Request): Promise<Response>;
|
|
75
|
+
/** OPTIONS — CORS preflight for any of the above. */
|
|
76
|
+
preflight(request: Request): Response;
|
|
77
|
+
}
|
|
78
|
+
/**
|
|
79
|
+
* A `CookieSetter` that writes into response headers.
|
|
80
|
+
*
|
|
81
|
+
* The cookie helper speaks the Next/`cookies()` shape — `set(name, value, opts)`
|
|
82
|
+
* — so bridging it to a Web Response means serialising here. Every cookie gets
|
|
83
|
+
* its own Set-Cookie header; folding them into one comma-separated value is a
|
|
84
|
+
* classic way to lose all but the first.
|
|
85
|
+
*/
|
|
86
|
+
export declare function headerCookieSetter(): {
|
|
87
|
+
setter: CookieSetter;
|
|
88
|
+
applyTo(headers: Headers): void;
|
|
89
|
+
};
|
|
90
|
+
/** Read one cookie from a request. No dependency, and no need for a general parser. */
|
|
91
|
+
export declare function readCookie(request: Request, name: string): string | undefined;
|
|
92
|
+
export declare function createAuthRoutes(opts: AuthRoutesOptions): AuthRoutes;
|
|
93
|
+
//# sourceMappingURL=routes.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"routes.d.ts","sourceRoot":"","sources":["../src/routes.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,eAAe,CAAC;AAClD,OAAO,KAAK,EAAE,cAAc,EAAE,YAAY,EAAE,MAAM,cAAc,CAAC;AACjE,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,gBAAgB,CAAC;AAElD;;;;;;;;;;;;GAYG;AAEH,mFAAmF;AACnF,MAAM,WAAW,WAAW;IAC1B,EAAE,EAAE,MAAM,CAAC;IACX,8FAA8F;IAC9F,YAAY,EAAE,MAAM,GAAG,IAAI,CAAC;IAC5B,wFAAwF;IACxF,MAAM,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;CACxB;AAED,MAAM,WAAW,iBAAiB;IAChC,QAAQ,EAAE,YAAY,CAAC;IACvB,OAAO,EAAE,cAAc,CAAC;IACxB;;;;OAIG;IACH,MAAM,EAAE,MAAM,CAAC;IACf,mFAAmF;IACnF,eAAe,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAAC,WAAW,GAAG,IAAI,CAAC,CAAC;IAC5D;;;;;;;OAOG;IACH,YAAY,CAAC,GAAG,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,OAAO,CAAC;IACpD,2DAA2D;IAC3D,cAAc,CAAC,EAAE,MAAM,EAAE,CAAC;IAC1B,uEAAuE;IACvE,QA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