@krizaka/auth 0.4.0 → 0.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +22 -3
- package/dist/chunk-H7AKE2OH.js +131 -0
- package/dist/chunk-H7AKE2OH.js.map +1 -0
- package/dist/identity-links-Dl9FNg6h.d.ts +225 -0
- package/dist/index.d.ts +72 -117
- package/dist/index.js +124 -12
- package/dist/index.js.map +1 -1
- package/dist/testkit.d.ts +15 -0
- package/dist/testkit.js +101 -0
- package/dist/testkit.js.map +1 -0
- package/package.json +13 -1
package/README.md
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
# @krizaka/auth
|
|
2
2
|
|
|
3
|
-
The account of a Krizaka product, behind a port: a display name, language, theme and avatar seed; the e-mail change by a link mailed to the **new** address (the verified flag is set by that very act); the password (checked before anything sensitive, other sessions signed out on change; reset by a link mailed to the account's address — the same answer whether or not the address has an account, the link used once within 30 minutes, every session signed out); the live sessions with sign-out of the others; the data export; the deletion. Each product keeps its **own** accounts — the package brings an adapter over the product's PostgreSQL and the migration it needs, nothing central.
|
|
3
|
+
The account of a Krizaka product, behind a port: a display name, language, theme and avatar seed; the e-mail change by a link mailed to the **new** address (the verified flag is set by that very act); the password (checked before anything sensitive, other sessions signed out on change; reset by a link mailed to the account's address — the same answer whether or not the address has an account, the link used once within 30 minutes by default — `passwordResetTtlMinutes`, 5 to 1440, read by the product from its settings and said in the mail — every session signed out); the live sessions with sign-out of the others; the data export; the deletion. Each product keeps its **own** accounts — the package brings an adapter over the product's PostgreSQL and the migration it needs, nothing central.
|
|
4
4
|
|
|
5
5
|
```ts
|
|
6
|
-
import { accountsMigration,
|
|
6
|
+
import { accountsMigration, dbAccounts } from "@krizaka/auth";
|
|
7
7
|
|
|
8
8
|
await db.query(accountsMigration({ backfillVerified: true })); // once, in your migrations (idempotent)
|
|
9
|
-
const accounts =
|
|
9
|
+
const accounts = dbAccounts({ query, transaction, mail, baseUrl: "https://www.akinaza.com", product: "Akinaza", tokenPrefix: "ae", passwords: { hash, verify }, tokenHash, passwordResetTtlMinutes: 30 /* optional, 5–1440 */ }); // `transaction`: the work on one connection (BEGIN … COMMIT); the password reset needs it under concurrent requests
|
|
10
10
|
await accounts.updateProfile(id, { name: "Éric", theme: "dark" });
|
|
11
11
|
await accounts.sessions(id, new Date(), currentSessionId);
|
|
12
12
|
await accounts.requestPasswordReset(email, new Date()); // mails `<baseUrl>/<locale>/reset-password?token=…`
|
|
@@ -18,3 +18,22 @@ The product keeps what is its own: its session cookie and token hashing (`tokenH
|
|
|
18
18
|
## Roles per scope
|
|
19
19
|
|
|
20
20
|
A role model is data: `defineRoles({ roles, permissions, manages })` says which roles exist, what each may do and who may hand which role to whom. `createRoles` keeps memberships (one person, several scopes, a role in each) and invitations (an e-mail invited with a role, a link used once, only its hash kept, never demoting), refuses to remove or demote the last owner, and answers `authorize(account, scope, "invoices")` with the role or a stable refusal (`NOT_A_MEMBER` 404, `FORBIDDEN` 403). `rolesMigration(roles, { scopeTable })` makes the tables.
|
|
21
|
+
|
|
22
|
+
## Federated sign-in (Google, Apple, Facebook, native PKCE)
|
|
23
|
+
|
|
24
|
+
Each product keeps its own accounts; **krizaka-users** is the federation provider behind a port, so a product holds no OAuth app of its own. `IdentityProvider` has two calls: `start(provider, returnTo, { codeChallenge? })` gives the address to send the person to, `complete(code, { codeVerifier? })` exchanges the one-time code (single use) for a verified `ExternalIdentity` (`issuer`, `subject`, `email`, `emailVerified`). A return address stays on the product (a path); an unknown provider is refused.
|
|
25
|
+
|
|
26
|
+
```ts
|
|
27
|
+
import { createFederatedSignIn, dbIdentityLinks, identityLinksMigration, usersIdentityProvider } from "@krizaka/auth";
|
|
28
|
+
|
|
29
|
+
await db.query(identityLinksMigration()); // once, in your migrations (idempotent): (issuer, subject) → account
|
|
30
|
+
const federation = usersIdentityProvider({ baseUrl: "https://auth.dev.akinaza.com", appUrl: "https://dev.akinaza.com", fetch });
|
|
31
|
+
const signIn = createFederatedSignIn({ links: dbIdentityLinks(query), accounts: { findByEmail, create }, clock });
|
|
32
|
+
|
|
33
|
+
const { url } = await federation.start("google", "/fr/account"); // redirect there
|
|
34
|
+
const result = await signIn.signIn(await federation.complete(code)); // { status: "signed-in", accountId, via } | { status: "refused", code }
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
An external identity attaches to an existing account **only when the address is verified on both sides** (by the provider and by the product); otherwise it is refused (`EMAIL_NOT_VERIFIED`, `ACCOUNT_EMAIL_UNVERIFIED`), and it is never a second user table. `create` is optional: leave it out and a person without an account is refused (`NO_ACCOUNT`). Adapters run the conformance kits of `@krizaka/auth/testkit` (`identityProviderContract`, `identityLinkStoreContract`).
|
|
38
|
+
|
|
39
|
+
> `postgresAccounts` was the first name of `dbAccounts`; it stays as a `@deprecated` alias for one minor and leaves in the next major.
|
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
// src/federation.ts
|
|
2
|
+
import crypto from "crypto";
|
|
3
|
+
var FEDERATED_PROVIDERS = ["google", "apple", "facebook"];
|
|
4
|
+
var isFederatedProvider = (value) => FEDERATED_PROVIDERS.includes(value);
|
|
5
|
+
var FEDERATION_CODE = {
|
|
6
|
+
invalidCode: "INVALID_CODE",
|
|
7
|
+
unknownProvider: "UNKNOWN_PROVIDER",
|
|
8
|
+
badReturn: "BAD_RETURN_TO",
|
|
9
|
+
unavailable: "UNAVAILABLE"
|
|
10
|
+
};
|
|
11
|
+
var FederationError = class extends Error {
|
|
12
|
+
constructor(code, message) {
|
|
13
|
+
super(message);
|
|
14
|
+
this.code = code;
|
|
15
|
+
this.name = "FederationError";
|
|
16
|
+
}
|
|
17
|
+
code;
|
|
18
|
+
};
|
|
19
|
+
var pkceChallenge = (verifier) => crypto.createHash("sha256").update(verifier).digest("base64url");
|
|
20
|
+
var isLocalReturn = (returnTo) => returnTo.startsWith("/") && !returnTo.startsWith("//") && !returnTo.includes("\\") && [...returnTo].every((c) => c.charCodeAt(0) > 31);
|
|
21
|
+
function memoryIdentityProvider() {
|
|
22
|
+
const pending = /* @__PURE__ */ new Map();
|
|
23
|
+
let counter = 0;
|
|
24
|
+
return {
|
|
25
|
+
async start(provider, returnTo) {
|
|
26
|
+
if (!isFederatedProvider(provider)) throw new FederationError(FEDERATION_CODE.unknownProvider, `Unknown provider ${String(provider)}`);
|
|
27
|
+
if (!isLocalReturn(returnTo)) throw new FederationError(FEDERATION_CODE.badReturn, "That return address is not allowed");
|
|
28
|
+
counter += 1;
|
|
29
|
+
const state = `state-${counter}`;
|
|
30
|
+
return { url: `https://auth.test/${provider}/start?state=${state}`, state };
|
|
31
|
+
},
|
|
32
|
+
async complete(code, options = {}) {
|
|
33
|
+
const entry = pending.get(code);
|
|
34
|
+
pending.delete(code);
|
|
35
|
+
if (!entry) throw new FederationError(FEDERATION_CODE.invalidCode, "That code is not valid");
|
|
36
|
+
if (entry.challenge !== null && (!options.codeVerifier || pkceChallenge(options.codeVerifier) !== entry.challenge)) throw new FederationError(FEDERATION_CODE.invalidCode, "That code is not valid");
|
|
37
|
+
return entry.identity;
|
|
38
|
+
},
|
|
39
|
+
issue(identity, challenge) {
|
|
40
|
+
counter += 1;
|
|
41
|
+
pending.set(`code-${counter}`, { identity, challenge: challenge ?? null });
|
|
42
|
+
return `code-${counter}`;
|
|
43
|
+
}
|
|
44
|
+
};
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
// src/identity-links.ts
|
|
48
|
+
import { compareAsc } from "date-fns";
|
|
49
|
+
var IdentityLinkError = class extends Error {
|
|
50
|
+
code = "ALREADY_LINKED";
|
|
51
|
+
constructor() {
|
|
52
|
+
super("That external identity is already linked to another account");
|
|
53
|
+
this.name = "IdentityLinkError";
|
|
54
|
+
}
|
|
55
|
+
};
|
|
56
|
+
function memoryIdentityLinks() {
|
|
57
|
+
const rows = /* @__PURE__ */ new Map();
|
|
58
|
+
const key = (issuer, subject) => `${issuer}
|
|
59
|
+
${subject}`;
|
|
60
|
+
return {
|
|
61
|
+
async find(issuer, subject) {
|
|
62
|
+
return rows.get(key(issuer, subject))?.accountId ?? null;
|
|
63
|
+
},
|
|
64
|
+
async link(accountId, issuer, subject, now) {
|
|
65
|
+
const existing = rows.get(key(issuer, subject));
|
|
66
|
+
if (existing && existing.accountId !== accountId) throw new IdentityLinkError();
|
|
67
|
+
if (!existing) rows.set(key(issuer, subject), { accountId, issuer, subject, linkedAt: now });
|
|
68
|
+
},
|
|
69
|
+
async unlink(accountId, issuer, subject) {
|
|
70
|
+
const existing = rows.get(key(issuer, subject));
|
|
71
|
+
if (existing?.accountId !== accountId) return false;
|
|
72
|
+
rows.delete(key(issuer, subject));
|
|
73
|
+
return true;
|
|
74
|
+
},
|
|
75
|
+
async list(accountId) {
|
|
76
|
+
return [...rows.values()].filter((r) => r.accountId === accountId).sort((a, b) => compareAsc(a.linkedAt, b.linkedAt)).map(({ issuer, subject, linkedAt }) => ({ issuer, subject, linkedAt }));
|
|
77
|
+
}
|
|
78
|
+
};
|
|
79
|
+
}
|
|
80
|
+
function identityLinksMigration() {
|
|
81
|
+
return `
|
|
82
|
+
CREATE TABLE IF NOT EXISTS external_identities (
|
|
83
|
+
issuer text NOT NULL CHECK (char_length(issuer) BETWEEN 1 AND 200),
|
|
84
|
+
subject text NOT NULL CHECK (char_length(subject) BETWEEN 1 AND 200),
|
|
85
|
+
account_id uuid NOT NULL REFERENCES accounts(id) ON DELETE CASCADE,
|
|
86
|
+
linked_at timestamptz NOT NULL,
|
|
87
|
+
PRIMARY KEY (issuer, subject)
|
|
88
|
+
);
|
|
89
|
+
CREATE INDEX IF NOT EXISTS external_identities_account ON external_identities(account_id, linked_at);
|
|
90
|
+
`;
|
|
91
|
+
}
|
|
92
|
+
function dbIdentityLinks(query) {
|
|
93
|
+
return {
|
|
94
|
+
async find(issuer, subject) {
|
|
95
|
+
const [row] = await query("SELECT account_id FROM external_identities WHERE issuer = $1 AND subject = $2", [issuer, subject]);
|
|
96
|
+
return row?.account_id ?? null;
|
|
97
|
+
},
|
|
98
|
+
async link(accountId, issuer, subject, now) {
|
|
99
|
+
const rows = await query(
|
|
100
|
+
`INSERT INTO external_identities (issuer, subject, account_id, linked_at) VALUES ($1, $2, $3, $4)
|
|
101
|
+
ON CONFLICT (issuer, subject) DO UPDATE SET issuer = excluded.issuer WHERE external_identities.account_id = excluded.account_id
|
|
102
|
+
RETURNING account_id`,
|
|
103
|
+
[issuer, subject, accountId, now]
|
|
104
|
+
);
|
|
105
|
+
if (rows.length === 0) throw new IdentityLinkError();
|
|
106
|
+
},
|
|
107
|
+
async unlink(accountId, issuer, subject) {
|
|
108
|
+
const rows = await query("DELETE FROM external_identities WHERE issuer = $1 AND subject = $2 AND account_id = $3 RETURNING 1", [issuer, subject, accountId]);
|
|
109
|
+
return rows.length > 0;
|
|
110
|
+
},
|
|
111
|
+
async list(accountId) {
|
|
112
|
+
const rows = await query("SELECT issuer, subject, linked_at FROM external_identities WHERE account_id = $1 ORDER BY linked_at, issuer, subject", [accountId]);
|
|
113
|
+
return rows.map((r) => ({ issuer: r.issuer, subject: r.subject, linkedAt: r.linked_at }));
|
|
114
|
+
}
|
|
115
|
+
};
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
export {
|
|
119
|
+
FEDERATED_PROVIDERS,
|
|
120
|
+
isFederatedProvider,
|
|
121
|
+
FEDERATION_CODE,
|
|
122
|
+
FederationError,
|
|
123
|
+
pkceChallenge,
|
|
124
|
+
isLocalReturn,
|
|
125
|
+
memoryIdentityProvider,
|
|
126
|
+
IdentityLinkError,
|
|
127
|
+
memoryIdentityLinks,
|
|
128
|
+
identityLinksMigration,
|
|
129
|
+
dbIdentityLinks
|
|
130
|
+
};
|
|
131
|
+
//# sourceMappingURL=chunk-H7AKE2OH.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/federation.ts","../src/identity-links.ts"],"sourcesContent":["import crypto from \"node:crypto\";\n\n/**\n * Federated sign-in (Google, Apple, Facebook, a native app's PKCE) delegated to krizaka-users, behind a PORT. The product keeps its\n * own accounts (`postgresAccounts`); this port only answers « who is this person, according to the provider ». An external\n * identity is never a second user table: it is a link to an account the product already has.\n */\nexport type FederatedProvider = \"google\" | \"apple\" | \"facebook\";\n\n/** The providers the port knows; anything else is refused before it reaches the adapter. */\nexport const FEDERATED_PROVIDERS: readonly FederatedProvider[] = [\"google\", \"apple\", \"facebook\"];\n\nexport const isFederatedProvider = (value: unknown): value is FederatedProvider => FEDERATED_PROVIDERS.includes(value as FederatedProvider);\n\n/** Who the provider says the person is. `issuer` + `subject` identify them for good; the address can change. */\nexport interface ExternalIdentity {\n /** The authority that vouches (`https://accounts.google.com`, `https://appleid.apple.com`…). */\n issuer: string;\n /** The person's stable id at that authority. */\n subject: string;\n email: string | null;\n /** The provider checked the address (a Facebook address, for one, may not be). */\n emailVerified: boolean;\n name: string | null;\n}\n\n/** What a sign-in is started with: a native app sends the PKCE challenge, a browser flow does not. */\nexport interface StartOptions {\n /** The S256 challenge of a PKCE flow (a native app); the matching verifier goes to `complete`. */\n codeChallenge?: string;\n}\n\nexport interface StartedSignIn {\n /** Where to send the person: the provider's consent page, through krizaka-users. */\n url: string;\n /** Echoed back with the code: the product checks it against the one it kept for this browser. */\n state: string;\n}\n\nexport interface CompleteOptions {\n /** The PKCE verifier of the challenge given to `start`. */\n codeVerifier?: string;\n}\n\nexport interface IdentityProvider {\n /** Starts a sign-in with `provider`; the person comes back to `returnTo` (a path or an address the adapter allows) with a one-time code. */\n start(provider: FederatedProvider, returnTo: string, options?: StartOptions): Promise<StartedSignIn>;\n /** Exchanges the one-time code (single use) for the verified identity. Throws `FederationError(\"INVALID_CODE\")` for a code that is unknown, used or expired. */\n complete(code: string, options?: CompleteOptions): Promise<ExternalIdentity>;\n}\n\nexport const FEDERATION_CODE = {\n invalidCode: \"INVALID_CODE\",\n unknownProvider: \"UNKNOWN_PROVIDER\",\n badReturn: \"BAD_RETURN_TO\",\n unavailable: \"UNAVAILABLE\",\n} as const;\nexport type FederationCode = (typeof FEDERATION_CODE)[keyof typeof FEDERATION_CODE];\n\nexport class FederationError extends Error {\n constructor(\n readonly code: FederationCode,\n message: string,\n ) {\n super(message);\n this.name = \"FederationError\";\n }\n}\n\n/** The S256 challenge of a PKCE verifier: base64url(SHA-256(verifier)). A native app computes it; the adapter and the in-memory provider check it. */\nexport const pkceChallenge = (verifier: string): string => crypto.createHash(\"sha256\").update(verifier).digest(\"base64url\");\n\n/** A return address stays on the product: a path (`/fr/account`), never `//host` or a scheme. */\nexport const isLocalReturn = (returnTo: string): boolean => returnTo.startsWith(\"/\") && !returnTo.startsWith(\"//\") && !returnTo.includes(\"\\\\\") && [...returnTo].every((c) => c.charCodeAt(0) > 31);\n\n/** An in-memory provider: the tests' adapter, and the reference the contract is written against. */\nexport function memoryIdentityProvider(): IdentityProvider & {\n /** Test seam: the one-time code the provider would hand back for this identity (with the PKCE challenge it was started with, if any). */\n issue(identity: ExternalIdentity, challenge?: string): string;\n} {\n const pending = new Map<string, { identity: ExternalIdentity; challenge: string | null }>();\n let counter = 0;\n return {\n async start(provider, returnTo) {\n if (!isFederatedProvider(provider)) throw new FederationError(FEDERATION_CODE.unknownProvider, `Unknown provider ${String(provider)}`);\n if (!isLocalReturn(returnTo)) throw new FederationError(FEDERATION_CODE.badReturn, \"That return address is not allowed\");\n counter += 1;\n const state = `state-${counter}`;\n return { url: `https://auth.test/${provider}/start?state=${state}`, state };\n },\n async complete(code, options = {}) {\n const entry = pending.get(code);\n pending.delete(code); // single use, whatever happens next\n if (!entry) throw new FederationError(FEDERATION_CODE.invalidCode, \"That code is not valid\");\n if (entry.challenge !== null && (!options.codeVerifier || pkceChallenge(options.codeVerifier) !== entry.challenge)) throw new FederationError(FEDERATION_CODE.invalidCode, \"That code is not valid\");\n return entry.identity;\n },\n issue(identity, challenge) {\n counter += 1;\n pending.set(`code-${counter}`, { identity, challenge: challenge ?? null });\n return `code-${counter}`;\n },\n };\n}\n","import { compareAsc } from \"date-fns\";\n\nimport type { Query } from \"./accounts\";\n\n/**\n * Which external identity belongs to which account. Never a second user table: a row is only `(issuer, subject) → account`.\n * The product's `accounts` stays the one place a person lives.\n */\nexport interface IdentityLinkStore {\n /** The account this external identity is linked to, or null. */\n find(issuer: string, subject: string): Promise<string | null>;\n /** Links it. Idempotent for the same account; throws when the identity is already linked to another one. */\n link(accountId: string, issuer: string, subject: string, now: Date): Promise<void>;\n /** Removes the link (the person unlinks Google); true when there was one. */\n unlink(accountId: string, issuer: string, subject: string): Promise<boolean>;\n /** The identities linked to an account, oldest first. */\n list(accountId: string): Promise<{ issuer: string; subject: string; linkedAt: Date }[]>;\n}\n\nexport class IdentityLinkError extends Error {\n readonly code = \"ALREADY_LINKED\";\n constructor() {\n super(\"That external identity is already linked to another account\");\n this.name = \"IdentityLinkError\";\n }\n}\n\n/** An in-memory store: the tests' adapter, and the reference the contract is written against. */\nexport function memoryIdentityLinks(): IdentityLinkStore {\n const rows = new Map<string, { accountId: string; issuer: string; subject: string; linkedAt: Date }>();\n const key = (issuer: string, subject: string) => `${issuer}\\n${subject}`;\n return {\n async find(issuer, subject) {\n return rows.get(key(issuer, subject))?.accountId ?? null;\n },\n async link(accountId, issuer, subject, now) {\n const existing = rows.get(key(issuer, subject));\n if (existing && existing.accountId !== accountId) throw new IdentityLinkError();\n if (!existing) rows.set(key(issuer, subject), { accountId, issuer, subject, linkedAt: now });\n },\n async unlink(accountId, issuer, subject) {\n const existing = rows.get(key(issuer, subject));\n if (existing?.accountId !== accountId) return false;\n rows.delete(key(issuer, subject));\n return true;\n },\n async list(accountId) {\n return [...rows.values()].filter((r) => r.accountId === accountId).sort((a, b) => compareAsc(a.linkedAt, b.linkedAt)).map(({ issuer, subject, linkedAt }) => ({ issuer, subject, linkedAt }));\n },\n };\n}\n\n/** The table of links (idempotent). `accounts` is the product's account table. */\nexport function identityLinksMigration(): string {\n return `\nCREATE TABLE IF NOT EXISTS external_identities (\n issuer text NOT NULL CHECK (char_length(issuer) BETWEEN 1 AND 200),\n subject text NOT NULL CHECK (char_length(subject) BETWEEN 1 AND 200),\n account_id uuid NOT NULL REFERENCES accounts(id) ON DELETE CASCADE,\n linked_at timestamptz NOT NULL,\n PRIMARY KEY (issuer, subject)\n);\nCREATE INDEX IF NOT EXISTS external_identities_account ON external_identities(account_id, linked_at);\n`;\n}\n\n/** The store over the product's own database (`external_identities`; see `identityLinksMigration`). */\nexport function dbIdentityLinks(query: Query): IdentityLinkStore {\n return {\n async find(issuer, subject) {\n const [row] = await query<{ account_id: string }>(\"SELECT account_id FROM external_identities WHERE issuer = $1 AND subject = $2\", [issuer, subject]);\n return row?.account_id ?? null;\n },\n async link(accountId, issuer, subject, now) {\n // One statement: the primary key decides a race; the same account is a no-op, another account is refused.\n const rows = await query<{ account_id: string }>(\n `INSERT INTO external_identities (issuer, subject, account_id, linked_at) VALUES ($1, $2, $3, $4)\n ON CONFLICT (issuer, subject) DO UPDATE SET issuer = excluded.issuer WHERE external_identities.account_id = excluded.account_id\n RETURNING account_id`,\n [issuer, subject, accountId, now],\n );\n if (rows.length === 0) throw new IdentityLinkError();\n },\n async unlink(accountId, issuer, subject) {\n const rows = await query(\"DELETE FROM external_identities WHERE issuer = $1 AND subject = $2 AND account_id = $3 RETURNING 1\", [issuer, subject, accountId]);\n return rows.length > 0;\n },\n async list(accountId) {\n const rows = await query<{ issuer: string; subject: string; linked_at: Date }>(\"SELECT issuer, subject, linked_at FROM external_identities WHERE account_id = $1 ORDER BY linked_at, issuer, subject\", [accountId]);\n return rows.map((r) => ({ issuer: r.issuer, subject: r.subject, linkedAt: r.linked_at }));\n },\n };\n}\n"],"mappings":"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","names":[]}
|
|
@@ -0,0 +1,225 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The account PORT (ADR-0008 of Yomizaka, now shared). A product's account — name, language, theme, avatar, e-mail change with
|
|
3
|
+
* verification, password (changed when signed in, or reset by a mailed link), sessions, export, deletion — behind one interface. Every product keeps its OWN accounts: no central
|
|
4
|
+
* service, no runtime dependency between products.
|
|
5
|
+
*/
|
|
6
|
+
type Theme = "light" | "dark" | "system";
|
|
7
|
+
interface AccountProfile {
|
|
8
|
+
id: string;
|
|
9
|
+
email: string;
|
|
10
|
+
name: string | null;
|
|
11
|
+
locale: "en" | "fr";
|
|
12
|
+
/** The theme the person chose; null = follow the device. */
|
|
13
|
+
theme: Theme | null;
|
|
14
|
+
/** A seed of the default avatars (the UI draws it); null = derived from the e-mail address. */
|
|
15
|
+
avatarSeed: string | null;
|
|
16
|
+
emailVerified: boolean;
|
|
17
|
+
/** An address awaiting its verification link, if the person asked to change it. */
|
|
18
|
+
pendingEmail: string | null;
|
|
19
|
+
}
|
|
20
|
+
interface ProfilePatch {
|
|
21
|
+
name?: string | null;
|
|
22
|
+
locale?: "en" | "fr";
|
|
23
|
+
theme?: Theme | null;
|
|
24
|
+
avatarSeed?: string | null;
|
|
25
|
+
}
|
|
26
|
+
/** A sign-in of the person: where from and when. Never the token. */
|
|
27
|
+
interface SessionSummary {
|
|
28
|
+
id: string;
|
|
29
|
+
createdAt: Date;
|
|
30
|
+
expiresAt: Date;
|
|
31
|
+
ip: string | null;
|
|
32
|
+
userAgent: string | null;
|
|
33
|
+
current: boolean;
|
|
34
|
+
}
|
|
35
|
+
interface AccountService {
|
|
36
|
+
profile(accountId: string): Promise<AccountProfile>;
|
|
37
|
+
updateProfile(accountId: string, patch: ProfilePatch): Promise<AccountProfile>;
|
|
38
|
+
/** Asks to change the address: the password is checked, a link is mailed to the NEW address. Answers the same whether or not it is already taken (no enumeration). */
|
|
39
|
+
requestEmailChange(accountId: string, input: {
|
|
40
|
+
newEmail: string;
|
|
41
|
+
password: string;
|
|
42
|
+
}, now: Date): Promise<void>;
|
|
43
|
+
/** Applies the change from the mailed link (single use, expires); the new address is verified by that very act. */
|
|
44
|
+
confirmEmailChange(token: string, now: Date): Promise<"CHANGED" | "INVALID">;
|
|
45
|
+
/** Changes the password (the current one is checked) and signs every other session out; `keepSessionId` stays. */
|
|
46
|
+
changePassword(accountId: string, input: {
|
|
47
|
+
current: string;
|
|
48
|
+
next: string;
|
|
49
|
+
}, keepSessionId?: string): Promise<void>;
|
|
50
|
+
/** Asks for a reset link, mailed (in the person's language) when an account with a password has this address; answers the same either way (no enumeration). */
|
|
51
|
+
requestPasswordReset(email: string, now: Date): Promise<void>;
|
|
52
|
+
/** Sets a new password from the mailed link — single use, expires — and signs every session out. The new password is checked before the link is used up. */
|
|
53
|
+
resetPassword(token: string, next: string, now: Date): Promise<"CHANGED" | "INVALID">;
|
|
54
|
+
/** Checks the password. Throws `AccountError(403, "WRONG_PASSWORD")`. */
|
|
55
|
+
confirmPassword(accountId: string, password: string): Promise<void>;
|
|
56
|
+
/** The person's live sign-ins, newest first; `currentSessionId` is flagged. */
|
|
57
|
+
sessions(accountId: string, now: Date, currentSessionId?: string): Promise<SessionSummary[]>;
|
|
58
|
+
/** Signs every other session out (and returns how many); `keepSessionId` stays. */
|
|
59
|
+
signOutOthers(accountId: string, keepSessionId: string): Promise<number>;
|
|
60
|
+
/** What the product keeps about the person, as one JSON-able document: the profile, the live sign-ins, and what `extra` adds. */
|
|
61
|
+
exportAccount(accountId: string, now: Date, extra?: () => Promise<Record<string, unknown>>): Promise<Record<string, unknown>>;
|
|
62
|
+
/** Deletes the identity: the account, its sessions and everything that hangs on it (the product erases its own data first). */
|
|
63
|
+
deleteAccount(accountId: string): Promise<void>;
|
|
64
|
+
}
|
|
65
|
+
declare class AccountError extends Error {
|
|
66
|
+
readonly status: number;
|
|
67
|
+
readonly code: string;
|
|
68
|
+
constructor(status: number, code: string, message: string);
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/** A SQL executor: the rows of a statement and its parameters (the product's pool). */
|
|
72
|
+
type Query = <T = Record<string, unknown>>(sql: string, params?: unknown[]) => Promise<T[]>;
|
|
73
|
+
interface Mail {
|
|
74
|
+
to: string;
|
|
75
|
+
/** The language of the mail (the person's). */
|
|
76
|
+
locale: "en" | "fr";
|
|
77
|
+
subject: string;
|
|
78
|
+
text: string;
|
|
79
|
+
}
|
|
80
|
+
interface AccountDeps {
|
|
81
|
+
query: Query;
|
|
82
|
+
/**
|
|
83
|
+
* Runs `work` in one transaction on one connection (BEGIN … COMMIT, rolled back when `work` throws) — the product's pool
|
|
84
|
+
* knows how. The password reset runs under it: the account row is locked, the links retired and issued, the token claimed,
|
|
85
|
+
* the password set and the sessions ended as one. Without it, the statements run one by one on `query` (one process, no
|
|
86
|
+
* concurrent requests): give it in production.
|
|
87
|
+
*/
|
|
88
|
+
transaction?: <T>(work: (query: Query) => Promise<T>) => Promise<T>;
|
|
89
|
+
mail: (mail: Mail) => Promise<void>;
|
|
90
|
+
/** `https://www.akinaza.com`: the e-mail change link is `<baseUrl>/<locale>/confirm-email?token=…`, the reset link `<baseUrl>/<locale>/reset-password?token=…`. */
|
|
91
|
+
baseUrl: string;
|
|
92
|
+
/** The product's name, in the words of the mail (« Akinaza »). */
|
|
93
|
+
product: string;
|
|
94
|
+
/** The product's token prefix, two or three letters (`ye1.` for Yomizaka: `ye`). The tokens are `<prefix>1.<43 base64url>`. */
|
|
95
|
+
tokenPrefix: string;
|
|
96
|
+
passwords: {
|
|
97
|
+
hash: (password: string) => Promise<string>;
|
|
98
|
+
verify: (password: string, stored: string) => Promise<boolean>;
|
|
99
|
+
};
|
|
100
|
+
/** How a token is kept: the product's own keyed hash, the one its sessions use. */
|
|
101
|
+
tokenHash: (token: string) => string;
|
|
102
|
+
/**
|
|
103
|
+
* How long a password reset link lives, in minutes: a whole number from 5 to 1440 (`PASSWORD_RESET_MIN_MINUTES`–`PASSWORD_RESET_MAX_MINUTES`),
|
|
104
|
+
* default `PASSWORD_RESET_TTL_MINUTES` (30). The product reads it from its settings; the expiry and the mailed text both use it.
|
|
105
|
+
* Out of range, `dbAccounts` throws.
|
|
106
|
+
*/
|
|
107
|
+
passwordResetTtlMinutes?: number;
|
|
108
|
+
/** Test seam: the token to issue. */
|
|
109
|
+
token?: () => string;
|
|
110
|
+
}
|
|
111
|
+
declare const EMAIL_CHANGE_TTL_HOURS = 24;
|
|
112
|
+
/** The default lifetime of a password reset link, in minutes (`AccountDeps.passwordResetTtlMinutes` changes it). */
|
|
113
|
+
declare const PASSWORD_RESET_TTL_MINUTES = 30;
|
|
114
|
+
declare const PASSWORD_RESET_MIN_MINUTES = 5;
|
|
115
|
+
declare const PASSWORD_RESET_MAX_MINUTES = 1440;
|
|
116
|
+
/** One format for every mailed link (an e-mail change, a password reset): the product's prefix, a version, 256 random bits. */
|
|
117
|
+
declare const linkToken: (prefix: string) => string;
|
|
118
|
+
declare const isLinkToken: (prefix: string, value: string | undefined | null) => value is string;
|
|
119
|
+
declare const emailChangeToken: (prefix: string) => string;
|
|
120
|
+
declare const isEmailChangeToken: (prefix: string, value: string | undefined | null) => value is string;
|
|
121
|
+
declare function passwordResetMail(product: string, locale: "en" | "fr", url: string, ttlMinutes?: number): {
|
|
122
|
+
subject: string;
|
|
123
|
+
text: string;
|
|
124
|
+
};
|
|
125
|
+
declare function emailChangeMail(product: string, locale: "en" | "fr", url: string): {
|
|
126
|
+
subject: string;
|
|
127
|
+
text: string;
|
|
128
|
+
};
|
|
129
|
+
/** The adapter over the product's own PostgreSQL (`accounts`, `sessions`, `email_changes`, `password_resets`; see `accountsMigration`). */
|
|
130
|
+
declare function dbAccounts(deps: AccountDeps): AccountService;
|
|
131
|
+
/** @deprecated The old name of `dbAccounts` (a name says what a thing does, not the technology). Removed in the next major. */
|
|
132
|
+
declare const postgresAccounts: typeof dbAccounts;
|
|
133
|
+
|
|
134
|
+
/**
|
|
135
|
+
* Federated sign-in (Google, Apple, Facebook, a native app's PKCE) delegated to krizaka-users, behind a PORT. The product keeps its
|
|
136
|
+
* own accounts (`postgresAccounts`); this port only answers « who is this person, according to the provider ». An external
|
|
137
|
+
* identity is never a second user table: it is a link to an account the product already has.
|
|
138
|
+
*/
|
|
139
|
+
type FederatedProvider = "google" | "apple" | "facebook";
|
|
140
|
+
/** The providers the port knows; anything else is refused before it reaches the adapter. */
|
|
141
|
+
declare const FEDERATED_PROVIDERS: readonly FederatedProvider[];
|
|
142
|
+
declare const isFederatedProvider: (value: unknown) => value is FederatedProvider;
|
|
143
|
+
/** Who the provider says the person is. `issuer` + `subject` identify them for good; the address can change. */
|
|
144
|
+
interface ExternalIdentity {
|
|
145
|
+
/** The authority that vouches (`https://accounts.google.com`, `https://appleid.apple.com`…). */
|
|
146
|
+
issuer: string;
|
|
147
|
+
/** The person's stable id at that authority. */
|
|
148
|
+
subject: string;
|
|
149
|
+
email: string | null;
|
|
150
|
+
/** The provider checked the address (a Facebook address, for one, may not be). */
|
|
151
|
+
emailVerified: boolean;
|
|
152
|
+
name: string | null;
|
|
153
|
+
}
|
|
154
|
+
/** What a sign-in is started with: a native app sends the PKCE challenge, a browser flow does not. */
|
|
155
|
+
interface StartOptions {
|
|
156
|
+
/** The S256 challenge of a PKCE flow (a native app); the matching verifier goes to `complete`. */
|
|
157
|
+
codeChallenge?: string;
|
|
158
|
+
}
|
|
159
|
+
interface StartedSignIn {
|
|
160
|
+
/** Where to send the person: the provider's consent page, through krizaka-users. */
|
|
161
|
+
url: string;
|
|
162
|
+
/** Echoed back with the code: the product checks it against the one it kept for this browser. */
|
|
163
|
+
state: string;
|
|
164
|
+
}
|
|
165
|
+
interface CompleteOptions {
|
|
166
|
+
/** The PKCE verifier of the challenge given to `start`. */
|
|
167
|
+
codeVerifier?: string;
|
|
168
|
+
}
|
|
169
|
+
interface IdentityProvider {
|
|
170
|
+
/** Starts a sign-in with `provider`; the person comes back to `returnTo` (a path or an address the adapter allows) with a one-time code. */
|
|
171
|
+
start(provider: FederatedProvider, returnTo: string, options?: StartOptions): Promise<StartedSignIn>;
|
|
172
|
+
/** Exchanges the one-time code (single use) for the verified identity. Throws `FederationError("INVALID_CODE")` for a code that is unknown, used or expired. */
|
|
173
|
+
complete(code: string, options?: CompleteOptions): Promise<ExternalIdentity>;
|
|
174
|
+
}
|
|
175
|
+
declare const FEDERATION_CODE: {
|
|
176
|
+
readonly invalidCode: "INVALID_CODE";
|
|
177
|
+
readonly unknownProvider: "UNKNOWN_PROVIDER";
|
|
178
|
+
readonly badReturn: "BAD_RETURN_TO";
|
|
179
|
+
readonly unavailable: "UNAVAILABLE";
|
|
180
|
+
};
|
|
181
|
+
type FederationCode = (typeof FEDERATION_CODE)[keyof typeof FEDERATION_CODE];
|
|
182
|
+
declare class FederationError extends Error {
|
|
183
|
+
readonly code: FederationCode;
|
|
184
|
+
constructor(code: FederationCode, message: string);
|
|
185
|
+
}
|
|
186
|
+
/** The S256 challenge of a PKCE verifier: base64url(SHA-256(verifier)). A native app computes it; the adapter and the in-memory provider check it. */
|
|
187
|
+
declare const pkceChallenge: (verifier: string) => string;
|
|
188
|
+
/** A return address stays on the product: a path (`/fr/account`), never `//host` or a scheme. */
|
|
189
|
+
declare const isLocalReturn: (returnTo: string) => boolean;
|
|
190
|
+
/** An in-memory provider: the tests' adapter, and the reference the contract is written against. */
|
|
191
|
+
declare function memoryIdentityProvider(): IdentityProvider & {
|
|
192
|
+
/** Test seam: the one-time code the provider would hand back for this identity (with the PKCE challenge it was started with, if any). */
|
|
193
|
+
issue(identity: ExternalIdentity, challenge?: string): string;
|
|
194
|
+
};
|
|
195
|
+
|
|
196
|
+
/**
|
|
197
|
+
* Which external identity belongs to which account. Never a second user table: a row is only `(issuer, subject) → account`.
|
|
198
|
+
* The product's `accounts` stays the one place a person lives.
|
|
199
|
+
*/
|
|
200
|
+
interface IdentityLinkStore {
|
|
201
|
+
/** The account this external identity is linked to, or null. */
|
|
202
|
+
find(issuer: string, subject: string): Promise<string | null>;
|
|
203
|
+
/** Links it. Idempotent for the same account; throws when the identity is already linked to another one. */
|
|
204
|
+
link(accountId: string, issuer: string, subject: string, now: Date): Promise<void>;
|
|
205
|
+
/** Removes the link (the person unlinks Google); true when there was one. */
|
|
206
|
+
unlink(accountId: string, issuer: string, subject: string): Promise<boolean>;
|
|
207
|
+
/** The identities linked to an account, oldest first. */
|
|
208
|
+
list(accountId: string): Promise<{
|
|
209
|
+
issuer: string;
|
|
210
|
+
subject: string;
|
|
211
|
+
linkedAt: Date;
|
|
212
|
+
}[]>;
|
|
213
|
+
}
|
|
214
|
+
declare class IdentityLinkError extends Error {
|
|
215
|
+
readonly code = "ALREADY_LINKED";
|
|
216
|
+
constructor();
|
|
217
|
+
}
|
|
218
|
+
/** An in-memory store: the tests' adapter, and the reference the contract is written against. */
|
|
219
|
+
declare function memoryIdentityLinks(): IdentityLinkStore;
|
|
220
|
+
/** The table of links (idempotent). `accounts` is the product's account table. */
|
|
221
|
+
declare function identityLinksMigration(): string;
|
|
222
|
+
/** The store over the product's own database (`external_identities`; see `identityLinksMigration`). */
|
|
223
|
+
declare function dbIdentityLinks(query: Query): IdentityLinkStore;
|
|
224
|
+
|
|
225
|
+
export { type AccountDeps as A, memoryIdentityProvider as B, type CompleteOptions as C, passwordResetMail as D, type ExternalIdentity as E, FEDERATED_PROVIDERS as F, pkceChallenge as G, postgresAccounts as H, type IdentityLinkStore as I, type Mail as M, PASSWORD_RESET_MAX_MINUTES as P, type Query as Q, type SessionSummary as S, type Theme as T, type IdentityProvider as a, AccountError as b, type AccountProfile as c, type AccountService as d, EMAIL_CHANGE_TTL_HOURS as e, FEDERATION_CODE as f, type FederatedProvider as g, type FederationCode as h, FederationError as i, IdentityLinkError as j, PASSWORD_RESET_MIN_MINUTES as k, PASSWORD_RESET_TTL_MINUTES as l, type ProfilePatch as m, type StartOptions as n, type StartedSignIn as o, dbAccounts as p, dbIdentityLinks as q, emailChangeMail as r, emailChangeToken as s, identityLinksMigration as t, isEmailChangeToken as u, isFederatedProvider as v, isLinkToken as w, isLocalReturn as x, linkToken as y, memoryIdentityLinks as z };
|
package/dist/index.d.ts
CHANGED
|
@@ -1,124 +1,54 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
* verification, password (changed when signed in, or reset by a mailed link), sessions, export, deletion — behind one interface. Every product keeps its OWN accounts: no central
|
|
4
|
-
* service, no runtime dependency between products.
|
|
5
|
-
*/
|
|
6
|
-
type Theme = "light" | "dark" | "system";
|
|
7
|
-
interface AccountProfile {
|
|
8
|
-
id: string;
|
|
9
|
-
email: string;
|
|
10
|
-
name: string | null;
|
|
11
|
-
locale: "en" | "fr";
|
|
12
|
-
/** The theme the person chose; null = follow the device. */
|
|
13
|
-
theme: Theme | null;
|
|
14
|
-
/** A seed of the default avatars (the UI draws it); null = derived from the e-mail address. */
|
|
15
|
-
avatarSeed: string | null;
|
|
16
|
-
emailVerified: boolean;
|
|
17
|
-
/** An address awaiting its verification link, if the person asked to change it. */
|
|
18
|
-
pendingEmail: string | null;
|
|
19
|
-
}
|
|
20
|
-
interface ProfilePatch {
|
|
21
|
-
name?: string | null;
|
|
22
|
-
locale?: "en" | "fr";
|
|
23
|
-
theme?: Theme | null;
|
|
24
|
-
avatarSeed?: string | null;
|
|
25
|
-
}
|
|
26
|
-
/** A sign-in of the person: where from and when. Never the token. */
|
|
27
|
-
interface SessionSummary {
|
|
28
|
-
id: string;
|
|
29
|
-
createdAt: Date;
|
|
30
|
-
expiresAt: Date;
|
|
31
|
-
ip: string | null;
|
|
32
|
-
userAgent: string | null;
|
|
33
|
-
current: boolean;
|
|
34
|
-
}
|
|
35
|
-
interface AccountService {
|
|
36
|
-
profile(accountId: string): Promise<AccountProfile>;
|
|
37
|
-
updateProfile(accountId: string, patch: ProfilePatch): Promise<AccountProfile>;
|
|
38
|
-
/** Asks to change the address: the password is checked, a link is mailed to the NEW address. Answers the same whether or not it is already taken (no enumeration). */
|
|
39
|
-
requestEmailChange(accountId: string, input: {
|
|
40
|
-
newEmail: string;
|
|
41
|
-
password: string;
|
|
42
|
-
}, now: Date): Promise<void>;
|
|
43
|
-
/** Applies the change from the mailed link (single use, expires); the new address is verified by that very act. */
|
|
44
|
-
confirmEmailChange(token: string, now: Date): Promise<"CHANGED" | "INVALID">;
|
|
45
|
-
/** Changes the password (the current one is checked) and signs every other session out; `keepSessionId` stays. */
|
|
46
|
-
changePassword(accountId: string, input: {
|
|
47
|
-
current: string;
|
|
48
|
-
next: string;
|
|
49
|
-
}, keepSessionId?: string): Promise<void>;
|
|
50
|
-
/** Asks for a reset link, mailed (in the person's language) when an account with a password has this address; answers the same either way (no enumeration). */
|
|
51
|
-
requestPasswordReset(email: string, now: Date): Promise<void>;
|
|
52
|
-
/** Sets a new password from the mailed link — single use, expires — and signs every session out. The new password is checked before the link is used up. */
|
|
53
|
-
resetPassword(token: string, next: string, now: Date): Promise<"CHANGED" | "INVALID">;
|
|
54
|
-
/** Checks the password. Throws `AccountError(403, "WRONG_PASSWORD")`. */
|
|
55
|
-
confirmPassword(accountId: string, password: string): Promise<void>;
|
|
56
|
-
/** The person's live sign-ins, newest first; `currentSessionId` is flagged. */
|
|
57
|
-
sessions(accountId: string, now: Date, currentSessionId?: string): Promise<SessionSummary[]>;
|
|
58
|
-
/** Signs every other session out (and returns how many); `keepSessionId` stays. */
|
|
59
|
-
signOutOthers(accountId: string, keepSessionId: string): Promise<number>;
|
|
60
|
-
/** What the product keeps about the person, as one JSON-able document: the profile, the live sign-ins, and what `extra` adds. */
|
|
61
|
-
exportAccount(accountId: string, now: Date, extra?: () => Promise<Record<string, unknown>>): Promise<Record<string, unknown>>;
|
|
62
|
-
/** Deletes the identity: the account, its sessions and everything that hangs on it (the product erases its own data first). */
|
|
63
|
-
deleteAccount(accountId: string): Promise<void>;
|
|
64
|
-
}
|
|
65
|
-
declare class AccountError extends Error {
|
|
66
|
-
readonly status: number;
|
|
67
|
-
readonly code: string;
|
|
68
|
-
constructor(status: number, code: string, message: string);
|
|
69
|
-
}
|
|
1
|
+
import { E as ExternalIdentity, I as IdentityLinkStore, a as IdentityProvider } from './identity-links-Dl9FNg6h.js';
|
|
2
|
+
export { A as AccountDeps, b as AccountError, c as AccountProfile, d as AccountService, C as CompleteOptions, e as EMAIL_CHANGE_TTL_HOURS, F as FEDERATED_PROVIDERS, f as FEDERATION_CODE, g as FederatedProvider, h as FederationCode, i as FederationError, j as IdentityLinkError, M as Mail, P as PASSWORD_RESET_MAX_MINUTES, k as PASSWORD_RESET_MIN_MINUTES, l as PASSWORD_RESET_TTL_MINUTES, m as ProfilePatch, Q as Query, S as SessionSummary, n as StartOptions, o as StartedSignIn, T as Theme, p as dbAccounts, q as dbIdentityLinks, r as emailChangeMail, s as emailChangeToken, t as identityLinksMigration, u as isEmailChangeToken, v as isFederatedProvider, w as isLinkToken, x as isLocalReturn, y as linkToken, z as memoryIdentityLinks, B as memoryIdentityProvider, D as passwordResetMail, G as pkceChallenge, H as postgresAccounts } from './identity-links-Dl9FNg6h.js';
|
|
70
3
|
|
|
71
|
-
/**
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
4
|
+
/** What federated sign-in needs from the product's accounts: no second user table, just a look-up and, when registration is open, a creation. */
|
|
5
|
+
interface FederatedAccounts {
|
|
6
|
+
/** The account that holds this address (lower case), and whether the product has verified it; null when none. */
|
|
7
|
+
findByEmail(email: string): Promise<{
|
|
8
|
+
id: string;
|
|
9
|
+
emailVerified: boolean;
|
|
10
|
+
} | null>;
|
|
11
|
+
/** Creates an account for a person the provider vouches for (address verified, no password). Absent when registration is closed. */
|
|
12
|
+
create?(identity: ExternalIdentity & {
|
|
13
|
+
email: string;
|
|
14
|
+
}): Promise<string>;
|
|
79
15
|
}
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
/**
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
16
|
+
/** Why a sign-in was refused: a stable code the product maps to its words. */
|
|
17
|
+
declare const FEDERATED_REFUSAL: {
|
|
18
|
+
/** The provider did not verify the address (or gave none): nothing is linked, nothing is created. */
|
|
19
|
+
readonly emailNotVerified: "EMAIL_NOT_VERIFIED";
|
|
20
|
+
/** An account holds the address but the product never verified it: linking would let a stranger take it over. */
|
|
21
|
+
readonly accountEmailUnverified: "ACCOUNT_EMAIL_UNVERIFIED";
|
|
22
|
+
/** No account, and registration is closed. */
|
|
23
|
+
readonly noAccount: "NO_ACCOUNT";
|
|
24
|
+
};
|
|
25
|
+
type FederatedRefusal = (typeof FEDERATED_REFUSAL)[keyof typeof FEDERATED_REFUSAL];
|
|
26
|
+
type FederatedSignInResult =
|
|
27
|
+
/** `via`: `link` already linked, `linked` attached to the account of that address now, `created` a new account. */
|
|
28
|
+
{
|
|
29
|
+
status: "signed-in";
|
|
30
|
+
accountId: string;
|
|
31
|
+
via: "link" | "linked" | "created";
|
|
32
|
+
} | {
|
|
33
|
+
status: "refused";
|
|
34
|
+
code: FederatedRefusal;
|
|
35
|
+
};
|
|
36
|
+
interface FederatedSignInDeps {
|
|
37
|
+
links: IdentityLinkStore;
|
|
38
|
+
accounts: FederatedAccounts;
|
|
39
|
+
clock: {
|
|
40
|
+
now(): Date;
|
|
99
41
|
};
|
|
100
|
-
/** How a token is kept: the product's own keyed hash, the one its sessions use. */
|
|
101
|
-
tokenHash: (token: string) => string;
|
|
102
|
-
/** Test seam: the token to issue. */
|
|
103
|
-
token?: () => string;
|
|
104
42
|
}
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
declare
|
|
111
|
-
|
|
112
|
-
declare function passwordResetMail(product: string, locale: "en" | "fr", url: string): {
|
|
113
|
-
subject: string;
|
|
114
|
-
text: string;
|
|
115
|
-
};
|
|
116
|
-
declare function emailChangeMail(product: string, locale: "en" | "fr", url: string): {
|
|
117
|
-
subject: string;
|
|
118
|
-
text: string;
|
|
43
|
+
/**
|
|
44
|
+
* From a verified external identity to an account of the product. The rule that matters: an identity attaches to an EXISTING account
|
|
45
|
+
* only when the address is verified on both sides — by the provider and by the product. Otherwise a stranger who registers at
|
|
46
|
+
* Facebook with your address would sign in as you.
|
|
47
|
+
*/
|
|
48
|
+
declare function createFederatedSignIn({ links, accounts, clock }: FederatedSignInDeps): {
|
|
49
|
+
signIn(identity: ExternalIdentity): Promise<FederatedSignInResult>;
|
|
119
50
|
};
|
|
120
|
-
|
|
121
|
-
declare function postgresAccounts(deps: AccountDeps): AccountService;
|
|
51
|
+
type FederatedSignIn = ReturnType<typeof createFederatedSignIn>;
|
|
122
52
|
|
|
123
53
|
/**
|
|
124
54
|
* What the account adapter needs from a product's database, safe to run on a database that already has `accounts` and `sessions`:
|
|
@@ -241,4 +171,29 @@ declare function createRoles<Role extends string, Permission extends string>(dep
|
|
|
241
171
|
};
|
|
242
172
|
type Roles<Role extends string = string, Permission extends string = string> = ReturnType<typeof createRoles<Role, Permission>>;
|
|
243
173
|
|
|
244
|
-
|
|
174
|
+
/** The `fetch` the adapter calls krizaka-users with (injected: no global, no network in tests). */
|
|
175
|
+
type Fetcher = (url: string, init: {
|
|
176
|
+
method: "POST";
|
|
177
|
+
headers: Record<string, string>;
|
|
178
|
+
body: string;
|
|
179
|
+
}) => Promise<{
|
|
180
|
+
ok: boolean;
|
|
181
|
+
status: number;
|
|
182
|
+
json(): Promise<unknown>;
|
|
183
|
+
}>;
|
|
184
|
+
interface UsersFederationOptions {
|
|
185
|
+
/** The tenant host of the product: `https://auth.dev.akinaza.com`. */
|
|
186
|
+
baseUrl: string;
|
|
187
|
+
/** The product's public address: the start URL sends the person back to it, so `returnTo` is absolute from it. */
|
|
188
|
+
appUrl: string;
|
|
189
|
+
fetch: Fetcher;
|
|
190
|
+
}
|
|
191
|
+
/** Reads krizaka-users' answer into an identity; anything that is not a complete identity is refused. */
|
|
192
|
+
declare function parseExternalIdentity(body: unknown): ExternalIdentity;
|
|
193
|
+
/**
|
|
194
|
+
* The adapter for krizaka-users (`auth.<product>` tenant host, krizaka/krizaka-users#31): `start` builds the tenant's start address,
|
|
195
|
+
* `complete` exchanges the one-time code (and the PKCE verifier of a native app) for the verified identity.
|
|
196
|
+
*/
|
|
197
|
+
declare function usersIdentityProvider({ baseUrl, appUrl, fetch }: UsersFederationOptions): IdentityProvider;
|
|
198
|
+
|
|
199
|
+
export { ExternalIdentity, FEDERATED_REFUSAL, type FederatedAccounts, type FederatedRefusal, type FederatedSignIn, type FederatedSignInDeps, type FederatedSignInResult, type Fetcher, IdentityLinkStore, IdentityProvider, type Invitation, type Member, ROLES_CODE, type RoleModel, type Roles, type RolesCode, type RolesDeps, RolesError, type RolesQuery, type UsersFederationOptions, accountsMigration, can, createFederatedSignIn, createRoles, defineRoles, parseExternalIdentity, rolesMigration, usersIdentityProvider };
|