@krizaka/auth 0.0.0-stage → 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 +201 -0
- package/README.md +13 -2
- package/dist/index.d.ts +114 -0
- package/dist/index.js +159 -0
- package/dist/index.js.map +1 -0
- package/package.json +58 -3
package/LICENSE
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright [yyyy] [name of copyright owner]
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
package/README.md
CHANGED
|
@@ -1,3 +1,14 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @krizaka/auth
|
|
2
2
|
|
|
3
|
-
|
|
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); 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
|
+
|
|
5
|
+
```ts
|
|
6
|
+
import { accountsMigration, postgresAccounts } from "@krizaka/auth";
|
|
7
|
+
|
|
8
|
+
await db.query(accountsMigration({ backfillVerified: true })); // once, in your migrations (idempotent)
|
|
9
|
+
const accounts = postgresAccounts({ query, mail, baseUrl: "https://www.akinaza.com", product: "Akinaza", tokenPrefix: "ae", passwords: { hash, verify }, tokenHash });
|
|
10
|
+
await accounts.updateProfile(id, { name: "Éric", theme: "dark" });
|
|
11
|
+
await accounts.sessions(id, new Date(), currentSessionId);
|
|
12
|
+
```
|
|
13
|
+
|
|
14
|
+
The product keeps what is its own: its session cookie and token hashing (`tokenHash`), its password hashing, its mailer, its rate limits and its HTTP answers (`AccountError` carries a status and a stable code). Time is passed in (`now`); nothing here reads the clock.
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* What the account adapter needs from a product's database, safe to run on a database that already has `accounts` and `sessions`:
|
|
3
|
+
* a display name, a theme, an avatar seed, the verified-address flag, and the table of e-mail changes (a link mailed to the NEW
|
|
4
|
+
* address). `accounts` needs `id`, `email`, `locale`, `password_hash`; `sessions` needs `account_id`, `created_at`, `expires_at`, `ip`, `user_agent`.
|
|
5
|
+
* `backfillVerified`: for accounts that exist already, treat the address as verified (invitation-only products).
|
|
6
|
+
*/
|
|
7
|
+
declare function accountsMigration(options?: {
|
|
8
|
+
backfillVerified?: boolean;
|
|
9
|
+
}): string;
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* The account PORT (ADR-0008 of Yomizaka, now shared). A product's account — name, language, theme, avatar, e-mail change with
|
|
13
|
+
* verification, password, sessions, export, deletion — behind one interface. Every product keeps its OWN accounts: no central
|
|
14
|
+
* service, no runtime dependency between products.
|
|
15
|
+
*/
|
|
16
|
+
type Theme = "light" | "dark" | "system";
|
|
17
|
+
interface AccountProfile {
|
|
18
|
+
id: string;
|
|
19
|
+
email: string;
|
|
20
|
+
name: string | null;
|
|
21
|
+
locale: "en" | "fr";
|
|
22
|
+
/** The theme the person chose; null = follow the device. */
|
|
23
|
+
theme: Theme | null;
|
|
24
|
+
/** A seed of the default avatars (the UI draws it); null = derived from the e-mail address. */
|
|
25
|
+
avatarSeed: string | null;
|
|
26
|
+
emailVerified: boolean;
|
|
27
|
+
/** An address awaiting its verification link, if the person asked to change it. */
|
|
28
|
+
pendingEmail: string | null;
|
|
29
|
+
}
|
|
30
|
+
interface ProfilePatch {
|
|
31
|
+
name?: string | null;
|
|
32
|
+
locale?: "en" | "fr";
|
|
33
|
+
theme?: Theme | null;
|
|
34
|
+
avatarSeed?: string | null;
|
|
35
|
+
}
|
|
36
|
+
/** A sign-in of the person: where from and when. Never the token. */
|
|
37
|
+
interface SessionSummary {
|
|
38
|
+
id: string;
|
|
39
|
+
createdAt: Date;
|
|
40
|
+
expiresAt: Date;
|
|
41
|
+
ip: string | null;
|
|
42
|
+
userAgent: string | null;
|
|
43
|
+
current: boolean;
|
|
44
|
+
}
|
|
45
|
+
interface AccountService {
|
|
46
|
+
profile(accountId: string): Promise<AccountProfile>;
|
|
47
|
+
updateProfile(accountId: string, patch: ProfilePatch): Promise<AccountProfile>;
|
|
48
|
+
/** 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). */
|
|
49
|
+
requestEmailChange(accountId: string, input: {
|
|
50
|
+
newEmail: string;
|
|
51
|
+
password: string;
|
|
52
|
+
}, now: Date): Promise<void>;
|
|
53
|
+
/** Applies the change from the mailed link (single use, expires); the new address is verified by that very act. */
|
|
54
|
+
confirmEmailChange(token: string, now: Date): Promise<"CHANGED" | "INVALID">;
|
|
55
|
+
/** Changes the password (the current one is checked) and signs every other session out; `keepSessionId` stays. */
|
|
56
|
+
changePassword(accountId: string, input: {
|
|
57
|
+
current: string;
|
|
58
|
+
next: string;
|
|
59
|
+
}, keepSessionId?: string): Promise<void>;
|
|
60
|
+
/** Checks the password. Throws `AccountError(403, "WRONG_PASSWORD")`. */
|
|
61
|
+
confirmPassword(accountId: string, password: string): Promise<void>;
|
|
62
|
+
/** The person's live sign-ins, newest first; `currentSessionId` is flagged. */
|
|
63
|
+
sessions(accountId: string, now: Date, currentSessionId?: string): Promise<SessionSummary[]>;
|
|
64
|
+
/** Signs every other session out (and returns how many); `keepSessionId` stays. */
|
|
65
|
+
signOutOthers(accountId: string, keepSessionId: string): Promise<number>;
|
|
66
|
+
/** What the product keeps about the person, as one JSON-able document: the profile, the live sign-ins, and what `extra` adds. */
|
|
67
|
+
exportAccount(accountId: string, now: Date, extra?: () => Promise<Record<string, unknown>>): Promise<Record<string, unknown>>;
|
|
68
|
+
/** Deletes the identity: the account, its sessions and everything that hangs on it (the product erases its own data first). */
|
|
69
|
+
deleteAccount(accountId: string): Promise<void>;
|
|
70
|
+
}
|
|
71
|
+
declare class AccountError extends Error {
|
|
72
|
+
readonly status: number;
|
|
73
|
+
readonly code: string;
|
|
74
|
+
constructor(status: number, code: string, message: string);
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/** A SQL executor: the rows of a statement and its parameters (the product's pool). */
|
|
78
|
+
type Query = <T = Record<string, unknown>>(sql: string, params?: unknown[]) => Promise<T[]>;
|
|
79
|
+
interface Mail {
|
|
80
|
+
to: string;
|
|
81
|
+
/** The language of the mail (the person's). */
|
|
82
|
+
locale: "en" | "fr";
|
|
83
|
+
subject: string;
|
|
84
|
+
text: string;
|
|
85
|
+
}
|
|
86
|
+
interface AccountDeps {
|
|
87
|
+
query: Query;
|
|
88
|
+
mail: (mail: Mail) => Promise<void>;
|
|
89
|
+
/** `https://www.akinaza.com`: the e-mail change link is `<baseUrl>/<locale>/confirm-email?token=…`. */
|
|
90
|
+
baseUrl: string;
|
|
91
|
+
/** The product's name, in the words of the mail (« Akinaza »). */
|
|
92
|
+
product: string;
|
|
93
|
+
/** The product's token prefix, two or three letters (`ye1.` for Yomizaka: `ye`). The tokens are `<prefix>1.<43 base64url>`. */
|
|
94
|
+
tokenPrefix: string;
|
|
95
|
+
passwords: {
|
|
96
|
+
hash: (password: string) => Promise<string>;
|
|
97
|
+
verify: (password: string, stored: string) => Promise<boolean>;
|
|
98
|
+
};
|
|
99
|
+
/** How a token is kept: the product's own keyed hash, the one its sessions use. */
|
|
100
|
+
tokenHash: (token: string) => string;
|
|
101
|
+
/** Test seam: the token to issue. */
|
|
102
|
+
token?: () => string;
|
|
103
|
+
}
|
|
104
|
+
declare const EMAIL_CHANGE_TTL_HOURS = 24;
|
|
105
|
+
declare const emailChangeToken: (prefix: string) => string;
|
|
106
|
+
declare const isEmailChangeToken: (prefix: string, value: string | undefined | null) => value is string;
|
|
107
|
+
declare function emailChangeMail(product: string, locale: "en" | "fr", url: string): {
|
|
108
|
+
subject: string;
|
|
109
|
+
text: string;
|
|
110
|
+
};
|
|
111
|
+
/** The adapter over the product's own PostgreSQL (`accounts`, `sessions`, `email_changes`; see `accountsMigration`). */
|
|
112
|
+
declare function postgresAccounts(deps: AccountDeps): AccountService;
|
|
113
|
+
|
|
114
|
+
export { type AccountDeps, AccountError, type AccountProfile, type AccountService, EMAIL_CHANGE_TTL_HOURS, type Mail, type ProfilePatch, type Query, type SessionSummary, type Theme, accountsMigration, emailChangeMail, emailChangeToken, isEmailChangeToken, postgresAccounts };
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,159 @@
|
|
|
1
|
+
// src/migration.ts
|
|
2
|
+
function accountsMigration(options = {}) {
|
|
3
|
+
return `
|
|
4
|
+
ALTER TABLE accounts ADD COLUMN IF NOT EXISTS name text CHECK (name IS NULL OR char_length(name) <= 80);
|
|
5
|
+
ALTER TABLE accounts ADD COLUMN IF NOT EXISTS avatar_seed text CHECK (avatar_seed IS NULL OR avatar_seed ~ '^[a-z0-9-]{1,40}$');
|
|
6
|
+
ALTER TABLE accounts ADD COLUMN IF NOT EXISTS theme text CHECK (theme IS NULL OR theme IN ('light', 'dark', 'system'));
|
|
7
|
+
ALTER TABLE accounts ADD COLUMN IF NOT EXISTS email_verified_at timestamptz;
|
|
8
|
+
${options.backfillVerified ? "UPDATE accounts SET email_verified_at = created_at WHERE email_verified_at IS NULL;\n" : ""}CREATE TABLE IF NOT EXISTS email_changes (
|
|
9
|
+
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
|
|
10
|
+
account_id uuid NOT NULL REFERENCES accounts(id) ON DELETE CASCADE,
|
|
11
|
+
new_email text NOT NULL CHECK (new_email = lower(new_email)),
|
|
12
|
+
token_hash text NOT NULL UNIQUE,
|
|
13
|
+
created_at timestamptz NOT NULL DEFAULT now(),
|
|
14
|
+
expires_at timestamptz NOT NULL,
|
|
15
|
+
used_at timestamptz
|
|
16
|
+
);
|
|
17
|
+
`;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
// src/port.ts
|
|
21
|
+
var AccountError = class extends Error {
|
|
22
|
+
constructor(status, code, message) {
|
|
23
|
+
super(message);
|
|
24
|
+
this.status = status;
|
|
25
|
+
this.code = code;
|
|
26
|
+
this.name = "AccountError";
|
|
27
|
+
}
|
|
28
|
+
status;
|
|
29
|
+
code;
|
|
30
|
+
};
|
|
31
|
+
|
|
32
|
+
// src/postgres.ts
|
|
33
|
+
import crypto from "crypto";
|
|
34
|
+
import { addHours } from "date-fns";
|
|
35
|
+
var EMAIL_CHANGE_TTL_HOURS = 24;
|
|
36
|
+
var NAME_MAX = 80;
|
|
37
|
+
var PASSWORD_MIN = 12;
|
|
38
|
+
var PASSWORD_MAX = 256;
|
|
39
|
+
var THEMES = ["light", "dark", "system"];
|
|
40
|
+
var emailChangeToken = (prefix) => `${prefix}1.${crypto.randomBytes(32).toString("base64url")}`;
|
|
41
|
+
var isEmailChangeToken = (prefix, value) => !!value && new RegExp(`^${prefix}1\\.[A-Za-z0-9_-]{43}$`).test(value);
|
|
42
|
+
function emailChangeMail(product, locale, url) {
|
|
43
|
+
return locale === "fr" ? { subject: `Confirmez votre nouvelle adresse \u2014 ${product}`, text: `Bonjour,
|
|
44
|
+
|
|
45
|
+
Pour utiliser cette adresse avec votre compte ${product}, confirmez-la en ouvrant ce lien (valide ${EMAIL_CHANGE_TTL_HOURS} h) :
|
|
46
|
+
${url}
|
|
47
|
+
|
|
48
|
+
Si vous n'avez rien demand\xE9, ignorez ce message : rien ne change.
|
|
49
|
+
` } : { subject: `Confirm your new address \u2014 ${product}`, text: `Hello,
|
|
50
|
+
|
|
51
|
+
To use this address with your ${product} account, confirm it by opening this link (valid ${EMAIL_CHANGE_TTL_HOURS} h):
|
|
52
|
+
${url}
|
|
53
|
+
|
|
54
|
+
If you did not ask for this, ignore this message: nothing changes.
|
|
55
|
+
` };
|
|
56
|
+
}
|
|
57
|
+
var looksLikeEmail = (address) => {
|
|
58
|
+
if (address.length > 320 || /\s/.test(address)) return false;
|
|
59
|
+
const at = address.indexOf("@");
|
|
60
|
+
if (at < 1 || at !== address.lastIndexOf("@")) return false;
|
|
61
|
+
const domain = address.slice(at + 1);
|
|
62
|
+
const dot = domain.lastIndexOf(".");
|
|
63
|
+
return dot > 0 && dot < domain.length - 1;
|
|
64
|
+
};
|
|
65
|
+
var cleanName = (raw) => {
|
|
66
|
+
const name = raw.replace(/\s+/g, " ").trim();
|
|
67
|
+
if (name.length > NAME_MAX) throw new AccountError(400, "BAD_REQUEST", `A name is at most ${NAME_MAX} characters`);
|
|
68
|
+
return name;
|
|
69
|
+
};
|
|
70
|
+
function postgresAccounts(deps) {
|
|
71
|
+
const { query } = deps;
|
|
72
|
+
const wrong = () => new AccountError(403, "WRONG_PASSWORD", "The password is not right");
|
|
73
|
+
async function profileOf(id) {
|
|
74
|
+
const [row] = await query(
|
|
75
|
+
`SELECT a.id, a.email, a.name, a.locale, a.theme, a.avatar_seed, a.email_verified_at,
|
|
76
|
+
(SELECT c.new_email FROM email_changes c WHERE c.account_id = a.id AND c.used_at IS NULL AND c.expires_at > now() ORDER BY c.created_at DESC LIMIT 1) AS pending
|
|
77
|
+
FROM accounts a WHERE a.id = $1`,
|
|
78
|
+
[id]
|
|
79
|
+
);
|
|
80
|
+
if (!row) throw new AccountError(404, "NOT_FOUND", "No such account");
|
|
81
|
+
return { id: row.id, email: row.email, name: row.name, locale: row.locale, theme: row.theme, avatarSeed: row.avatar_seed, emailVerified: !!row.email_verified_at, pendingEmail: row.pending };
|
|
82
|
+
}
|
|
83
|
+
async function confirmPassword(id, password) {
|
|
84
|
+
const [row] = await query("SELECT password_hash FROM accounts WHERE id = $1", [id]);
|
|
85
|
+
if (!row?.password_hash || password.length > PASSWORD_MAX || !await deps.passwords.verify(password, row.password_hash)) throw wrong();
|
|
86
|
+
}
|
|
87
|
+
return {
|
|
88
|
+
profile: profileOf,
|
|
89
|
+
async updateProfile(id, patch) {
|
|
90
|
+
const name = patch.name === void 0 ? void 0 : patch.name === null ? null : cleanName(patch.name);
|
|
91
|
+
if (patch.avatarSeed && !/^[a-z0-9-]{1,40}$/.test(patch.avatarSeed)) throw new AccountError(400, "BAD_REQUEST", "Not an avatar");
|
|
92
|
+
if (patch.theme && !THEMES.includes(patch.theme)) throw new AccountError(400, "BAD_REQUEST", "Not a theme");
|
|
93
|
+
await query(
|
|
94
|
+
`UPDATE accounts SET name = CASE WHEN $2::boolean THEN $3 ELSE name END, locale = COALESCE($4, locale),
|
|
95
|
+
avatar_seed = CASE WHEN $5::boolean THEN $6 ELSE avatar_seed END, theme = CASE WHEN $7::boolean THEN $8 ELSE theme END WHERE id = $1`,
|
|
96
|
+
[id, name !== void 0, name === "" ? null : name ?? null, patch.locale ?? null, patch.avatarSeed !== void 0, patch.avatarSeed ?? null, patch.theme !== void 0, patch.theme ?? null]
|
|
97
|
+
);
|
|
98
|
+
return profileOf(id);
|
|
99
|
+
},
|
|
100
|
+
async requestEmailChange(id, input, now) {
|
|
101
|
+
await confirmPassword(id, input.password);
|
|
102
|
+
const address = input.newEmail.trim().toLowerCase();
|
|
103
|
+
if (!looksLikeEmail(address)) throw new AccountError(400, "BAD_REQUEST", "Not an e-mail address");
|
|
104
|
+
const [taken] = await query("SELECT 1 FROM accounts WHERE email = $1", [address]);
|
|
105
|
+
if (taken) return;
|
|
106
|
+
const profile = await profileOf(id);
|
|
107
|
+
await query("UPDATE email_changes SET used_at = $2 WHERE account_id = $1 AND used_at IS NULL", [id, now]);
|
|
108
|
+
const token = (deps.token ?? (() => emailChangeToken(deps.tokenPrefix)))();
|
|
109
|
+
await query("INSERT INTO email_changes (account_id, new_email, token_hash, expires_at) VALUES ($1, $2, $3, $4)", [id, address, deps.tokenHash(token), addHours(now, EMAIL_CHANGE_TTL_HOURS)]);
|
|
110
|
+
const url = `${deps.baseUrl.replace(/\/$/, "")}/${profile.locale}/confirm-email?token=${encodeURIComponent(token)}`;
|
|
111
|
+
await deps.mail({ to: address, locale: profile.locale, ...emailChangeMail(deps.product, profile.locale, url) });
|
|
112
|
+
},
|
|
113
|
+
async confirmEmailChange(token, now) {
|
|
114
|
+
if (!isEmailChangeToken(deps.tokenPrefix, token)) return "INVALID";
|
|
115
|
+
const [row] = await query("UPDATE email_changes SET used_at = $2 WHERE token_hash = $1 AND used_at IS NULL AND expires_at > $2 RETURNING account_id, new_email", [deps.tokenHash(token), now]);
|
|
116
|
+
if (!row) return "INVALID";
|
|
117
|
+
try {
|
|
118
|
+
await query("UPDATE accounts SET email = $2, email_verified_at = $3 WHERE id = $1", [row.account_id, row.new_email, now]);
|
|
119
|
+
} catch {
|
|
120
|
+
return "INVALID";
|
|
121
|
+
}
|
|
122
|
+
return "CHANGED";
|
|
123
|
+
},
|
|
124
|
+
async changePassword(id, input, keepSessionId) {
|
|
125
|
+
await confirmPassword(id, input.current);
|
|
126
|
+
if (input.next.length < PASSWORD_MIN) throw new AccountError(400, "PASSWORD_TOO_SHORT", `At least ${PASSWORD_MIN} characters`);
|
|
127
|
+
if (input.next.length > PASSWORD_MAX) throw new AccountError(400, "PASSWORD_TOO_LONG", `At most ${PASSWORD_MAX} characters`);
|
|
128
|
+
await query("UPDATE accounts SET password_hash = $2 WHERE id = $1", [id, await deps.passwords.hash(input.next)]);
|
|
129
|
+
await query("DELETE FROM sessions WHERE account_id = $1 AND ($2::uuid IS NULL OR id <> $2::uuid)", [id, keepSessionId ?? null]);
|
|
130
|
+
},
|
|
131
|
+
confirmPassword,
|
|
132
|
+
async sessions(id, now, currentSessionId) {
|
|
133
|
+
const rows = await query("SELECT id, created_at, expires_at, ip, user_agent FROM sessions WHERE account_id = $1 AND expires_at > $2 ORDER BY created_at DESC", [id, now]);
|
|
134
|
+
return rows.map((r) => ({ id: r.id, createdAt: r.created_at, expiresAt: r.expires_at, ip: r.ip, userAgent: r.user_agent, current: r.id === currentSessionId }));
|
|
135
|
+
},
|
|
136
|
+
async signOutOthers(id, keepSessionId) {
|
|
137
|
+
return (await query("DELETE FROM sessions WHERE account_id = $1 AND id <> $2::uuid RETURNING id", [id, keepSessionId])).length;
|
|
138
|
+
},
|
|
139
|
+
async exportAccount(id, now, extra) {
|
|
140
|
+
const profile = await profileOf(id);
|
|
141
|
+
const live = await this.sessions(id, now);
|
|
142
|
+
return { exportedAt: now.toISOString(), account: profile, sessions: live.map(({ current: _current, ...s }) => s), ...extra ? await extra() : {} };
|
|
143
|
+
},
|
|
144
|
+
async deleteAccount(id) {
|
|
145
|
+
const rows = await query("DELETE FROM accounts WHERE id = $1 RETURNING id", [id]);
|
|
146
|
+
if (!rows.length) throw new AccountError(404, "NOT_FOUND", "No such account");
|
|
147
|
+
}
|
|
148
|
+
};
|
|
149
|
+
}
|
|
150
|
+
export {
|
|
151
|
+
AccountError,
|
|
152
|
+
EMAIL_CHANGE_TTL_HOURS,
|
|
153
|
+
accountsMigration,
|
|
154
|
+
emailChangeMail,
|
|
155
|
+
emailChangeToken,
|
|
156
|
+
isEmailChangeToken,
|
|
157
|
+
postgresAccounts
|
|
158
|
+
};
|
|
159
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/migration.ts","../src/port.ts","../src/postgres.ts"],"sourcesContent":["/**\n * What the account adapter needs from a product's database, safe to run on a database that already has `accounts` and `sessions`:\n * a display name, a theme, an avatar seed, the verified-address flag, and the table of e-mail changes (a link mailed to the NEW\n * address). `accounts` needs `id`, `email`, `locale`, `password_hash`; `sessions` needs `account_id`, `created_at`, `expires_at`, `ip`, `user_agent`.\n * `backfillVerified`: for accounts that exist already, treat the address as verified (invitation-only products).\n */\nexport function accountsMigration(options: { backfillVerified?: boolean } = {}): string {\n return `\nALTER TABLE accounts ADD COLUMN IF NOT EXISTS name text CHECK (name IS NULL OR char_length(name) <= 80);\nALTER TABLE accounts ADD COLUMN IF NOT EXISTS avatar_seed text CHECK (avatar_seed IS NULL OR avatar_seed ~ '^[a-z0-9-]{1,40}$');\nALTER TABLE accounts ADD COLUMN IF NOT EXISTS theme text CHECK (theme IS NULL OR theme IN ('light', 'dark', 'system'));\nALTER TABLE accounts ADD COLUMN IF NOT EXISTS email_verified_at timestamptz;\n${options.backfillVerified ? \"UPDATE accounts SET email_verified_at = created_at WHERE email_verified_at IS NULL;\\n\" : \"\"}CREATE TABLE IF NOT EXISTS email_changes (\n id uuid PRIMARY KEY DEFAULT gen_random_uuid(),\n account_id uuid NOT NULL REFERENCES accounts(id) ON DELETE CASCADE,\n new_email text NOT NULL CHECK (new_email = lower(new_email)),\n token_hash text NOT NULL UNIQUE,\n created_at timestamptz NOT NULL DEFAULT now(),\n expires_at timestamptz NOT NULL,\n used_at timestamptz\n);\n`;\n}\n","/**\n * The account PORT (ADR-0008 of Yomizaka, now shared). A product's account — name, language, theme, avatar, e-mail change with\n * verification, password, sessions, export, deletion — behind one interface. Every product keeps its OWN accounts: no central\n * service, no runtime dependency between products.\n */\nexport type Theme = \"light\" | \"dark\" | \"system\";\n\nexport interface AccountProfile {\n id: string;\n email: string;\n name: string | null;\n locale: \"en\" | \"fr\";\n /** The theme the person chose; null = follow the device. */\n theme: Theme | null;\n /** A seed of the default avatars (the UI draws it); null = derived from the e-mail address. */\n avatarSeed: string | null;\n emailVerified: boolean;\n /** An address awaiting its verification link, if the person asked to change it. */\n pendingEmail: string | null;\n}\n\nexport interface ProfilePatch {\n name?: string | null;\n locale?: \"en\" | \"fr\";\n theme?: Theme | null;\n avatarSeed?: string | null;\n}\n\n/** A sign-in of the person: where from and when. Never the token. */\nexport interface SessionSummary {\n id: string;\n createdAt: Date;\n expiresAt: Date;\n ip: string | null;\n userAgent: string | null;\n current: boolean;\n}\n\nexport interface AccountService {\n profile(accountId: string): Promise<AccountProfile>;\n updateProfile(accountId: string, patch: ProfilePatch): Promise<AccountProfile>;\n /** 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). */\n requestEmailChange(accountId: string, input: { newEmail: string; password: string }, now: Date): Promise<void>;\n /** Applies the change from the mailed link (single use, expires); the new address is verified by that very act. */\n confirmEmailChange(token: string, now: Date): Promise<\"CHANGED\" | \"INVALID\">;\n /** Changes the password (the current one is checked) and signs every other session out; `keepSessionId` stays. */\n changePassword(accountId: string, input: { current: string; next: string }, keepSessionId?: string): Promise<void>;\n /** Checks the password. Throws `AccountError(403, \"WRONG_PASSWORD\")`. */\n confirmPassword(accountId: string, password: string): Promise<void>;\n /** The person's live sign-ins, newest first; `currentSessionId` is flagged. */\n sessions(accountId: string, now: Date, currentSessionId?: string): Promise<SessionSummary[]>;\n /** Signs every other session out (and returns how many); `keepSessionId` stays. */\n signOutOthers(accountId: string, keepSessionId: string): Promise<number>;\n /** What the product keeps about the person, as one JSON-able document: the profile, the live sign-ins, and what `extra` adds. */\n exportAccount(accountId: string, now: Date, extra?: () => Promise<Record<string, unknown>>): Promise<Record<string, unknown>>;\n /** Deletes the identity: the account, its sessions and everything that hangs on it (the product erases its own data first). */\n deleteAccount(accountId: string): Promise<void>;\n}\n\nexport class AccountError extends Error {\n constructor(\n readonly status: number,\n readonly code: string,\n message: string,\n ) {\n super(message);\n this.name = \"AccountError\";\n }\n}\n","import crypto from \"node:crypto\";\n\nimport { addHours } from \"date-fns\";\n\nimport { AccountError, type AccountProfile, type AccountService, type ProfilePatch, type SessionSummary, type Theme } from \"./port\";\n\n/** A SQL executor: the rows of a statement and its parameters (the product's pool). */\nexport type Query = <T = Record<string, unknown>>(sql: string, params?: unknown[]) => Promise<T[]>;\n\nexport interface Mail {\n to: string;\n /** The language of the mail (the person's). */\n locale: \"en\" | \"fr\";\n subject: string;\n text: string;\n}\n\nexport interface AccountDeps {\n query: Query;\n mail: (mail: Mail) => Promise<void>;\n /** `https://www.akinaza.com`: the e-mail change link is `<baseUrl>/<locale>/confirm-email?token=…`. */\n baseUrl: string;\n /** The product's name, in the words of the mail (« Akinaza »). */\n product: string;\n /** The product's token prefix, two or three letters (`ye1.` for Yomizaka: `ye`). The tokens are `<prefix>1.<43 base64url>`. */\n tokenPrefix: string;\n passwords: { hash: (password: string) => Promise<string>; verify: (password: string, stored: string) => Promise<boolean> };\n /** How a token is kept: the product's own keyed hash, the one its sessions use. */\n tokenHash: (token: string) => string;\n /** Test seam: the token to issue. */\n token?: () => string;\n}\n\n// @fixed: the lifetime of an e-mail change link, a security parameter\nexport const EMAIL_CHANGE_TTL_HOURS = 24;\nconst NAME_MAX = 80;\nconst PASSWORD_MIN = 12;\nconst PASSWORD_MAX = 256;\nconst THEMES: readonly Theme[] = [\"light\", \"dark\", \"system\"];\n\nexport const emailChangeToken = (prefix: string) => `${prefix}1.${crypto.randomBytes(32).toString(\"base64url\")}`;\nexport const isEmailChangeToken = (prefix: string, value: string | undefined | null): value is string => !!value && new RegExp(`^${prefix}1\\\\.[A-Za-z0-9_-]{43}$`).test(value);\n\nexport function emailChangeMail(product: string, locale: \"en\" | \"fr\", url: string) {\n return locale === \"fr\"\n ? { subject: `Confirmez votre nouvelle adresse — ${product}`, text: `Bonjour,\\n\\nPour utiliser cette adresse avec votre compte ${product}, confirmez-la en ouvrant ce lien (valide ${EMAIL_CHANGE_TTL_HOURS} h) :\\n${url}\\n\\nSi vous n'avez rien demandé, ignorez ce message : rien ne change.\\n` }\n : { subject: `Confirm your new address — ${product}`, text: `Hello,\\n\\nTo use this address with your ${product} account, confirm it by opening this link (valid ${EMAIL_CHANGE_TTL_HOURS} h):\\n${url}\\n\\nIf you did not ask for this, ignore this message: nothing changes.\\n` };\n}\n\n/** One « @ », something on each side, a dot inside the domain, no space — checked without a backtracking pattern. */\nconst looksLikeEmail = (address: string): boolean => {\n if (address.length > 320 || /\\s/.test(address)) return false;\n const at = address.indexOf(\"@\");\n if (at < 1 || at !== address.lastIndexOf(\"@\")) return false;\n const domain = address.slice(at + 1);\n const dot = domain.lastIndexOf(\".\");\n return dot > 0 && dot < domain.length - 1;\n};\n\nconst cleanName = (raw: string): string => {\n const name = raw.replace(/\\s+/g, \" \").trim();\n if (name.length > NAME_MAX) throw new AccountError(400, \"BAD_REQUEST\", `A name is at most ${NAME_MAX} characters`);\n return name;\n};\n\ninterface ProfileRow {\n id: string;\n email: string;\n name: string | null;\n locale: \"en\" | \"fr\";\n theme: Theme | null;\n avatar_seed: string | null;\n email_verified_at: Date | null;\n pending: string | null;\n}\n\n/** The adapter over the product's own PostgreSQL (`accounts`, `sessions`, `email_changes`; see `accountsMigration`). */\nexport function postgresAccounts(deps: AccountDeps): AccountService {\n const { query } = deps;\n const wrong = () => new AccountError(403, \"WRONG_PASSWORD\", \"The password is not right\");\n\n async function profileOf(id: string): Promise<AccountProfile> {\n const [row] = await query<ProfileRow>(\n `SELECT a.id, a.email, a.name, a.locale, a.theme, a.avatar_seed, a.email_verified_at,\n (SELECT c.new_email FROM email_changes c WHERE c.account_id = a.id AND c.used_at IS NULL AND c.expires_at > now() ORDER BY c.created_at DESC LIMIT 1) AS pending\n FROM accounts a WHERE a.id = $1`,\n [id],\n );\n if (!row) throw new AccountError(404, \"NOT_FOUND\", \"No such account\");\n return { id: row.id, email: row.email, name: row.name, locale: row.locale, theme: row.theme, avatarSeed: row.avatar_seed, emailVerified: !!row.email_verified_at, pendingEmail: row.pending };\n }\n\n async function confirmPassword(id: string, password: string): Promise<void> {\n const [row] = await query<{ password_hash: string | null }>(\"SELECT password_hash FROM accounts WHERE id = $1\", [id]);\n if (!row?.password_hash || password.length > PASSWORD_MAX || !(await deps.passwords.verify(password, row.password_hash))) throw wrong();\n }\n\n return {\n profile: profileOf,\n\n async updateProfile(id, patch: ProfilePatch) {\n const name = patch.name === undefined ? undefined : patch.name === null ? null : cleanName(patch.name);\n if (patch.avatarSeed && !/^[a-z0-9-]{1,40}$/.test(patch.avatarSeed)) throw new AccountError(400, \"BAD_REQUEST\", \"Not an avatar\");\n if (patch.theme && !THEMES.includes(patch.theme)) throw new AccountError(400, \"BAD_REQUEST\", \"Not a theme\");\n await query(\n `UPDATE accounts SET name = CASE WHEN $2::boolean THEN $3 ELSE name END, locale = COALESCE($4, locale),\n avatar_seed = CASE WHEN $5::boolean THEN $6 ELSE avatar_seed END, theme = CASE WHEN $7::boolean THEN $8 ELSE theme END WHERE id = $1`,\n [id, name !== undefined, name === \"\" ? null : (name ?? null), patch.locale ?? null, patch.avatarSeed !== undefined, patch.avatarSeed ?? null, patch.theme !== undefined, patch.theme ?? null],\n );\n return profileOf(id);\n },\n\n async requestEmailChange(id, input, now) {\n await confirmPassword(id, input.password);\n const address = input.newEmail.trim().toLowerCase();\n if (!looksLikeEmail(address)) throw new AccountError(400, \"BAD_REQUEST\", \"Not an e-mail address\");\n const [taken] = await query(\"SELECT 1 FROM accounts WHERE email = $1\", [address]);\n if (taken) return; // the same answer, no mail: the address is not disclosed\n const profile = await profileOf(id);\n await query(\"UPDATE email_changes SET used_at = $2 WHERE account_id = $1 AND used_at IS NULL\", [id, now]);\n const token = (deps.token ?? (() => emailChangeToken(deps.tokenPrefix)))();\n await query(\"INSERT INTO email_changes (account_id, new_email, token_hash, expires_at) VALUES ($1, $2, $3, $4)\", [id, address, deps.tokenHash(token), addHours(now, EMAIL_CHANGE_TTL_HOURS)]);\n const url = `${deps.baseUrl.replace(/\\/$/, \"\")}/${profile.locale}/confirm-email?token=${encodeURIComponent(token)}`;\n await deps.mail({ to: address, locale: profile.locale, ...emailChangeMail(deps.product, profile.locale, url) });\n },\n\n async confirmEmailChange(token, now) {\n if (!isEmailChangeToken(deps.tokenPrefix, token)) return \"INVALID\";\n const [row] = await query<{ account_id: string; new_email: string }>(\"UPDATE email_changes SET used_at = $2 WHERE token_hash = $1 AND used_at IS NULL AND expires_at > $2 RETURNING account_id, new_email\", [deps.tokenHash(token), now]);\n if (!row) return \"INVALID\";\n try {\n await query(\"UPDATE accounts SET email = $2, email_verified_at = $3 WHERE id = $1\", [row.account_id, row.new_email, now]);\n } catch {\n return \"INVALID\"; // taken in the meantime\n }\n return \"CHANGED\";\n },\n\n async changePassword(id, input, keepSessionId) {\n await confirmPassword(id, input.current);\n if (input.next.length < PASSWORD_MIN) throw new AccountError(400, \"PASSWORD_TOO_SHORT\", `At least ${PASSWORD_MIN} characters`);\n if (input.next.length > PASSWORD_MAX) throw new AccountError(400, \"PASSWORD_TOO_LONG\", `At most ${PASSWORD_MAX} characters`);\n await query(\"UPDATE accounts SET password_hash = $2 WHERE id = $1\", [id, await deps.passwords.hash(input.next)]);\n await query(\"DELETE FROM sessions WHERE account_id = $1 AND ($2::uuid IS NULL OR id <> $2::uuid)\", [id, keepSessionId ?? null]);\n },\n\n confirmPassword,\n\n async sessions(id, now, currentSessionId) {\n const rows = await query<{ id: string; created_at: Date; expires_at: Date; ip: string | null; user_agent: string | null }>(\"SELECT id, created_at, expires_at, ip, user_agent FROM sessions WHERE account_id = $1 AND expires_at > $2 ORDER BY created_at DESC\", [id, now]);\n return rows.map((r): SessionSummary => ({ id: r.id, createdAt: r.created_at, expiresAt: r.expires_at, ip: r.ip, userAgent: r.user_agent, current: r.id === currentSessionId }));\n },\n\n async signOutOthers(id, keepSessionId) {\n return (await query(\"DELETE FROM sessions WHERE account_id = $1 AND id <> $2::uuid RETURNING id\", [id, keepSessionId])).length;\n },\n\n async exportAccount(id, now, extra) {\n const profile = await profileOf(id);\n const live = await this.sessions(id, now);\n return { exportedAt: now.toISOString(), account: profile, sessions: live.map(({ current: _current, ...s }) => s), ...(extra ? await extra() : {}) };\n },\n\n async deleteAccount(id) {\n const rows = await query(\"DELETE FROM accounts WHERE id = $1 RETURNING id\", [id]);\n if (!rows.length) throw new AccountError(404, \"NOT_FOUND\", \"No such account\");\n },\n };\n}\n"],"mappings":";AAMO,SAAS,kBAAkB,UAA0C,CAAC,GAAW;AACtF,SAAO;AAAA;AAAA;AAAA;AAAA;AAAA,EAKP,QAAQ,mBAAmB,0FAA0F,EAAE;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAUzH;;;ACqCO,IAAM,eAAN,cAA2B,MAAM;AAAA,EACtC,YACW,QACA,MACT,SACA;AAC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AI;AACtB,YAAM,OAAO,MAAM,MAAM,mDAAmD,CAAC,EAAE,CAAC;AAChF,UAAI,CAAC,KAAK,OAAQ,OAAM,IAAI,aAAa,KAAK,aAAa,iBAAiB;AAAA,IAC9E;AAAA,EACF;AACF;","names":[]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,61 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@krizaka/auth",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
3
|
+
"version": "0.2.0",
|
|
4
|
+
"description": "The account of a Krizaka product — name, language, theme, avatar, e-mail change by link with the verified flag, password, sessions with sign-out of the others, data export, deletion — behind a port, with a PostgreSQL adapter and its migration. Each product keeps its own accounts; no framework, no wall clock, no mail vendor.",
|
|
5
|
+
"keywords": [
|
|
6
|
+
"krizaka",
|
|
7
|
+
"auth",
|
|
8
|
+
"account",
|
|
9
|
+
"profile",
|
|
10
|
+
"sessions"
|
|
11
|
+
],
|
|
12
|
+
"homepage": "https://github.com/krizaka/krizaka-ts/tree/main/packages/auth",
|
|
13
|
+
"bugs": "https://github.com/krizaka/krizaka-ts/issues",
|
|
14
|
+
"repository": {
|
|
15
|
+
"type": "git",
|
|
16
|
+
"url": "git+https://github.com/krizaka/krizaka-ts.git",
|
|
17
|
+
"directory": "packages/auth"
|
|
18
|
+
},
|
|
19
|
+
"license": "Apache-2.0",
|
|
20
|
+
"author": "Krizaka (https://www.krizaka.com)",
|
|
21
|
+
"type": "module",
|
|
22
|
+
"main": "./dist/index.js",
|
|
23
|
+
"module": "./dist/index.js",
|
|
24
|
+
"types": "./dist/index.d.ts",
|
|
25
|
+
"exports": {
|
|
26
|
+
".": {
|
|
27
|
+
"types": "./dist/index.d.ts",
|
|
28
|
+
"import": "./dist/index.js"
|
|
29
|
+
},
|
|
30
|
+
"./package.json": "./package.json"
|
|
31
|
+
},
|
|
32
|
+
"files": [
|
|
33
|
+
"dist",
|
|
34
|
+
"README.md",
|
|
35
|
+
"LICENSE"
|
|
36
|
+
],
|
|
37
|
+
"sideEffects": false,
|
|
38
|
+
"engines": {
|
|
39
|
+
"node": ">=22"
|
|
40
|
+
},
|
|
41
|
+
"dependencies": {
|
|
42
|
+
"date-fns": "^4.4.0"
|
|
43
|
+
},
|
|
44
|
+
"devDependencies": {
|
|
45
|
+
"@krizaka/config": "^0.7.0",
|
|
46
|
+
"@types/node": "^22.10.0",
|
|
47
|
+
"@types/pg": "^8.23.1",
|
|
48
|
+
"eslint": "^9.39.0",
|
|
49
|
+
"pg": "^8.23.1",
|
|
50
|
+
"tsup": "^8.5.0",
|
|
51
|
+
"typescript": "^5.9.3",
|
|
52
|
+
"vitest": "^4.1.11"
|
|
53
|
+
},
|
|
54
|
+
"scripts": {
|
|
55
|
+
"build": "node -e \"require('node:fs').rmSync('dist',{recursive:true,force:true})\" && tsup",
|
|
56
|
+
"lint": "eslint . --max-warnings 0 && tsc --noEmit",
|
|
57
|
+
"typecheck": "tsc --noEmit",
|
|
58
|
+
"test": "vitest run",
|
|
59
|
+
"check": "pnpm run lint && pnpm run test && pnpm run build"
|
|
60
|
+
}
|
|
6
61
|
}
|