@sharadox/account-web-library 0.1.0-development.3 → 0.1.0-development.9

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.
Files changed (94) hide show
  1. package/README.md +75 -3
  2. package/distribution/account-database/type.d.ts +73 -0
  3. package/distribution/account-database/type.d.ts.map +1 -0
  4. package/distribution/account-database/type.js +2 -0
  5. package/distribution/account-database/type.js.map +1 -0
  6. package/distribution/account-migration/index.d.ts +18 -0
  7. package/distribution/account-migration/index.d.ts.map +1 -0
  8. package/distribution/account-migration/index.js +122 -0
  9. package/distribution/account-migration/index.js.map +1 -0
  10. package/distribution/audit-event/index.d.ts +12 -0
  11. package/distribution/audit-event/index.d.ts.map +1 -0
  12. package/distribution/audit-event/index.js +25 -0
  13. package/distribution/audit-event/index.js.map +1 -0
  14. package/distribution/audit-event/type.d.ts +15 -0
  15. package/distribution/audit-event/type.d.ts.map +1 -0
  16. package/distribution/audit-event/type.js +2 -0
  17. package/distribution/audit-event/type.js.map +1 -0
  18. package/distribution/code-request/index.d.ts +16 -0
  19. package/distribution/code-request/index.d.ts.map +1 -0
  20. package/distribution/code-request/index.js +52 -0
  21. package/distribution/code-request/index.js.map +1 -0
  22. package/distribution/code-request/type.d.ts +25 -0
  23. package/distribution/code-request/type.d.ts.map +1 -0
  24. package/distribution/code-request/type.js +2 -0
  25. package/distribution/code-request/type.js.map +1 -0
  26. package/distribution/code-request-prune/index.d.ts +13 -0
  27. package/distribution/code-request-prune/index.d.ts.map +1 -0
  28. package/distribution/code-request-prune/index.js +12 -0
  29. package/distribution/code-request-prune/index.js.map +1 -0
  30. package/distribution/code-verification/index.d.ts +14 -0
  31. package/distribution/code-verification/index.d.ts.map +1 -0
  32. package/distribution/code-verification/index.js +43 -0
  33. package/distribution/code-verification/index.js.map +1 -0
  34. package/distribution/code-verification/type.d.ts +22 -0
  35. package/distribution/code-verification/type.d.ts.map +1 -0
  36. package/distribution/code-verification/type.js +2 -0
  37. package/distribution/code-verification/type.js.map +1 -0
  38. package/distribution/contact-addition/index.d.ts +13 -0
  39. package/distribution/contact-addition/index.d.ts.map +1 -0
  40. package/distribution/contact-addition/index.js +48 -0
  41. package/distribution/contact-addition/index.js.map +1 -0
  42. package/distribution/contact-addition/type.d.ts +15 -0
  43. package/distribution/contact-addition/type.d.ts.map +1 -0
  44. package/distribution/contact-addition/type.js +2 -0
  45. package/distribution/contact-addition/type.js.map +1 -0
  46. package/distribution/contact-kind/index.d.ts +12 -0
  47. package/distribution/contact-kind/index.d.ts.map +1 -0
  48. package/distribution/contact-kind/index.js +18 -0
  49. package/distribution/contact-kind/index.js.map +1 -0
  50. package/distribution/contact-kind/type.d.ts +6 -0
  51. package/distribution/contact-kind/type.d.ts.map +1 -0
  52. package/distribution/contact-kind/type.js +2 -0
  53. package/distribution/contact-kind/type.js.map +1 -0
  54. package/distribution/contact-lookup/index.d.ts +16 -0
  55. package/distribution/contact-lookup/index.d.ts.map +1 -0
  56. package/distribution/contact-lookup/index.js +20 -0
  57. package/distribution/contact-lookup/index.js.map +1 -0
  58. package/distribution/contact-removal/index.d.ts +19 -0
  59. package/distribution/contact-removal/index.d.ts.map +1 -0
  60. package/distribution/contact-removal/index.js +35 -0
  61. package/distribution/contact-removal/index.js.map +1 -0
  62. package/distribution/contact-verification/index.d.ts +20 -0
  63. package/distribution/contact-verification/index.d.ts.map +1 -0
  64. package/distribution/contact-verification/index.js +37 -0
  65. package/distribution/contact-verification/index.js.map +1 -0
  66. package/distribution/database-error/index.d.ts +12 -0
  67. package/distribution/database-error/index.d.ts.map +1 -0
  68. package/distribution/database-error/index.js +14 -0
  69. package/distribution/database-error/index.js.map +1 -0
  70. package/distribution/person-account/index.d.ts +14 -0
  71. package/distribution/person-account/index.d.ts.map +1 -0
  72. package/distribution/person-account/index.js +45 -0
  73. package/distribution/person-account/index.js.map +1 -0
  74. package/distribution/person-account/type.d.ts +17 -0
  75. package/distribution/person-account/type.d.ts.map +1 -0
  76. package/distribution/person-account/type.js +2 -0
  77. package/distribution/person-account/type.js.map +1 -0
  78. package/distribution/test-database/index.d.ts +13 -0
  79. package/distribution/test-database/index.d.ts.map +1 -0
  80. package/distribution/test-database/index.js +17 -0
  81. package/distribution/test-database/index.js.map +1 -0
  82. package/distribution/username-availability/index.d.ts +11 -0
  83. package/distribution/username-availability/index.d.ts.map +1 -0
  84. package/distribution/username-availability/index.js +21 -0
  85. package/distribution/username-availability/index.js.map +1 -0
  86. package/distribution/username-change/index.d.ts +15 -0
  87. package/distribution/username-change/index.d.ts.map +1 -0
  88. package/distribution/username-change/index.js +39 -0
  89. package/distribution/username-change/index.js.map +1 -0
  90. package/distribution/username-change/type.d.ts +7 -0
  91. package/distribution/username-change/type.d.ts.map +1 -0
  92. package/distribution/username-change/type.js +2 -0
  93. package/distribution/username-change/type.js.map +1 -0
  94. package/package.json +5 -2
package/README.md CHANGED
@@ -9,9 +9,9 @@ Passwordless accounts for web applications, built on open standards, with no aut
9
9
 
10
10
  One deployment per company. Everything company-specific is configuration.
11
11
 
12
- **Status: 0.1.0, building blocks.** Usernames, one-time codes, TOTP, recovery codes, email contacts, effective
13
- permissions and ban lengths. Accounts, contacts, sessions, storage and the OpenID Connect server come next (see
14
- `CHANGELOG.md`).
12
+ **Status: 0.1.0, in progress.** Building blocks (usernames, one-time codes, TOTP, recovery codes, email contacts,
13
+ effective permissions, ban lengths) and account storage in Postgres (accounts, usernames, contacts, audit log).
14
+ Sign-in codes, sessions and the OpenID Connect server come next (see `CHANGELOG.md`).
15
15
 
16
16
  ## Install
17
17
 
@@ -19,6 +19,22 @@ permissions and ban lengths. Accounts, contacts, sessions, storage and the OpenI
19
19
  pnpm add @sharadox/account-web-library
20
20
  ```
21
21
 
22
+ ## Storage
23
+
24
+ Postgres through Kysely (`@sharadox/database-web-library`). Run `migrateAccount(database)` when the application
25
+ migrates: the tables are tracked in their own table (`account_migration`). Type Kysely with `AccountDatabase`
26
+ (`account-database/type`). The database enforces the rules itself, as the last line behind the code:
27
+
28
+ - ids are UUIDv7;
29
+ - usernames follow the rules and are unique without regard to case;
30
+ - a verified contact belongs to one account only;
31
+ - every person keeps at least one verified sign-in contact, checked when a change commits;
32
+ - agents have an owner (and go with them);
33
+ - the audit log is never changed.
34
+
35
+ Tests: `createTestAccountDatabase()` (`test-database`) gives a migrated Postgres in memory (PGlite, a development
36
+ dependency).
37
+
22
38
  ## API
23
39
 
24
40
  Each export has its own entry point (`@sharadox/account-web-library/<name>`).
@@ -89,6 +105,62 @@ Codes like `7KQM-W3HD-9TXA` (about 59 bits each), from characters that can't be
89
105
  - `normalizeEmail` trims and lowercases, and throws for text that isn't an email address.
90
106
  - `emailLedgerForm` also drops `+tags`, for the banned-contact ledger.
91
107
 
108
+ ### `person-account`: `createPersonAccount(database, { username, contact, now? })`
109
+
110
+ Creates a person with the contact their one-time code just proved, stored verified, and records `account.created`.
111
+ Returns `{ created: true, accountId, contactId }`, or `{ created: false, reason }` with `username-invalid`,
112
+ `username-taken` or `contact-taken`.
113
+
114
+ ### `username-availability`: `usernameAvailability(database, username)` → `available` | `taken` | `invalid`
115
+
116
+ Rate limit it: it tells whether an account exists.
117
+
118
+ ### `username-change`: `changeUsername(database, { accountId, username })`
119
+
120
+ Any time, and the old name is free at once; the audit log keeps `{ from, to }`. Reasons: `username-invalid`,
121
+ `username-taken`, `no-account`.
122
+
123
+ ### `contact-lookup`: `findAccountByContact(database, contact)` → `{ accountId, contactId, signIn }` or undefined
124
+
125
+ Verified contacts only, normalized first.
126
+
127
+ ### `contact-addition`, `contact-verification`, `contact-removal`
128
+
129
+ - `addContact(database, { accountId, contact, now? })` adds it unverified. Reasons: `already-added`,
130
+ `contact-taken`, `no-account`.
131
+ - `verifyContact(database, { accountId, contactId, now? })` once its code came back. Reasons: `no-contact`,
132
+ `contact-taken` (another account verified it first).
133
+ - `removeContact(database, { accountId, contactId })`. Reasons: `no-contact`, `last-sign-in-contact`.
134
+
135
+ Each is recorded in the audit log. Ask for a fresh code first (step-up) and tell the other contacts.
136
+
137
+ ### `code-request`: `requestCode(database, { purpose, contact, accountId?, pepper, length = 8, lifetimeSeconds = 600, now? })` → `{ requestId, code, contact, expiresAt }`
138
+
139
+ Starts a one-time code for `sign-in`, `contact-verification` or `step-up`.
140
+
141
+ - Only an HMAC bound to the purpose and request is stored.
142
+ - A new request replaces the open one for the same contact and purpose.
143
+ - Send the code after answering the request, so timing reveals nothing. Rate limit and cap the sends first
144
+ (`limitRate`, `spendFromCap` from protection-web-library).
145
+
146
+ ### `code-verification`: `verifyCode(database, { requestId, code, purpose, pepper, maximumAttempts = 5, now? })`
147
+
148
+ Returns `{ valid: true, contact, accountId }` (the account that asked, null for sign-in), or `{ valid: false, reason }`
149
+ with `unknown`, `used`, `replaced`, `expired`, `attempts` or `wrong`. The row is locked, so concurrent guesses can't
150
+ pass the limit; after the last attempt even the right code is refused.
151
+
152
+ ### `code-request-prune`: `pruneCodeRequests(database, { before })` → deleted count
153
+
154
+ ### `contact-kind`: `normalizeContact({ kind, value })`, `CONTACT_KINDS`
155
+
156
+ `email` in this version; unknown kinds and invalid values throw.
157
+
158
+ ### `audit-event`: `recordAuditEvent(database, { action, accountId?, actorAccountId?, application?, detail?, now? })` → id
159
+
160
+ Pass the transaction of the change it describes. `detail` holds ids and kinds, never contact values or secrets.
161
+
162
+ ### `database-error`: `databaseError(error)` → `{ code, constraint }` or undefined
163
+
92
164
  ## License
93
165
 
94
166
  Sharadox Open Source License 0.1.0 (see `LICENSE.md`).
@@ -0,0 +1,73 @@
1
+ import type { ColumnType, Generated } from "kysely";
2
+ /** A timestamp the database fills in when not given. */
3
+ type DefaultTime = ColumnType<Date, Date | undefined, Date>;
4
+ /** An application the accounts sign in to (`account` itself, `platform`, `shop`…). */
5
+ export interface ApplicationTable {
6
+ id: string;
7
+ name: string;
8
+ created_at: DefaultTime;
9
+ }
10
+ /** A person, or an agent owned by a person. */
11
+ export interface AccountTable {
12
+ id: string;
13
+ kind: "person" | "agent";
14
+ /** Shown as written; unique without regard to case. */
15
+ username: string;
16
+ /** The person who owns an agent; null for people. */
17
+ owner_id: string | null;
18
+ created_at: DefaultTime;
19
+ last_active_at: DefaultTime;
20
+ }
21
+ /** A way to reach an account (email now; phone and messaging later). */
22
+ export interface ContactTable {
23
+ id: string;
24
+ account_id: string;
25
+ kind: string;
26
+ /** Normalized (see `normalizeContact`). */
27
+ value: string;
28
+ /** When a one-time code proved it; null until then. A verified contact belongs to one account only. */
29
+ verified_at: Date | null;
30
+ /** Whether codes for signing in may be sent to it. */
31
+ sign_in: Generated<boolean>;
32
+ created_at: DefaultTime;
33
+ }
34
+ /** One line of the append-only audit log. */
35
+ export interface AuditEventTable {
36
+ id: string;
37
+ at: DefaultTime;
38
+ /** The account it is about (kept after the account is deleted, as a bare id). */
39
+ account_id: string | null;
40
+ /** Who did it, when not the account itself (an administrator, an agent). */
41
+ actor_account_id: string | null;
42
+ application: string | null;
43
+ action: string;
44
+ detail: ColumnType<Record<string, unknown>, Record<string, unknown> | undefined, never>;
45
+ }
46
+ /** A one-time code sent to a contact, stored only as an HMAC bound to its purpose and request. */
47
+ export interface CodeRequestTable {
48
+ id: string;
49
+ /** `sign-in`, `contact-verification` or `step-up`. */
50
+ purpose: string;
51
+ /** The account asking (step-up, contact verification); null when signing in. */
52
+ account_id: string | null;
53
+ kind: string;
54
+ value: string;
55
+ code_hash: string;
56
+ created_at: Date;
57
+ expires_at: Date;
58
+ attempts: Generated<number>;
59
+ /** When the right code came back. */
60
+ used_at: Date | null;
61
+ /** When a newer request for the same contact and purpose replaced it. */
62
+ voided_at: Date | null;
63
+ }
64
+ /** The tables `migrateAccount` creates, for typing a Kysely instance. */
65
+ export interface AccountDatabase {
66
+ application: ApplicationTable;
67
+ account: AccountTable;
68
+ contact: ContactTable;
69
+ audit_event: AuditEventTable;
70
+ code_request: CodeRequestTable;
71
+ }
72
+ export {};
73
+ //# sourceMappingURL=type.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"type.d.ts","sourceRoot":"","s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MAAM,CAAC;IACf,MAAM,EAAE,UAAU,CAAC,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,SAAS,EAAE,KAAK,CAAC,CAAC;CACzF;AAED,kGAAkG;AAClG,MAAM,WAAW,gBAAgB;IAC/B,EAAE,EAAE,MAAM,CAAC;IACX,sDAAsD;IACtD,OAAO,EAAE,MAAM,CAAC;IAChB,gFAAgF;IAChF,UAAU,EAAE,MAAM,GAAG,IAAI,CAAC;IAC1B,IAAI,EAAE,MAAM,CAAC;IACb,KAAK,EAAE,MAAM,CAAC;IACd,SAAS,EAAE,MAAM,CAAC;IAClB,UAAU,EAAE,IAAI,CAAC;IACjB,UAAU,EAAE,IAAI,CAAC;IACjB,QAAQ,EAAE,SAAS,CAAC,MAAM,CAAC,CAAC;IAC5B,qCAAqC;IACrC,OAAO,EAAE,IAAI,GAAG,IAAI,CAAC;IACrB,yEAAyE;IACzE,SAAS,EAAE,IAAI,GAAG,IAAI,CAAC;CACxB;AAED,yEAAyE;AACzE,MAAM,WAAW,eAAe;IAC9B,WAAW,EAAE,gBAAgB,CAAC;IAC9B,OAAO,EAAE,YAAY,CAAC;IACtB,OAAO,EAAE,YAAY,CAAC;IACtB,WAAW,EAAE,eAAe,CAAC;IAC7B,YAAY,EAAE,gBAAgB,CAAC;CAChC"}
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=type.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"type.js","sourceRoot":"","sources":["../../source/account-database/type.ts"],"names":[],"mappings":""}
@@ -0,0 +1,18 @@
1
+ import type { Kysely } from "kysely";
2
+ import type { Migration } from "@sharadox/database-web-library/migration/type";
3
+ /** The table that records which account migrations a database has applied (apart from the application's own). */
4
+ export declare const ACCOUNT_MIGRATION_TABLE = "account_migration";
5
+ /**
6
+ * The account tables, forward only. The database enforces the rules itself, as the last line behind the code:
7
+ * UUIDv7 ids, username rules and case-insensitive uniqueness, one account per verified contact, agents owned by a
8
+ * person, every person keeping a verified sign-in contact (checked at commit), and an audit log that is never changed.
9
+ */
10
+ export declare const accountMigrations: Migration[];
11
+ /**
12
+ * Creates or updates the account tables, tracked in their own migration table. Returns the names applied.
13
+ *
14
+ * @example
15
+ * await migrateAccount(database);
16
+ */
17
+ export declare function migrateAccount<Schema>(database: Kysely<Schema>): Promise<string[]>;
18
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../source/account-migration/index.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AAErC,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,+CAA+C,CAAC;AAE/E,iHAAiH;AACjH,eAAO,MAAM,uBAAuB,sBAAsB,CAAC;AAE3D;;;;GAIG;AACH,eAAO,MAAM,iBAAiB,EAAE,SAAS,EAuGxC,CAAC;AAEF;;;;;GAKG;AACH,wBAAgB,cAAc,CAAC,MAAM,EAAE,QAAQ,EAAE,MAAM,CAAC,MAAM,CAAC,GAAG,OAAO,CAAC,MAAM,EAAE,CAAC,CAElF"}
@@ -0,0 +1,122 @@
1
+ import { migrate } from "@sharadox/database-web-library/migration";
2
+ /** The table that records which account migrations a database has applied (apart from the application's own). */
3
+ export const ACCOUNT_MIGRATION_TABLE = "account_migration";
4
+ /**
5
+ * The account tables, forward only. The database enforces the rules itself, as the last line behind the code:
6
+ * UUIDv7 ids, username rules and case-insensitive uniqueness, one account per verified contact, agents owned by a
7
+ * person, every person keeping a verified sign-in contact (checked at commit), and an audit log that is never changed.
8
+ */
9
+ export const accountMigrations = [
10
+ {
11
+ name: "0001-application-account-contact-audit",
12
+ sql: `
13
+ create table application (
14
+ id text primary key check (id ~ '^[a-z][a-z0-9]*(-[a-z0-9]+)*$' and length(id) <= 50),
15
+ name text not null,
16
+ created_at timestamptz not null default now()
17
+ );
18
+ insert into application (id, name) values ('account', 'Account');
19
+
20
+ create table account (
21
+ id uuid primary key check (uuid_extract_version(id) = 7),
22
+ kind text not null check (kind in ('person', 'agent')),
23
+ username text not null
24
+ check (length(username) between 1 and 50 and username ~ '^[A-Za-z0-9]+([-_.][A-Za-z0-9]+)*$'),
25
+ owner_id uuid references account (id) on delete cascade,
26
+ created_at timestamptz not null default now(),
27
+ last_active_at timestamptz not null default now(),
28
+ constraint account_owner_check check ((kind = 'agent') = (owner_id is not null))
29
+ );
30
+ create unique index account_username_key on account (lower(username));
31
+ create index account_owner on account (owner_id) where owner_id is not null;
32
+ create index account_last_active_at on account (last_active_at);
33
+
34
+ create table contact (
35
+ id uuid primary key check (uuid_extract_version(id) = 7),
36
+ account_id uuid not null references account (id) on delete cascade,
37
+ kind text not null check (kind ~ '^[a-z][a-z0-9]*(-[a-z0-9]+)*$'),
38
+ value text not null check (length(value) between 1 and 320),
39
+ verified_at timestamptz,
40
+ sign_in boolean not null default true,
41
+ created_at timestamptz not null default now()
42
+ );
43
+ create unique index contact_verified on contact (kind, value) where verified_at is not null;
44
+ create unique index contact_per_account on contact (account_id, kind, value);
45
+
46
+ create function account_require_sign_in_contact(target uuid) returns void
47
+ language plpgsql set search_path = public as $$
48
+ begin
49
+ if exists (select 1 from account where id = target and kind = 'person')
50
+ and not exists (
51
+ select 1 from contact where account_id = target and verified_at is not null and sign_in
52
+ ) then
53
+ raise exception 'a person account needs at least one verified sign-in contact' using errcode = '23514';
54
+ end if;
55
+ end $$;
56
+ create function account_after_insert() returns trigger
57
+ language plpgsql set search_path = public as $$
58
+ begin
59
+ perform account_require_sign_in_contact(new.id);
60
+ return null;
61
+ end $$;
62
+ create function contact_after_change() returns trigger
63
+ language plpgsql set search_path = public as $$
64
+ begin
65
+ perform account_require_sign_in_contact(old.account_id);
66
+ return null;
67
+ end $$;
68
+ create constraint trigger account_sign_in_contact after insert on account
69
+ deferrable initially deferred for each row execute function account_after_insert();
70
+ create constraint trigger contact_sign_in_contact after update or delete on contact
71
+ deferrable initially deferred for each row execute function contact_after_change();
72
+
73
+ create table audit_event (
74
+ id uuid primary key check (uuid_extract_version(id) = 7),
75
+ at timestamptz not null default now(),
76
+ account_id uuid,
77
+ actor_account_id uuid,
78
+ application text,
79
+ action text not null check (length(action) between 1 and 100),
80
+ detail jsonb not null default '{}'
81
+ );
82
+ create index audit_event_account on audit_event (account_id, at);
83
+ create function audit_event_unchangeable() returns trigger
84
+ language plpgsql as $$
85
+ begin
86
+ raise exception 'audit events are never changed';
87
+ end $$;
88
+ create trigger audit_event_unchangeable before update on audit_event
89
+ for each row execute function audit_event_unchangeable();
90
+ `,
91
+ },
92
+ {
93
+ name: "0002-code-request",
94
+ sql: `
95
+ create table code_request (
96
+ id uuid primary key check (uuid_extract_version(id) = 7),
97
+ purpose text not null check (purpose in ('sign-in', 'contact-verification', 'step-up')),
98
+ account_id uuid,
99
+ kind text not null,
100
+ value text not null,
101
+ code_hash text not null,
102
+ created_at timestamptz not null,
103
+ expires_at timestamptz not null,
104
+ attempts integer not null default 0 check (attempts >= 0),
105
+ used_at timestamptz,
106
+ voided_at timestamptz
107
+ );
108
+ create index code_request_open on code_request (kind, value, purpose) where used_at is null and voided_at is null;
109
+ create index code_request_expires_at on code_request (expires_at);
110
+ `,
111
+ },
112
+ ];
113
+ /**
114
+ * Creates or updates the account tables, tracked in their own migration table. Returns the names applied.
115
+ *
116
+ * @example
117
+ * await migrateAccount(database);
118
+ */
119
+ export function migrateAccount(database) {
120
+ return migrate(database, accountMigrations, { table: ACCOUNT_MIGRATION_TABLE });
121
+ }
122
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../source/account-migration/index.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,OAAO,EAAE,MAAM,0CAA0C,CAAC;AAGnE,iHAAiH;AACjH,MAAM,CAAC,MAAM,uBAAuB,GAAG,mBAAmB,CAAC;AAE3D;;;;GAIG;AACH,MAAM,CAAC,MAAM,iBAAiB,GAAgB;IAC5C;QACE,IAAI,EAAE,wCAAwC;QAC9C,GAAG,EAAE;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;KA8EJ;KACF;IACD;QACE,IAAI,EAAE,mBAAmB;QACzB,GAAG,EAAE;;;;;;;;;;;;;;;;KAgBJ;KACF;CACF,CAAC;AAEF;;;;;GAKG;AACH,MAAM,UAAU,cAAc,CAAS,QAAwB;IAC7D,OAAO,OAAO,CAAC,QAAQ,EAAE,iBAAiB,EAAE,EAAE,KAAK,EAAE,uBAAuB,EAAE,CAAC,CAAC;AAClF,CAAC"}
@@ -0,0 +1,12 @@
1
+ import type { Kysely } from "kysely";
2
+ import type { AccountDatabase } from "@sharadox/account-web-library/account-database/type";
3
+ import type { AuditEvent } from "@sharadox/account-web-library/audit-event/type";
4
+ /**
5
+ * Adds a line to the append-only audit log (the database refuses changes to it). Pass a transaction to record it
6
+ * together with the change it describes. Returns the event's UUIDv7.
7
+ *
8
+ * @example
9
+ * await recordAuditEvent(transaction, { accountId, action: "contact.removed", detail: { contactId } });
10
+ */
11
+ export declare function recordAuditEvent(database: Kysely<AccountDatabase>, { accountId, actorAccountId, application, action, detail, now }: AuditEvent): Promise<string>;
12
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../source/audit-event/index.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AAErC,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,qDAAqD,CAAC;AAC3F,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,gDAAgD,CAAC;AAEjF;;;;;;GAMG;AACH,wBAAsB,gBAAgB,CACpC,QAAQ,EAAE,MAAM,CAAC,eAAe,CAAC,EACjC,EAAE,SAAgB,EAAE,cAAqB,EAAE,WAAkB,EAAE,MAAM,EAAE,MAAW,EAAE,GAAgB,EAAE,EAAE,UAAU,GACjH,OAAO,CAAC,MAAM,CAAC,CAejB"}
@@ -0,0 +1,25 @@
1
+ import { uuidVersion7 } from "@sharadox/web-library/identifier/uuid-version-7";
2
+ /**
3
+ * Adds a line to the append-only audit log (the database refuses changes to it). Pass a transaction to record it
4
+ * together with the change it describes. Returns the event's UUIDv7.
5
+ *
6
+ * @example
7
+ * await recordAuditEvent(transaction, { accountId, action: "contact.removed", detail: { contactId } });
8
+ */
9
+ export async function recordAuditEvent(database, { accountId = null, actorAccountId = null, application = null, action, detail = {}, now = Date.now() }) {
10
+ const id = uuidVersion7({ now });
11
+ await database
12
+ .insertInto("audit_event")
13
+ .values({
14
+ id,
15
+ at: new Date(now),
16
+ account_id: accountId,
17
+ actor_account_id: actorAccountId,
18
+ application,
19
+ action,
20
+ detail,
21
+ })
22
+ .execute();
23
+ return id;
24
+ }
25
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../source/audit-event/index.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,YAAY,EAAE,MAAM,iDAAiD,CAAC;AAI/E;;;;;;GAMG;AACH,MAAM,CAAC,KAAK,UAAU,gBAAgB,CACpC,QAAiC,EACjC,EAAE,SAAS,GAAG,IAAI,EAAE,cAAc,GAAG,IAAI,EAAE,WAAW,GAAG,IAAI,EAAE,MAAM,EAAE,MAAM,GAAG,EAAE,EAAE,GAAG,GAAG,IAAI,CAAC,GAAG,EAAE,EAAc;IAElH,MAAM,EAAE,GAAG,YAAY,CAAC,EAAE,GAAG,EAAE,CAAC,CAAC;IACjC,MAAM,QAAQ;SACX,UAAU,CAAC,aAAa,CAAC;SACzB,MAAM,CAAC;QACN,EAAE;QACF,EAAE,EAAE,IAAI,IAAI,CAAC,GAAG,CAAC;QACjB,UAAU,EAAE,SAAS;QACrB,gBAAgB,EAAE,cAAc;QAChC,WAAW;QACX,MAAM;QACN,MAAM;KACP,CAAC;SACD,OAAO,EAAE,CAAC;IACb,OAAO,EAAE,CAAC;AACZ,CAAC"}
@@ -0,0 +1,15 @@
1
+ /** What happened, to which account, done by whom, in which application. */
2
+ export interface AuditEvent {
3
+ /** The account it is about. */
4
+ accountId?: string | null;
5
+ /** Who did it, when not the account itself. */
6
+ actorAccountId?: string | null;
7
+ application?: string | null;
8
+ /** `<subject>.<verb>`: `account.created`, `contact.removed`, `role.granted`… */
9
+ action: string;
10
+ /** Ids and kinds, never contact values or secrets. */
11
+ detail?: Record<string, unknown>;
12
+ /** Milliseconds since 1970 (now by default). */
13
+ now?: number;
14
+ }
15
+ //# sourceMappingURL=type.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"type.d.ts","sourceRoot":"","sources":["../../source/audit-event/type.ts"],"names":[],"mappings":"AAAA,2EAA2E;AAC3E,MAAM,WAAW,UAAU;IACzB,+BAA+B;IAC/B,SAAS,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IAC1B,+CAA+C;IAC/C,cAAc,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IAC/B,WAAW,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IAC5B,gFAAgF;IAChF,MAAM,EAAE,MAAM,CAAC;IACf,sDAAsD;IACtD,MAAM,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IACjC,gDAAgD;IAChD,GAAG,CAAC,EAAE,MAAM,CAAC;CACd"}
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=type.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"type.js","sourceRoot":"","sources":["../../source/audit-event/type.ts"],"names":[],"mappings":""}
@@ -0,0 +1,16 @@
1
+ import type { Kysely } from "kysely";
2
+ import type { AccountDatabase } from "@sharadox/account-web-library/account-database/type";
3
+ import type { CodePurpose, CodeRequest, CodeRequestOptions } from "@sharadox/account-web-library/code-request/type";
4
+ /** The purposes a code can have. */
5
+ export declare const CODE_PURPOSES: readonly CodePurpose[];
6
+ /**
7
+ * Starts a one-time code for a contact: a new code (8 digits, 10 minutes by default), stored only as an HMAC bound
8
+ * to its purpose and request, replacing any open request for the same contact and purpose. Returns the code to send
9
+ * through the contact's channel. Rate limit and cap the sends before calling it (protection-web-library).
10
+ *
11
+ * @example
12
+ * const { requestId, code } = await requestCode(database, { purpose: "sign-in", contact, pepper });
13
+ * await channel.send(contact, code); // after answering the request, so timing reveals nothing
14
+ */
15
+ export declare function requestCode(database: Kysely<AccountDatabase>, { purpose, contact, accountId, pepper, length, lifetimeSeconds, now }: CodeRequestOptions): Promise<CodeRequest>;
16
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../source/code-request/index.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AAErC,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,qDAAqD,CAAC;AAC3F,OAAO,KAAK,EAAE,WAAW,EAAE,WAAW,EAAE,kBAAkB,EAAE,MAAM,iDAAiD,CAAC;AAIpH,oCAAoC;AACpC,eAAO,MAAM,aAAa,EAAE,SAAS,WAAW,EAAmD,CAAC;AAEpG;;;;;;;;GAQG;AACH,wBAAsB,WAAW,CAC/B,QAAQ,EAAE,MAAM,CAAC,eAAe,CAAC,EACjC,EAAE,OAAO,EAAE,OAAO,EAAE,SAAS,EAAE,MAAM,EAAE,MAAU,EAAE,eAAqB,EAAE,GAAgB,EAAE,EAAE,kBAAkB,GAC/G,OAAO,CAAC,WAAW,CAAC,CAmCtB"}
@@ -0,0 +1,52 @@
1
+ import { uuidVersion7 } from "@sharadox/web-library/identifier/uuid-version-7";
2
+ import { normalizeContact } from "@sharadox/account-web-library/contact-kind";
3
+ import { createOneTimeCode, hashOneTimeCode } from "@sharadox/account-web-library/one-time-code";
4
+ /** The purposes a code can have. */
5
+ export const CODE_PURPOSES = ["sign-in", "contact-verification", "step-up"];
6
+ /**
7
+ * Starts a one-time code for a contact: a new code (8 digits, 10 minutes by default), stored only as an HMAC bound
8
+ * to its purpose and request, replacing any open request for the same contact and purpose. Returns the code to send
9
+ * through the contact's channel. Rate limit and cap the sends before calling it (protection-web-library).
10
+ *
11
+ * @example
12
+ * const { requestId, code } = await requestCode(database, { purpose: "sign-in", contact, pepper });
13
+ * await channel.send(contact, code); // after answering the request, so timing reveals nothing
14
+ */
15
+ export async function requestCode(database, { purpose, contact, accountId, pepper, length = 8, lifetimeSeconds = 600, now = Date.now() }) {
16
+ if (!CODE_PURPOSES.includes(purpose))
17
+ throw new Error(`unknown code purpose "${purpose}"`);
18
+ const { kind, value } = normalizeContact(contact);
19
+ const requestId = uuidVersion7({ now });
20
+ const code = createOneTimeCode(length);
21
+ const codeHash = hashOneTimeCode(code, { pepper, purpose: `${purpose}:${requestId}` });
22
+ const createdAt = new Date(now);
23
+ const expiresAt = new Date(now + lifetimeSeconds * 1000);
24
+ await database.transaction().execute(async (transaction) => {
25
+ await transaction
26
+ .updateTable("code_request")
27
+ .set({ voided_at: createdAt })
28
+ .where("kind", "=", kind)
29
+ .where("value", "=", value)
30
+ .where("purpose", "=", purpose)
31
+ .where("used_at", "is", null)
32
+ .where("voided_at", "is", null)
33
+ .execute();
34
+ await transaction
35
+ .insertInto("code_request")
36
+ .values({
37
+ id: requestId,
38
+ purpose,
39
+ account_id: accountId ?? null,
40
+ kind,
41
+ value,
42
+ code_hash: codeHash,
43
+ created_at: createdAt,
44
+ expires_at: expiresAt,
45
+ used_at: null,
46
+ voided_at: null,
47
+ })
48
+ .execute();
49
+ });
50
+ return { requestId, code, contact: { kind, value }, expiresAt };
51
+ }
52
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../source/code-request/index.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,YAAY,EAAE,MAAM,iDAAiD,CAAC;AAG/E,O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K,CAAC,MAAM,EAAE,GAAG,EAAE,IAAI,CAAC;aACxB,KAAK,CAAC,OAAO,EAAE,GAAG,EAAE,KAAK,CAAC;aAC1B,KAAK,CAAC,SAAS,EAAE,GAAG,EAAE,OAAO,CAAC;aAC9B,KAAK,CAAC,SAAS,EAAE,IAAI,EAAE,IAAI,CAAC;aAC5B,KAAK,CAAC,WAAW,EAAE,IAAI,EAAE,IAAI,CAAC;aAC9B,OAAO,EAAE,CAAC;QACb,MAAM,WAAW;aACd,UAAU,CAAC,cAAc,CAAC;aAC1B,MAAM,CAAC;YACN,EAAE,EAAE,SAAS;YACb,OAAO;YACP,UAAU,EAAE,SAAS,IAAI,IAAI;YAC7B,IAAI;YACJ,KAAK;YACL,SAAS,EAAE,QAAQ;YACnB,UAAU,EAAE,SAAS;YACrB,UAAU,EAAE,SAAS;YACrB,OAAO,EAAE,IAAI;YACb,SAAS,EAAE,IAAI;SAChB,CAAC;aACD,OAAO,EAAE,CAAC;IACf,CAAC,CAAC,CAAC;IACH,OAAO,EAAE,SAAS,EAAE,IAAI,EAAE,OAAO,EAAE,EAAE,IAAI,EAAE,KAAK,EAAE,EAAE,SAAS,EAAE,CAAC;AAClE,CAAC"}
@@ -0,0 +1,25 @@
1
+ import type { Contact } from "@sharadox/account-web-library/contact-kind/type";
2
+ /** What a one-time code is for; a code works only for its own purpose and request. */
3
+ export type CodePurpose = "sign-in" | "contact-verification" | "step-up";
4
+ export interface CodeRequestOptions {
5
+ purpose: CodePurpose;
6
+ contact: Contact;
7
+ /** The account asking (step-up, contact verification). */
8
+ accountId?: string;
9
+ /** At least 32 characters, kept outside the database. */
10
+ pepper: string;
11
+ /** Digits (8 by default). */
12
+ length?: number;
13
+ /** 600 (10 minutes) by default. */
14
+ lifetimeSeconds?: number;
15
+ /** Milliseconds since 1970 (now by default). */
16
+ now?: number;
17
+ }
18
+ export interface CodeRequest {
19
+ requestId: string;
20
+ /** Send it, then forget it: only its hash is stored. */
21
+ code: string;
22
+ contact: Contact;
23
+ expiresAt: Date;
24
+ }
25
+ //# sourceMappingURL=type.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"type.d.ts","sourceRoot":"","sources":["../../source/code-request/type.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,iDAAiD,CAAC;AAE/E,sFAAsF;AACtF,MAAM,MAAM,WAAW,GAAG,SAAS,GAAG,sBAAsB,GAAG,SAAS,CAAC;AAEzE,MAAM,WAAW,kBAAkB;IACjC,OAAO,EAAE,WAAW,CAAC;IACrB,OAAO,EAAE,OAAO,CAAC;IACjB,0DAA0D;IAC1D,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,yDAAyD;IACzD,MAAM,EAAE,MAAM,CAAC;IACf,6BAA6B;IAC7B,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,mCAAmC;IACnC,eAAe,CAAC,EAAE,MAAM,CAAC;IACzB,gDAAgD;IAChD,GAAG,CAAC,EAAE,MAAM,CAAC;CACd;AAED,MAAM,WAAW,WAAW;IAC1B,SAAS,EAAE,MAAM,CAAC;IAClB,wDAAwD;IACxD,IAAI,EAAE,MAAM,CAAC;IACb,OAAO,EAAE,OAAO,CAAC;IACjB,SAAS,EAAE,IAAI,CAAC;CACjB"}
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=type.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"type.js","sourceRoot":"","sources":["../../source/code-request/type.ts"],"names":[],"mappings":""}
@@ -0,0 +1,13 @@
1
+ import type { Kysely } from "kysely";
2
+ import type { AccountDatabase } from "@sharadox/account-web-library/account-database/type";
3
+ /**
4
+ * Deletes code requests that expired before `before`, with the contacts they hold, from a daily job. Returns how
5
+ * many were deleted.
6
+ *
7
+ * @example
8
+ * await pruneCodeRequests(database, { before: new Date(Date.now() - 86_400_000) });
9
+ */
10
+ export declare function pruneCodeRequests(database: Kysely<AccountDatabase>, { before }: {
11
+ before: Date;
12
+ }): Promise<number>;
13
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../source/code-request-prune/index.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AACrC,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,qDAAqD,CAAC;AAE3F;;;;;;GAMG;AACH,wBAAsB,iBAAiB,CACrC,QAAQ,EAAE,MAAM,CAAC,eAAe,CAAC,EACjC,EAAE,MAAM,EAAE,EAAE;IAAE,MAAM,EAAE,IAAI,CAAA;CAAE,GAC3B,OAAO,CAAC,MAAM,CAAC,CAGjB"}
@@ -0,0 +1,12 @@
1
+ /**
2
+ * Deletes code requests that expired before `before`, with the contacts they hold, from a daily job. Returns how
3
+ * many were deleted.
4
+ *
5
+ * @example
6
+ * await pruneCodeRequests(database, { before: new Date(Date.now() - 86_400_000) });
7
+ */
8
+ export async function pruneCodeRequests(database, { before }) {
9
+ const result = await database.deleteFrom("code_request").where("expires_at", "<", before).executeTakeFirst();
10
+ return Number(result.numDeletedRows);
11
+ }
12
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../source/code-request-prune/index.ts"],"names":[],"mappings":"AAGA;;;;;;GAMG;AACH,MAAM,CAAC,KAAK,UAAU,iBAAiB,CACrC,QAAiC,EACjC,EAAE,MAAM,EAAoB;IAE5B,MAAM,MAAM,GAAG,MAAM,QAAQ,CAAC,UAAU,CAAC,cAAc,CAAC,CAAC,KAAK,CAAC,YAAY,EAAE,GAAG,EAAE,MAAM,CAAC,CAAC,gBAAgB,EAAE,CAAC;IAC7G,OAAO,MAAM,CAAC,MAAM,CAAC,cAAc,CAAC,CAAC;AACvC,CAAC"}
@@ -0,0 +1,14 @@
1
+ import type { Kysely } from "kysely";
2
+ import type { AccountDatabase } from "@sharadox/account-web-library/account-database/type";
3
+ import type { CodeVerificationOptions, CodeVerificationResult } from "@sharadox/account-web-library/code-verification/type";
4
+ /**
5
+ * Checks a typed one-time code against its request, with the row locked so concurrent guesses can't pass the
6
+ * attempt limit. The right code works once, before it expires, unless a newer request replaced it or 5 wrong codes
7
+ * came first. Returns the proved contact and the account that asked (null for sign-in).
8
+ *
9
+ * @example
10
+ * const result = await verifyCode(database, { requestId, code: typed, purpose: "sign-in", pepper });
11
+ * if (result.valid) signIn(await findAccountByContact(database, result.contact));
12
+ */
13
+ export declare function verifyCode(database: Kysely<AccountDatabase>, { requestId, code, purpose, pepper, maximumAttempts, now }: CodeVerificationOptions): Promise<CodeVerificationResult>;
14
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../source/code-verification/index.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AACrC,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,qDAAqD,CAAC;AAC3F,OAAO,KAAK,EACV,uBAAuB,EACvB,sBAAsB,EACvB,MAAM,sDAAsD,CAAC;AAK9D;;;;;;;;GAQG;AACH,wBAAsB,UAAU,CAC9B,QAAQ,EAAE,MAAM,CAAC,eAAe,CAAC,EACjC,EAAE,SAAS,EAAE,IAAI,EAAE,OAAO,EAAE,MAAM,EAAE,eAAmB,EAAE,GAAgB,EAAE,EAAE,uBAAuB,GACnG,OAAO,CAAC,sBAAsB,CAAC,CAwBjC"}
@@ -0,0 +1,43 @@
1
+ import { matchesOneTimeCode } from "@sharadox/account-web-library/one-time-code";
2
+ const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
3
+ /**
4
+ * Checks a typed one-time code against its request, with the row locked so concurrent guesses can't pass the
5
+ * attempt limit. The right code works once, before it expires, unless a newer request replaced it or 5 wrong codes
6
+ * came first. Returns the proved contact and the account that asked (null for sign-in).
7
+ *
8
+ * @example
9
+ * const result = await verifyCode(database, { requestId, code: typed, purpose: "sign-in", pepper });
10
+ * if (result.valid) signIn(await findAccountByContact(database, result.contact));
11
+ */
12
+ export async function verifyCode(database, { requestId, code, purpose, pepper, maximumAttempts = 5, now = Date.now() }) {
13
+ if (!UUID.test(requestId))
14
+ return { valid: false, reason: "unknown" };
15
+ return database.transaction().execute(async (transaction) => {
16
+ const request = await transaction
17
+ .selectFrom("code_request")
18
+ .selectAll()
19
+ .where("id", "=", requestId)
20
+ .where("purpose", "=", purpose)
21
+ .forUpdate()
22
+ .executeTakeFirst();
23
+ if (!request)
24
+ return { valid: false, reason: "unknown" };
25
+ if (request.used_at)
26
+ return { valid: false, reason: "used" };
27
+ if (request.voided_at)
28
+ return { valid: false, reason: "replaced" };
29
+ if (request.expires_at.getTime() <= now)
30
+ return { valid: false, reason: "expired" };
31
+ if (request.attempts >= maximumAttempts)
32
+ return { valid: false, reason: "attempts" };
33
+ const at = transaction.updateTable("code_request").where("id", "=", requestId);
34
+ if (matchesOneTimeCode(code, request.code_hash, { pepper, purpose: `${purpose}:${requestId}` })) {
35
+ await at.set({ used_at: new Date(now) }).execute();
36
+ return { valid: true, contact: { kind: request.kind, value: request.value }, accountId: request.account_id };
37
+ }
38
+ const attempts = request.attempts + 1;
39
+ await at.set({ attempts }).execute();
40
+ return { valid: false, reason: attempts >= maximumAttempts ? "attempts" : "wrong" };
41
+ });
42
+ }
43
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../source/code-verification/index.ts"],"names":[],"mappings":"AAMA,OAAO,EAAE,kBAAkB,EAAE,MAAM,6CAA6C,CAAC;AAEjF,MAAM,IAAI,GAAG,iEAAiE,CAAC;AAE/E;;;;;;;;GAQG;AACH,MAAM,CAAC,KAAK,UAAU,UAAU,CAC9B,QAAiC,EACjC,EAAE,SAAS,EAAE,IAAI,EAAE,OAAO,EAAE,MAAM,EAAE,eAAe,G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