@things-factory/auth-base 10.1.4 → 10.1.7

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 (75) hide show
  1. package/CHANGELOG.md +16 -0
  2. package/dist-client/auth.d.ts +9 -1
  3. package/dist-client/auth.js +12 -3
  4. package/dist-client/auth.js.map +1 -1
  5. package/dist-client/tsconfig.tsbuildinfo +1 -1
  6. package/dist-server/controllers/profile.d.ts +1 -0
  7. package/dist-server/controllers/signin.js +33 -12
  8. package/dist-server/controllers/signin.js.map +1 -1
  9. package/dist-server/controllers/unlock-user.js +21 -2
  10. package/dist-server/controllers/unlock-user.js.map +1 -1
  11. package/dist-server/index.js +8 -0
  12. package/dist-server/index.js.map +1 -1
  13. package/dist-server/router/auth-public-process-router.js +32 -5
  14. package/dist-server/router/auth-public-process-router.js.map +1 -1
  15. package/dist-server/service/index.d.ts +3 -1
  16. package/dist-server/service/index.js +15 -11
  17. package/dist-server/service/index.js.map +1 -1
  18. package/dist-server/service/privilege/privilege-directive.d.ts +15 -0
  19. package/dist-server/service/privilege/privilege-directive.js +27 -6
  20. package/dist-server/service/privilege/privilege-directive.js.map +1 -1
  21. package/dist-server/service/role/index.d.ts +2 -1
  22. package/dist-server/service/role/index.js +2 -1
  23. package/dist-server/service/role/index.js.map +1 -1
  24. package/dist-server/service/role/role-mutation.d.ts +17 -1
  25. package/dist-server/service/role/role-mutation.js +126 -7
  26. package/dist-server/service/role/role-mutation.js.map +1 -1
  27. package/dist-server/service/role/role-privilege-query.d.ts +14 -0
  28. package/dist-server/service/role/role-privilege-query.js +37 -0
  29. package/dist-server/service/role/role-privilege-query.js.map +1 -0
  30. package/dist-server/service/role/role-query.d.ts +61 -1
  31. package/dist-server/service/role/role-query.js +114 -55
  32. package/dist-server/service/role/role-query.js.map +1 -1
  33. package/dist-server/service/role-template/index.d.ts +4 -0
  34. package/dist-server/service/role-template/index.js +9 -0
  35. package/dist-server/service/role-template/index.js.map +1 -0
  36. package/dist-server/service/role-template/role-template-mutation.d.ts +39 -0
  37. package/dist-server/service/role-template/role-template-mutation.js +124 -0
  38. package/dist-server/service/role-template/role-template-mutation.js.map +1 -0
  39. package/dist-server/service/role-template/role-template-query.d.ts +11 -0
  40. package/dist-server/service/role-template/role-template-query.js +79 -0
  41. package/dist-server/service/role-template/role-template-query.js.map +1 -0
  42. package/dist-server/service/role-template/role-template-types.d.ts +51 -0
  43. package/dist-server/service/role-template/role-template-types.js +71 -0
  44. package/dist-server/service/role-template/role-template-types.js.map +1 -0
  45. package/dist-server/service/role-template/role-template.d.ts +110 -0
  46. package/dist-server/service/role-template/role-template.js +129 -0
  47. package/dist-server/service/role-template/role-template.js.map +1 -0
  48. package/dist-server/service/user/user.d.ts +1 -0
  49. package/dist-server/service/user/user.js +55 -13
  50. package/dist-server/service/user/user.js.map +1 -1
  51. package/dist-server/tsconfig.tsbuildinfo +1 -1
  52. package/dist-server/utils/account-lock-rule.d.ts +79 -0
  53. package/dist-server/utils/account-lock-rule.js +114 -0
  54. package/dist-server/utils/account-lock-rule.js.map +1 -0
  55. package/dist-server/utils/lock-duration.d.ts +3 -0
  56. package/dist-server/utils/lock-duration.js +36 -0
  57. package/dist-server/utils/lock-duration.js.map +1 -0
  58. package/package.json +4 -4
  59. package/tests/account-lock-db.test.ts +216 -0
  60. package/tests/account-lock-rule.test.ts +141 -0
  61. package/tests/compiled.ts +41 -0
  62. package/tests/has-privilege-db.test.ts +198 -0
  63. package/tests/lock-recovery.test.ts +204 -0
  64. package/tests/password-hashing.test.ts +131 -0
  65. package/tests/password-persistence.test.ts +147 -0
  66. package/tests/permission-gate.test.ts +226 -0
  67. package/tests/privilege-directive.test.ts +180 -0
  68. package/tests/role-mutation-db.test.ts +263 -0
  69. package/tests/role-privileges-db.test.ts +226 -0
  70. package/tests/role-template-seed-db.test.ts +179 -0
  71. package/tests/role-template.test.ts +126 -0
  72. package/tests/signin-policy.test.ts +200 -0
  73. package/tests/token-issuance.test.ts +240 -0
  74. package/translations/en.json +161 -1
  75. package/translations/ko.json +161 -1
@@ -0,0 +1,129 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.registerRoleTemplate = registerRoleTemplate;
4
+ exports.roleTemplates = roleTemplates;
5
+ exports.roleTemplateById = roleTemplateById;
6
+ exports.computedRoleTemplates = computedRoleTemplates;
7
+ exports.allRoleTemplates = allRoleTemplates;
8
+ exports.unknownTemplateGrants = unknownTemplateGrants;
9
+ exports.reportUnknownTemplateGrants = reportUnknownTemplateGrants;
10
+ const env_1 = require("@things-factory/env");
11
+ const REGISTRY = 'ROLE_TEMPLATES';
12
+ process[REGISTRY] = {};
13
+ function registry() {
14
+ return process[REGISTRY];
15
+ }
16
+ /**
17
+ * Declares a role template. Call it from the application's server entry.
18
+ *
19
+ * Categories are not checked here: registration runs while modules load, before the
20
+ * schema is built and therefore before `process['PRIVILEGES']` exists. The name check
21
+ * happens at boot instead (`reportUnknownTemplateGrants`).
22
+ */
23
+ function registerRoleTemplate(template) {
24
+ if (!template?.id || !template?.name) {
25
+ throw new Error('A role template needs both an id and a name.');
26
+ }
27
+ if (!Array.isArray(template.grants)) {
28
+ throw new Error(`Role template "${template.id}" has no grants. Write \`grants: []\` if this seat is meant to ` +
29
+ 'open nothing — leaving it out is indistinguishable from forgetting, and the screen cannot ' +
30
+ 'tell an administrator which one it is.');
31
+ }
32
+ for (const grant of template.grants) {
33
+ if (!grant?.category || !Array.isArray(grant.axes) || grant.axes.length === 0) {
34
+ throw new Error(`Role template "${template.id}" has a grant without a category or with no axes. ` +
35
+ 'Axes are always listed one by one.');
36
+ }
37
+ /*
38
+ * Across the nine roles operato-plant declares, no role is granted `mutation` on a
39
+ * category without `query` on the same category — you cannot fix what you cannot see.
40
+ * A template that does so is almost certainly a slip, so say it out loud rather than
41
+ * silently granting a half-usable seat.
42
+ */
43
+ if (grant.axes.includes('mutation') && !grant.axes.includes('query')) {
44
+ env_1.logger.warn(`[role-template] "${template.id}" grants ${grant.category}:mutation without ${grant.category}:query. ` +
45
+ 'Someone who may change a thing but not see it can rarely use either.');
46
+ }
47
+ }
48
+ if (registry()[template.id]) {
49
+ throw new Error(`Role template "${template.id}" is declared twice.`);
50
+ }
51
+ registry()[template.id] = { ...template };
52
+ }
53
+ function roleTemplates() {
54
+ return Object.values(registry());
55
+ }
56
+ function roleTemplateById(id) {
57
+ return registry()[id];
58
+ }
59
+ /**
60
+ * The two templates the framework can build without knowing a single category name.
61
+ *
62
+ * Everything else has to be declared by an application: a job title spans modules
63
+ * (a production lead uses worklist *and* order *and* ops-master) and no one package knows
64
+ * that. These two are different — they are defined over whatever is declared, so they can
65
+ * be computed from the registry `@privilege` fills.
66
+ */
67
+ function computedRoleTemplates() {
68
+ const declared = Object.values(process['PRIVILEGES'] || {});
69
+ const axesOf = new Map();
70
+ for (const [category, axis] of declared) {
71
+ if (!axesOf.has(category)) {
72
+ axesOf.set(category, new Set());
73
+ }
74
+ axesOf.get(category).add(axis);
75
+ }
76
+ const categories = [...axesOf.keys()].sort();
77
+ /*
78
+ * No description on either of these.
79
+ *
80
+ * They carried i18n keys, which the seeding path stored verbatim onto the role and the
81
+ * list then drew as the description. And a static sentence would be worse than what the
82
+ * screen already computes from `grants` — "opens 30 things across 30 modules" is exact
83
+ * and moves when the installation does.
84
+ */
85
+ const viewer = {
86
+ id: 'framework.viewer',
87
+ name: 'VIEWER',
88
+ grants: categories.filter(category => axesOf.get(category).has('query')).map(category => ({ category, axes: ['query'] }))
89
+ };
90
+ /*
91
+ * The one place that widens on purpose.
92
+ *
93
+ * Everywhere else an unenumerated axis is a defect waiting for the day a new axis is
94
+ * declared. Here "everything that exists" is the meaning of the template, so picking up
95
+ * a newly declared axis is correct rather than accidental.
96
+ */
97
+ const administrator = {
98
+ id: 'framework.administrator',
99
+ name: 'ADMINISTRATOR',
100
+ grants: categories.map(category => ({ category, axes: [...axesOf.get(category)].sort() }))
101
+ };
102
+ return [viewer, administrator];
103
+ }
104
+ /** Every template this installation offers — declared by apps, plus the computed two. */
105
+ function allRoleTemplates() {
106
+ return [...computedRoleTemplates(), ...roleTemplates()];
107
+ }
108
+ /**
109
+ * Names a template mentions that this installation does not declare.
110
+ *
111
+ * A template that survives a category rename becomes a role that grants nothing, and that
112
+ * is the quietest way this design can fail — the administrator picks "quality inspector",
113
+ * gets a role, and it opens no doors. operato-plant's seed already does this for its own
114
+ * table (`seed-demo-org.ts` warns about grants it could not attach); this is the same
115
+ * check moved to where templates are declared.
116
+ */
117
+ function unknownTemplateGrants(template) {
118
+ const declared = process['PRIVILEGES'] || {};
119
+ return template.grants.flatMap(grant => grant.axes.filter(axis => !declared[`${grant.category} ${axis}`]).map(axis => `${grant.category}:${axis}`));
120
+ }
121
+ function reportUnknownTemplateGrants() {
122
+ const unknown = roleTemplates().flatMap(template => unknownTemplateGrants(template).map(grant => `${template.id} → ${grant}`));
123
+ if (unknown.length) {
124
+ env_1.logger.warn(`[role-template] ${unknown.length} grants name privileges this installation does not declare — ` +
125
+ `${unknown.join(', ')}. Privilege definitions come from @privilege at boot, so either the query ` +
126
+ 'is not installed here or the name has moved. A role seeded from such a template opens nothing.');
127
+ }
128
+ }
129
+ //# sourceMappingURL=role-template.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"role-template.js","sourceRoot":"","sources":["../../../server/service/role-template/role-template.ts"],"names":[],"mappings":";;AAmGA,oDAwCC;AAED,sCAEC;AAED,4CAEC;AAUD,sDAyCC;AAGD,4CAEC;AAWD,sDAMC;AAED,kEAYC;AA1OD,6CAA4C;AAoF5C,MAAM,QAAQ,GAAG,gBAAgB,CAAA;AAEjC,OAAO,CAAC,QAAQ,CAAC,GAAG,EAAE,CAAA;AAEtB,SAAS,QAAQ;IACf,OAAO,OAAO,CAAC,QAAQ,CAAC,CAAA;AAC1B,CAAC;AAED;;;;;;GAMG;AACH,SAAgB,oBAAoB,CAAC,QAAsB;IACzD,IAAI,CAAC,QAAQ,EAAE,EAAE,IAAI,CAAC,QAA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;AACH,CAAC","sourcesContent":["import { logger } from '@things-factory/env'\n\n/**\n * Role templates — the seeds an application offers so a new domain does not start with\n * zero roles.\n *\n * ── Why this is a boot registry and not a table ───────────────────────────────\n * A template is a declaration. Copying it into rows per domain gives 100 domains x 3\n * templates = 300 rows, and once the code changes the template there is nowhere to ask\n * which of the two is true: the declaration, or the row that was written from an older\n * one. `@privilege` lives in the boot registry for the same reason.\n *\n * ── What a template is not ───────────────────────────────────────────────────\n * It is a seed, not a role. Once it has been used the resulting role belongs to the\n * administrator: the template is never re-applied and never overwrites. Nothing is written\n * onto the role to remember where it came from — what an administrator would want from\n * that (\"the template gained two privileges, here they are\") is the template's current\n * grants against the role's current privileges, and that is computed rather than stored.\n *\n * ── A role is one thing seen from three sides ────────────────────────────────\n * operato-plant uses roles as privilege bundles; operato-twin uses them as the seat an\n * approval line points at (`worklist` resolves an approver of type `Role` by id). Those\n * are not two concepts. A role is a seat in the organisation: what it opens, who fills it,\n * and whether approvals route to it. Splitting them would put two QUALITY-INSPECTORs in\n * one plant and force every person into both.\n */\n\n/** One module and the axes this template grants on it. Axes are always enumerated. */\nexport type RoleTemplateGrant = {\n /** `@privilege(category:)` — what is guarded, not the package name. */\n category: string\n /**\n * `query` / `mutation` / ... — listed one by one.\n *\n * There is deliberately no `'all'`. A template written as \"everything\" would widen on\n * its own the day a new axis is declared, with nobody having touched it. The single\n * place that may widen is the framework-computed administrator template, which means\n * \"whatever exists now\" by definition.\n */\n axes: string[]\n}\n\nexport type RoleTemplate = {\n /** Declaration key, namespaced by the declaring app: `plant.quality-inspector`. */\n id: string\n /**\n * The role name created in the domain: `QUALITY-INSPECTOR`.\n *\n * Two apps may declare the same name on purpose — that is one seat, and the privileges\n * become the union. The name is also a stored identifier: approval lines hold the role's\n * id, so renaming here creates a second role and leaves the approval line pointing at\n * the first. Renaming is a migration, not a template edit.\n */\n name: string\n /**\n * Plain text, not an i18n key.\n *\n * `createRoleFromTemplate` copies this onto the role it seeds, and the role list draws\n * the role's description as a value — so a key written here reaches the screen as\n * `label.role-template.administrator`. That is exactly what the framework's own two\n * templates did until 2026-09-11.\n *\n * operato-plant had it right from the start: \"검사 기준과 처분을 정하는 자리\".\n */\n description?: string\n /**\n * Required, and may be empty.\n *\n * `[]` is a statement: this seat opens nothing, it exists for approval routing. A\n * missing `grants` is a different thing — someone forgot — and is rejected here, so the\n * screen can tell \"opens nothing on purpose\" from \"nothing was written down\".\n */\n grants: RoleTemplateGrant[]\n}\n\n/**\n * Registered form of a template.\n *\n * Identical to the declaration today. It stays a separate name because the registry is\n * what every reader goes through, and giving it its own type keeps a later addition from\n * rippling into every call site.\n */\nexport type RegisteredRoleTemplate = RoleTemplate\n\nconst REGISTRY = 'ROLE_TEMPLATES'\n\nprocess[REGISTRY] = {}\n\nfunction registry(): Record<string, RegisteredRoleTemplate> {\n return process[REGISTRY]\n}\n\n/**\n * Declares a role template. Call it from the application's server entry.\n *\n * Categories are not checked here: registration runs while modules load, before the\n * schema is built and therefore before `process['PRIVILEGES']` exists. The name check\n * happens at boot instead (`reportUnknownTemplateGrants`).\n */\nexport function registerRoleTemplate(template: RoleTemplate): void {\n if (!template?.id || !template?.name) {\n throw new Error('A role template needs both an id and a name.')\n }\n\n if (!Array.isArray(template.grants)) {\n throw new Error(\n `Role template \"${template.id}\" has no grants. Write \\`grants: []\\` if this seat is meant to ` +\n 'open nothing — leaving it out is indistinguishable from forgetting, and the screen cannot ' +\n 'tell an administrator which one it is.'\n )\n }\n\n for (const grant of template.grants) {\n if (!grant?.category || !Array.isArray(grant.axes) || grant.axes.length === 0) {\n throw new Error(\n `Role template \"${template.id}\" has a grant without a category or with no axes. ` +\n 'Axes are always listed one by one.'\n )\n }\n\n /*\n * Across the nine roles operato-plant declares, no role is granted `mutation` on a\n * category without `query` on the same category — you cannot fix what you cannot see.\n * A template that does so is almost certainly a slip, so say it out loud rather than\n * silently granting a half-usable seat.\n */\n if (grant.axes.includes('mutation') && !grant.axes.includes('query')) {\n logger.warn(\n `[role-template] \"${template.id}\" grants ${grant.category}:mutation without ${grant.category}:query. ` +\n 'Someone who may change a thing but not see it can rarely use either.'\n )\n }\n }\n\n if (registry()[template.id]) {\n throw new Error(`Role template \"${template.id}\" is declared twice.`)\n }\n\n registry()[template.id] = { ...template }\n}\n\nexport function roleTemplates(): RegisteredRoleTemplate[] {\n return Object.values(registry())\n}\n\nexport function roleTemplateById(id: string): RegisteredRoleTemplate | undefined {\n return registry()[id]\n}\n\n/**\n * The two templates the framework can build without knowing a single category name.\n *\n * Everything else has to be declared by an application: a job title spans modules\n * (a production lead uses worklist *and* order *and* ops-master) and no one package knows\n * that. These two are different — they are defined over whatever is declared, so they can\n * be computed from the registry `@privilege` fills.\n */\nexport function computedRoleTemplates(): RegisteredRoleTemplate[] {\n const declared: [string, string][] = Object.values(process['PRIVILEGES'] || {})\n const axesOf = new Map<string, Set<string>>()\n\n for (const [category, axis] of declared) {\n if (!axesOf.has(category)) {\n axesOf.set(category, new Set())\n }\n axesOf.get(category)!.add(axis)\n }\n\n const categories = [...axesOf.keys()].sort()\n\n /*\n * No description on either of these.\n *\n * They carried i18n keys, which the seeding path stored verbatim onto the role and the\n * list then drew as the description. And a static sentence would be worse than what the\n * screen already computes from `grants` — \"opens 30 things across 30 modules\" is exact\n * and moves when the installation does.\n */\n const viewer: RoleTemplate = {\n id: 'framework.viewer',\n name: 'VIEWER',\n grants: categories.filter(category => axesOf.get(category)!.has('query')).map(category => ({ category, axes: ['query'] }))\n }\n\n /*\n * The one place that widens on purpose.\n *\n * Everywhere else an unenumerated axis is a defect waiting for the day a new axis is\n * declared. Here \"everything that exists\" is the meaning of the template, so picking up\n * a newly declared axis is correct rather than accidental.\n */\n const administrator: RoleTemplate = {\n id: 'framework.administrator',\n name: 'ADMINISTRATOR',\n grants: categories.map(category => ({ category, axes: [...axesOf.get(category)!].sort() }))\n }\n\n return [viewer, administrator]\n}\n\n/** Every template this installation offers — declared by apps, plus the computed two. */\nexport function allRoleTemplates(): RegisteredRoleTemplate[] {\n return [...computedRoleTemplates(), ...roleTemplates()]\n}\n\n/**\n * Names a template mentions that this installation does not declare.\n *\n * A template that survives a category rename becomes a role that grants nothing, and that\n * is the quietest way this design can fail — the administrator picks \"quality inspector\",\n * gets a role, and it opens no doors. operato-plant's seed already does this for its own\n * table (`seed-demo-org.ts` warns about grants it could not attach); this is the same\n * check moved to where templates are declared.\n */\nexport function unknownTemplateGrants(template: RoleTemplate): string[] {\n const declared = process['PRIVILEGES'] || {}\n\n return template.grants.flatMap(grant =>\n grant.axes.filter(axis => !declared[`${grant.category} ${axis}`]).map(axis => `${grant.category}:${axis}`)\n )\n}\n\nexport function reportUnknownTemplateGrants(): void {\n const unknown = roleTemplates().flatMap(template =>\n unknownTemplateGrants(template).map(grant => `${template.id} → ${grant}`)\n )\n\n if (unknown.length) {\n logger.warn(\n `[role-template] ${unknown.length} grants name privileges this installation does not declare — ` +\n `${unknown.join(', ')}. Privilege definitions come from @privilege at boot, so either the query ` +\n 'is not installed here or the name has moved. A role seeded from such a template opens nothing.'\n )\n }\n}\n"]}
@@ -27,6 +27,7 @@ export declare class User {
27
27
  status: UserStatus;
28
28
  failCount: number;
29
29
  passwordUpdatedAt: Date;
30
+ lockedAt: Date;
30
31
  owner: boolean;
31
32
  credentials: WebAuthCredential[];
32
33
  usersAuthProviders: UsersAuthProviders[];
@@ -13,6 +13,8 @@ const typeorm_1 = require("typeorm");
13
13
  const env_1 = require("@things-factory/env");
14
14
  const shell_1 = require("@things-factory/shell");
15
15
  const password_rule_js_1 = require("../../controllers/utils/password-rule.js");
16
+ const account_lock_rule_js_1 = require("../../utils/account-lock-rule.js");
17
+ const lock_duration_js_1 = require("../../utils/lock-duration.js");
16
18
  const auth_error_js_1 = require("../../errors/auth-error.js");
17
19
  const get_secret_js_1 = require("../../utils/get-secret.js");
18
20
  const role_js_1 = require("../role/role.js");
@@ -99,12 +101,23 @@ let User = User_1 = class User {
99
101
  }
100
102
  });
101
103
  case UserStatus.LOCKED:
102
- throw new auth_error_js_1.AuthError({
103
- errorCode: auth_error_js_1.AuthError.ERROR_CODES.USER_LOCKED,
104
- detail: {
105
- email: user.email
106
- }
107
- });
104
+ /*
105
+ * 잠금이 아직 유효한지는 `utils/account-lock-rule.ts` 한 곳이 판정한다 — `signin` 과
106
+ * 이 자리가 각자 판단하면 로그인은 되는데 요청은 거절되는 상태가 생긴다.
107
+ *
108
+ * **여기서는 행을 고치지 않는다.** 매 요청 지나는 경로라 쓰기를 얹지 않는다. 판정이
109
+ * 「풀렸다」면 통과시키고, 행 정리(`ACTIVATED` · `failCount` 0 · `lockedAt` 비움)는
110
+ * 다음 `signin` 이 한다.
111
+ */
112
+ if ((0, account_lock_rule_js_1.isAccountLocked)(user, new Date(), (0, lock_duration_js_1.lockDurationMinutes)())) {
113
+ throw new auth_error_js_1.AuthError({
114
+ errorCode: auth_error_js_1.AuthError.ERROR_CODES.USER_LOCKED,
115
+ detail: {
116
+ email: user.email
117
+ }
118
+ });
119
+ }
120
+ break;
108
121
  case UserStatus.DELETED:
109
122
  throw new auth_error_js_1.AuthError({
110
123
  errorCode: auth_error_js_1.AuthError.ERROR_CODES.USER_DELETED
@@ -159,18 +172,31 @@ let User = User_1 = class User {
159
172
  }
160
173
  });
161
174
  case UserStatus.LOCKED:
162
- throw new auth_error_js_1.AuthError({
163
- errorCode: auth_error_js_1.AuthError.ERROR_CODES.USER_LOCKED,
164
- detail: {
165
- email: user.email
166
- }
167
- });
175
+ /*
176
+ * 잠금이 아직 유효한지는 `utils/account-lock-rule.ts` 한 곳이 판정한다 — `signin` 과
177
+ * 이 자리가 각자 판단하면 로그인은 되는데 요청은 거절되는 상태가 생긴다.
178
+ *
179
+ * **여기서는 행을 고치지 않는다.** 매 요청 지나는 경로라 쓰기를 얹지 않는다. 판정이
180
+ * 「풀렸다」면 통과시키고, 행 정리(`ACTIVATED` · `failCount` 0 · `lockedAt` 비움)는
181
+ * 다음 `signin` 이 한다.
182
+ */
183
+ if ((0, account_lock_rule_js_1.isAccountLocked)(user, new Date(), (0, lock_duration_js_1.lockDurationMinutes)())) {
184
+ throw new auth_error_js_1.AuthError({
185
+ errorCode: auth_error_js_1.AuthError.ERROR_CODES.USER_LOCKED,
186
+ detail: {
187
+ email: user.email
188
+ }
189
+ });
190
+ }
191
+ break;
168
192
  case UserStatus.DELETED:
169
193
  throw new auth_error_js_1.AuthError({
170
194
  errorCode: auth_error_js_1.AuthError.ERROR_CODES.USER_DELETED
171
195
  });
172
196
  }
173
- const { defaultPassword } = env_1.config.get('password');
197
+ /* 설정이 없으면 `{}` 로 — 기본값 없이 구조 분해하면 `password` 를 설정하지 않은 배포에서
198
+ 이 줄이 던진다. `password-rule.ts` 도 같은 자리에서 대비를 두고 있다. */
199
+ const { defaultPassword } = env_1.config.get('password', {});
174
200
  if (defaultPassword && user.password === this.encode(defaultPassword, user.salt)) {
175
201
  user.status = UserStatus.PWD_RESET_REQUIRED;
176
202
  }
@@ -329,8 +355,24 @@ tslib_1.__decorate([
329
355
  tslib_1.__decorate([
330
356
  (0, typeorm_1.Column)({ nullable: true }),
331
357
  tslib_1.__metadata("design:type", Date // Last time the password was updated
358
+ /*
359
+ * When the account was locked, so the lock can lift on its own.
360
+ *
361
+ * The decision of whether a lock is still in effect lives in one place —
362
+ * `utils/account-lock-rule.ts` — because two callers ask: `signin`, and `checkAuth` on every
363
+ * request. A row locked before this column existed has no value here, and the rule keeps such a
364
+ * lock in effect rather than releasing it, so nothing opens quietly.
365
+ */
332
366
  )
333
367
  ], User.prototype, "passwordUpdatedAt", void 0);
368
+ tslib_1.__decorate([
369
+ (0, typeorm_1.Column)({ nullable: true }),
370
+ (0, type_graphql_1.Field)({
371
+ nullable: true,
372
+ description: 'When the account was locked. With the configured lock duration this says when it lifts.'
373
+ }),
374
+ tslib_1.__metadata("design:type", Date)
375
+ ], User.prototype, "lockedAt", void 0);
334
376
  tslib_1.__decorate([
335
377
  (0, type_graphql_1.Field)({ nullable: true, description: 'Whether the user is the owner of the domain (not persisted in DB).' }),
336
378
  tslib_1.__metadata("design:type", Boolean)
@@ -1 +1 @@
1
- {"version":3,"file":"user.js","sourceRoot":"","sources":["../../../server/service/user/user.ts"],"names":[],"mappings":";AAAA,iGAAiG;AACjG,mGAAmG;;;;;AAEnG,4DAA2B;AAC3B,wEAA8B;AAC9B,+CAA+D;AAC/D,qDAAqD;AACrD,qCAagB;AAEhB,6CAA4C;AAC5C,iDAA+G;AAE/G,+EAAiF;AACjF,8DAAsD;AACtD,6DAAkD;AAClD,6CAAsC;AACtC,4DAAqD;AACrD,0FAAiF;AACjF,6FAAoF;AAEpF,MAAM,SAAS,GAAG,YAAM,CAAC,GAAG,CAAC,WAAW,EAAE,EAAE,CAAC,CAAA;AAC7C,MAAM,aAAa,GAAG,SAAS,CAAC,IAAI,CAAA;AAEpC,MAAM,oBAAoB,GAAG,MAAM,CAAC,YAAM,CAAC,GAAG,CAAC,uBAAuB,CAAC,CAAC,IAAI,IAAI,CAAA;AAEhF,IAAY,UAOX;AAPD,WAAY,UAAU;IACpB,mCAAqB,CAAA;IACrB,qCAAuB,CAAA;IACvB,iCAAmB,CAAA;IACnB,+BAAiB,CAAA;IACjB,+BAAiB,CAAA;IACjB,4DAA8C,CAAA,CAAC,wDAAwD;AACzG,CAAC,EAPW,UAAU,0BAAV,UAAU,QAOrB;AAaM,IAAM,IAAI,YAAV,MAAM,IAAI;IA6Hf,8BAA8B;IAC9B,KAAK,CAAC,IAAI,CAAC,OAAQ;QACjB,IAAI,EAAE,SAAS,GAAG,oBAAoB,EAAE,GAAG,OAAO,IAAI,EAAE,CAAA;QAExD,IAAI,IAAI,GAAG;YACT,QAAQ,EAAE,IAAI,CAAC,QAAQ,IAAI,IAAI,CAAC,KAAK;YACrC,KAAK,EAAE,IAAI,CAAC,KAAK;SAClB,CAAA;QAED,OAAO,MAAM,sBAAG,CAAC,IAAI,CAAC,IAAI,EAAE,sBAAM,EAAE;YAClC,SAAS;YACT,MAAM,EAAE,cAAc;YACtB,OAAO,EAAE,MA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AAE;IAClB,IAAA,oBAAK,EAAC,EAAE,QAAQ,EAAE,IAAI,EAAE,WAAW,EAAE,mDAAmD,EAAE,CAAC;sCACjF,IAAI;IAEf,8BAA8B;;uCAFf;eA3HJ,IAAI;IAXhB,IAAA,gBAAM,GAAE;IACR,IAAA,eAAK,EAAC,WAAW,EAAE,CAAC,IAAU,EAAE,EAAE,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,EAAE;QAChD,MAAM,EAAE,IAAI;KACb,CAAC;IACD,IAAA,eAAK,EAAC,WAAW,EAAE,CAAC,IAAU,EAAE,EAAE,CAAC,CAAC,IAAI,CAAC,QAAQ,CAAC,EAAE;QACnD,MAAM,EAAE,IAAI;QACZ,KAAK,EAAE,wBAAwB;KAChC,CAAC;IACD,IAAA,yBAAU,EAAC;QACV,WAAW,EAAE,oGAAoG;KAClH,CAAC;GACW,IAAI,CA6VhB","sourcesContent":["// This file defines the User entity and its GraphQL schema for authentication and authorization.\n// It includes user fields, status enum, and utility methods for password and privilege management.\n\nimport crypto from 'crypto'\nimport jwt from 'jsonwebtoken'\nimport { Directive, Field, ID, ObjectType } from 'type-graphql'\nimport { GraphQLEmailAddress } from 'graphql-scalars'\nimport {\n Column,\n CreateDateColumn,\n Entity,\n ILike,\n Index,\n JoinTable,\n ManyToMany,\n ManyToOne,\n OneToMany,\n PrimaryGeneratedColumn,\n RelationId,\n UpdateDateColumn\n} from 'typeorm'\n\nimport { config } from '@things-factory/env'\nimport { applyDomainInheritanceFilter, Domain, getRepository, InheritedValueType } from '@things-factory/shell'\n\nimport { validatePasswordByRule } from '../../controllers/utils/password-rule.js'\nimport { AuthError } from '../../errors/auth-error.js'\nimport { SECRET } from '../../utils/get-secret.js'\nimport { Role } from '../role/role.js'\nimport { Privilege } from '../privilege/privilege.js'\nimport { WebAuthCredential } from '../web-auth-credential/web-auth-credential.js'\nimport { UsersAuthProviders } from '../users-auth-providers/users-auth-providers.js'\n\nconst ORMCONFIG = config.get('ormconfig', {})\nconst DATABASE_TYPE = ORMCONFIG.type\n\nconst sessionExpirySeconds = Number(config.get('session/expirySeconds')) || '7d'\n\nexport enum UserStatus {\n INACTIVE = 'inactive', // The user account is inactive and cannot log in.\n ACTIVATED = 'activated', // The user account is active and can log in.\n DELETED = 'deleted', // The user account has been deleted.\n LOCKED = 'locked', // The user account is locked due to security reasons.\n BANNED = 'banned', // The user account is banned from the system.\n PWD_RESET_REQUIRED = 'password_reset_required' // The user must reset their password before logging in.\n}\n\n@Entity()\n@Index('ix_user_0', (user: User) => [user.email], {\n unique: true\n})\n@Index('ix_user_1', (user: User) => [user.username], {\n unique: true,\n where: '\"username\" IS NOT NULL'\n})\n@ObjectType({\n description: 'Represents a user account in the system, including authentication, roles, and domain associations.'\n})\nexport class User {\n @PrimaryGeneratedColumn('uuid')\n @Field(type => ID, { description: 'Unique identifier for the user.' })\n readonly id: string\n\n @Column({ nullable: true })\n @Field({ nullable: true, description: 'Unique username for the user.' })\n username: string\n\n @Column()\n @Field({ nullable: true, description: 'Full name of the user.' })\n name: string\n\n @Column({ nullable: true })\n @Field({ nullable: true, description: 'Optional description or note about the user.' })\n description: string\n\n @ManyToMany(type => Domain)\n @JoinTable({ name: 'users_domains' })\n @Field(type => [Domain], { description: 'Domains (organizations, companies, etc.) the user belongs to.' })\n domains?: Domain[]\n\n @Column()\n @Field(type => GraphQLEmailAddress, { description: 'Email address of the user.' })\n email: string\n\n @Directive('@privilege(category: \"security\", privilege: \"query\", domainOwnerGranted: true)')\n @Column({\n nullable: true,\n type:\n DATABASE_TYPE == 'mysql' || DATABASE_TYPE == 'mariadb'\n ? 'longtext'\n : DATABASE_TYPE == 'oracle'\n ? 'clob'\n : DATABASE_TYPE == 'mssql'\n ? 'nvarchar'\n : 'varchar',\n length: DATABASE_TYPE == 'mssql' ? 'MAX' : undefined\n })\n password: string // Hashed password for authentication\n\n @ManyToMany(type => Role, role => role.users)\n @JoinTable({ name: 'users_roles' })\n @Field(type => [Role], { description: 'Roles assigned to the user.' })\n roles?: Role[]\n\n @Column({ nullable: true })\n @Field({ nullable: true, description: 'Type or category of the user (e.g., user, application, appliance).' })\n userType: string\n\n @Column({ nullable: true })\n @Field({ nullable: true, description: 'Reference information for the user (external system, etc.).' })\n reference: string\n\n @Directive('@privilege(category: \"security\", privilege: \"query\", domainOwnerGranted: true)')\n @Column({ nullable: true })\n salt: string // Salt used for password hashing\n\n @Column({ nullable: true })\n @Field({ nullable: true, description: 'Locale or language preference for the user.' })\n locale: string\n\n @Directive('@privilege(category: \"security\", privilege: \"query\", domainOwnerGranted: true)')\n @Column({ nullable: true })\n @Field({ nullable: true, description: 'Single sign-on (SSO) identifier for federated authentication.' })\n ssoId: string\n\n @Column({\n type:\n DATABASE_TYPE == 'postgres' || DATABASE_TYPE == 'mysql' || DATABASE_TYPE == 'mariadb'\n ? 'enum'\n : DATABASE_TYPE == 'oracle'\n ? 'varchar2'\n : DATABASE_TYPE == 'mssql'\n ? 'nvarchar'\n : 'varchar',\n enum:\n DATABASE_TYPE == 'postgres' || DATABASE_TYPE == 'mysql' || DATABASE_TYPE == 'mariadb' ? UserStatus : undefined,\n length: DATABASE_TYPE == 'postgres' || DATABASE_TYPE == 'mysql' || DATABASE_TYPE == 'mariadb' ? undefined : 32,\n default: UserStatus.INACTIVE\n })\n @Field(type => String, { description: 'Current status of the user account.' })\n status: UserStatus\n\n @Column({ type: 'smallint', default: 0 })\n failCount: number // Number of failed login attempts\n\n @Column({ nullable: true })\n passwordUpdatedAt: Date // Last time the password was updated\n\n @Field({ nullable: true, description: 'Whether the user is the owner of the domain (not persisted in DB).' })\n owner: boolean /* should not be a column */\n\n @OneToMany(() => WebAuthCredential, credential => credential.user)\n credentials: WebAuthCredential[]\n\n @OneToMany(() => UsersAuthProviders, usersAuthProviders => usersAuthProviders.user)\n @Field(type => [UsersAuthProviders], {\n nullable: true,\n description: 'External authentication providers linked to the user.'\n })\n usersAuthProviders: UsersAuthProviders[]\n\n @ManyToOne(type => User, { nullable: true })\n @Field({ nullable: true, description: 'User who created this user account.' })\n creator: User\n\n @RelationId((user: User) => user.creator)\n creatorId: string\n\n @ManyToOne(type => User, { nullable: true })\n @Field({ nullable: true, description: 'User who last updated this user account.' })\n updater: User\n\n @RelationId((user: User) => user.updater)\n updaterId: string\n\n @CreateDateColumn()\n @Field({ nullable: true, description: 'Timestamp when the user account was created.' })\n createdAt: Date\n\n @UpdateDateColumn()\n @Field({ nullable: true, description: 'Timestamp when the user account was last updated.' })\n updatedAt: Date\n\n /* signing for jsonwebtoken */\n async sign(options?) {\n var { expiresIn = sessionExpirySeconds } = options || {}\n\n var user = {\n username: this.username || this.email,\n email: this.email\n }\n\n return await jwt.sign(user, SECRET, {\n expiresIn,\n issuer: 'hatiolab.com',\n subject: 'user'\n })\n }\n\n /* validate password through password rule */\n static validatePasswordByRule(password, lng) {\n validatePasswordByRule(password, lng)\n }\n\n /* generate salt */\n static generateSalt() {\n return crypto.randomBytes(16).toString('hex')\n }\n\n /* encode password */\n static encode(password: string, salt) {\n return crypto\n .createHmac('sha256', salt || SECRET)\n .update(password)\n .digest('base64')\n }\n\n /* verify password */\n static verify(hashed, password, salt) {\n return (\n hashed ==\n crypto\n .createHmac('sha256', salt || SECRET)\n .update(password)\n .digest('base64') ||\n hashed ==\n crypto\n .createHmac('sha1', salt || SECRET)\n .update(password)\n .digest('base64')\n )\n }\n\n static async checkAuthWithEmail(decoded) {\n if (!decoded?.email) {\n throw new AuthError({\n errorCode: AuthError.ERROR_CODES.USER_NOT_FOUND\n })\n }\n\n const repository = getRepository(User)\n var user = await repository.findOne({\n where: { email: decoded.email },\n relations: ['domains'],\n cache: true\n })\n\n if (!user)\n throw new AuthError({\n errorCode: AuthError.ERROR_CODES.USER_NOT_FOUND\n })\n else {\n switch (user.status) {\n case UserStatus.INACTIVE:\n throw new AuthError({\n errorCode: AuthError.ERROR_CODES.USER_NOT_ACTIVATED,\n detail: {\n email: user.email\n }\n })\n case UserStatus.LOCKED:\n throw new AuthError({\n errorCode: AuthError.ERROR_CODES.USER_LOCKED,\n detail: {\n email: user.email\n }\n })\n case UserStatus.DELETED:\n throw new AuthError({\n errorCode: AuthError.ERROR_CODES.USER_DELETED\n })\n }\n\n return user\n }\n }\n\n static async checkAuth(decoded) {\n // id 는 하위호환성을 위해 단기적으로 유지함\n const { id, username } = decoded || {}\n\n if (!id && !username) {\n throw new AuthError({\n errorCode: AuthError.ERROR_CODES.USER_NOT_FOUND\n })\n }\n\n const repository = getRepository(User)\n if (id) {\n var user = await repository.findOne({\n where: { id },\n relations: ['domains', 'credentials'],\n cache: true\n })\n } else {\n var user = await repository.findOne({\n where: { username },\n relations: ['domains', 'credentials'],\n cache: true\n })\n\n if (!user && /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/.test(username)) {\n user = await repository.findOne({\n where: {\n email: ILike(username)\n },\n relations: ['domains', 'credentials'],\n cache: true\n })\n }\n }\n\n if (!user)\n throw new AuthError({\n errorCode: AuthError.ERROR_CODES.USER_NOT_FOUND\n })\n else {\n switch (user.status) {\n case UserStatus.INACTIVE:\n throw new AuthError({\n errorCode: AuthError.ERROR_CODES.USER_NOT_ACTIVATED,\n detail: {\n email: user.email\n }\n })\n case UserStatus.LOCKED:\n throw new AuthError({\n errorCode: AuthError.ERROR_CODES.USER_LOCKED,\n detail: {\n email: user.email\n }\n })\n case UserStatus.DELETED:\n throw new AuthError({\n errorCode: AuthError.ERROR_CODES.USER_DELETED\n })\n }\n\n const { defaultPassword } = config.get('password')\n\n if (defaultPassword && user.password === this.encode(defaultPassword, user.salt)) {\n user.status = UserStatus.PWD_RESET_REQUIRED\n }\n\n return user\n }\n }\n\n /**\n * 역할은 부모 도메인으로부터 상속되므로, 권한 판정도 현재 도메인과 부모 도메인에 정의된\n * 역할을 함께 본다 (상속 규약 단일 소스: `applyDomainInheritanceFilter`).\n * 부모 역할이 형제 자식 도메인으로 번지지 않도록 하는 것은 체크인 게이트(`getUserDomains`)의\n * 멤버십 조건이 담당한다.\n */\n static async hasPrivilege(privilege: string, category: string, domain: Domain, user: User): Promise<boolean> {\n const queryBuilder = getRepository(Privilege)\n .createQueryBuilder('privilege')\n .innerJoin('privilege.roles', 'role')\n .innerJoin('role.users', 'user')\n .where('privilege.category = :category', { category })\n .andWhere('privilege.name = :privilege', { privilege })\n .andWhere('user.id = :userId', { userId: user.id })\n\n applyDomainInheritanceFilter(queryBuilder, 'role', domain, InheritedValueType.Include)\n\n const result = await queryBuilder.getCount()\n\n return result > 0\n }\n\n static async getPrivilegesByDomain(user: User, domain: Domain): Promise<{ category: string; privilege: string }[]> {\n const queryBuilder = getRepository(User)\n .createQueryBuilder('user')\n .leftJoinAndSelect('user.roles', 'role')\n .leftJoinAndSelect('role.privileges', 'privilege')\n .select(['privilege.name AS privilege', 'privilege.category AS category'])\n .where('user.id = :userId', { userId: user.id })\n\n applyDomainInheritanceFilter(queryBuilder, 'role', domain, InheritedValueType.Include)\n\n const result = await queryBuilder\n .orderBy('privilege.category')\n .addOrderBy('privilege.name')\n .getRawMany()\n\n const distinct = result.reduce((acc, current) => {\n const last = acc[acc.length - 1]\n if (!last || last.privilege !== current.privilege || last.category !== current.category) {\n acc.push(current)\n }\n return acc\n }, [])\n\n return distinct\n }\n\n /**\n * 엔티티에서 조회 유틸을 정적으로 import 하면 순환 참조가 된다\n * (user → get-user-domains → checkin-domain-facts → granted-role → role → user).\n * 순환 참조 상태에서 엔티티 데코레이터가 평가되면 type-graphql 이 타입을 추론하지 못해\n * 모듈 로드 자체가 실패하므로, 호출 시점에 지연 로드한다.\n */\n static async getDomainsWithPrivilege(privilege: string, category: string, user: User) {\n const { getDomainsWithPrivilege } = await import('../../utils/get-user-domains.js')\n\n return getDomainsWithPrivilege(user, privilege, category)\n }\n}\n"]}
1
+ {"version":3,"file":"user.js","sourceRoot":"","sources":["../../../server/service/user/user.ts"],"names":[],"mappings":";AAAA,iGAAiG;AACjG,mGAAmG;;;;;AAEnG,4DAA2B;AAC3B,wEAA8B;AAC9B,+CAA+D;AAC/D,qDAAqD;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,EAAE,IAAI,EAAE,WAAW,EAAE,0CAA0C,EAAE,CAAC;sCAC1E,IAAI;qCAAA;AAGb;IADC,IAAA,oBAAU,EAAC,CAAC,IAAU,EAAE,EAAE,CAAC,IAAI,CAAC,OAAO,CAAC;;uCACxB;AAIjB;IAFC,IAAA,0BAAgB,GAAE;IAClB,IAAA,oBAAK,EAAC,EAAE,QAAQ,EAAE,IAAI,EAAE,WAAW,EAAE,8CAA8C,EAAE,CAAC;sCAC5E,IAAI;uCAAA;AAIf;IAFC,IAAA,0BAAgB,GAAE;IAClB,IAAA,oBAAK,EAAC,EAAE,QAAQ,EAAE,IAAI,EAAE,WAAW,EAAE,mDAAmD,EAAE,CAAC;sCACjF,IAAI;IAEf,8BAA8B;;uCAFf;eA1IJ,IAAI;IAXhB,IAAA,gBAAM,GAAE;IACR,IAAA,eAAK,EAAC,WAAW,EAAE,CAAC,IAAU,EAAE,EAAE,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,EAAE;QAChD,MAAM,EAAE,IAAI;KACb,CAAC;IACD,IAAA,eAAK,EAAC,WAAW,EAAE,CAAC,IAAU,EAAE,EAAE,CAAC,CAAC,IAAI,CAAC,QAAQ,CAAC,EAAE;QACnD,MAAM,EAAE,IAAI;QACZ,KAAK,EAAE,wBAAwB;KAChC,CAAC;IACD,IAAA,yBAAU,EAAC;QACV,WAAW,EAAE,oGAAoG;KAClH,CAAC;GACW,IAAI,CAoYhB","sourcesContent":["// This file defines the User entity and its GraphQL schema for authentication and authorization.\n// It includes user fields, status enum, and utility methods for password and privilege management.\n\nimport crypto from 'crypto'\nimport jwt from 'jsonwebtoken'\nimport { Directive, Field, ID, ObjectType } from 'type-graphql'\nimport { GraphQLEmailAddress } from 'graphql-scalars'\nimport {\n Column,\n CreateDateColumn,\n Entity,\n ILike,\n Index,\n JoinTable,\n ManyToMany,\n ManyToOne,\n OneToMany,\n PrimaryGeneratedColumn,\n RelationId,\n UpdateDateColumn\n} from 'typeorm'\n\nimport { config } from '@things-factory/env'\nimport { applyDomainInheritanceFilter, Domain, getRepository, InheritedValueType } from '@things-factory/shell'\n\nimport { validatePasswordByRule } from '../../controllers/utils/password-rule.js'\nimport { isAccountLocked } from '../../utils/account-lock-rule.js'\nimport { lockDurationMinutes } from '../../utils/lock-duration.js'\nimport { AuthError } from '../../errors/auth-error.js'\nimport { SECRET } from '../../utils/get-secret.js'\nimport { Role } from '../role/role.js'\nimport { Privilege } from '../privilege/privilege.js'\nimport { WebAuthCredential } from '../web-auth-credential/web-auth-credential.js'\nimport { UsersAuthProviders } from '../users-auth-providers/users-auth-providers.js'\n\nconst ORMCONFIG = config.get('ormconfig', {})\nconst DATABASE_TYPE = ORMCONFIG.type\n\nconst sessionExpirySeconds = Number(config.get('session/expirySeconds')) || '7d'\n\nexport enum UserStatus {\n INACTIVE = 'inactive', // The user account is inactive and cannot log in.\n ACTIVATED = 'activated', // The user account is active and can log in.\n DELETED = 'deleted', // The user account has been deleted.\n LOCKED = 'locked', // The user account is locked due to security reasons.\n BANNED = 'banned', // The user account is banned from the system.\n PWD_RESET_REQUIRED = 'password_reset_required' // The user must reset their password before logging in.\n}\n\n@Entity()\n@Index('ix_user_0', (user: User) => [user.email], {\n unique: true\n})\n@Index('ix_user_1', (user: User) => [user.username], {\n unique: true,\n where: '\"username\" IS NOT NULL'\n})\n@ObjectType({\n description: 'Represents a user account in the system, including authentication, roles, and domain associations.'\n})\nexport class User {\n @PrimaryGeneratedColumn('uuid')\n @Field(type => ID, { description: 'Unique identifier for the user.' })\n readonly id: string\n\n @Column({ nullable: true })\n @Field({ nullable: true, description: 'Unique username for the user.' })\n username: string\n\n @Column()\n @Field({ nullable: true, description: 'Full name of the user.' })\n name: string\n\n @Column({ nullable: true })\n @Field({ nullable: true, description: 'Optional description or note about the user.' })\n description: string\n\n @ManyToMany(type => Domain)\n @JoinTable({ name: 'users_domains' })\n @Field(type => [Domain], { description: 'Domains (organizations, companies, etc.) the user belongs to.' })\n domains?: Domain[]\n\n @Column()\n @Field(type => GraphQLEmailAddress, { description: 'Email address of the user.' })\n email: string\n\n @Directive('@privilege(category: \"security\", privilege: \"query\", domainOwnerGranted: true)')\n @Column({\n nullable: true,\n type:\n DATABASE_TYPE == 'mysql' || DATABASE_TYPE == 'mariadb'\n ? 'longtext'\n : DATABASE_TYPE == 'oracle'\n ? 'clob'\n : DATABASE_TYPE == 'mssql'\n ? 'nvarchar'\n : 'varchar',\n length: DATABASE_TYPE == 'mssql' ? 'MAX' : undefined\n })\n password: string // Hashed password for authentication\n\n @ManyToMany(type => Role, role => role.users)\n @JoinTable({ name: 'users_roles' })\n @Field(type => [Role], { description: 'Roles assigned to the user.' })\n roles?: Role[]\n\n @Column({ nullable: true })\n @Field({ nullable: true, description: 'Type or category of the user (e.g., user, application, appliance).' })\n userType: string\n\n @Column({ nullable: true })\n @Field({ nullable: true, description: 'Reference information for the user (external system, etc.).' })\n reference: string\n\n @Directive('@privilege(category: \"security\", privilege: \"query\", domainOwnerGranted: true)')\n @Column({ nullable: true })\n salt: string // Salt used for password hashing\n\n @Column({ nullable: true })\n @Field({ nullable: true, description: 'Locale or language preference for the user.' })\n locale: string\n\n @Directive('@privilege(category: \"security\", privilege: \"query\", domainOwnerGranted: true)')\n @Column({ nullable: true })\n @Field({ nullable: true, description: 'Single sign-on (SSO) identifier for federated authentication.' })\n ssoId: string\n\n @Column({\n type:\n DATABASE_TYPE == 'postgres' || DATABASE_TYPE == 'mysql' || DATABASE_TYPE == 'mariadb'\n ? 'enum'\n : DATABASE_TYPE == 'oracle'\n ? 'varchar2'\n : DATABASE_TYPE == 'mssql'\n ? 'nvarchar'\n : 'varchar',\n enum:\n DATABASE_TYPE == 'postgres' || DATABASE_TYPE == 'mysql' || DATABASE_TYPE == 'mariadb' ? UserStatus : undefined,\n length: DATABASE_TYPE == 'postgres' || DATABASE_TYPE == 'mysql' || DATABASE_TYPE == 'mariadb' ? undefined : 32,\n default: UserStatus.INACTIVE\n })\n @Field(type => String, { description: 'Current status of the user account.' })\n status: UserStatus\n\n @Column({ type: 'smallint', default: 0 })\n failCount: number // Number of failed login attempts\n\n @Column({ nullable: true })\n passwordUpdatedAt: Date // Last time the password was updated\n\n /*\n * When the account was locked, so the lock can lift on its own.\n *\n * The decision of whether a lock is still in effect lives in one place —\n * `utils/account-lock-rule.ts` — because two callers ask: `signin`, and `checkAuth` on every\n * request. A row locked before this column existed has no value here, and the rule keeps such a\n * lock in effect rather than releasing it, so nothing opens quietly.\n */\n @Column({ nullable: true })\n @Field({\n nullable: true,\n description: 'When the account was locked. With the configured lock duration this says when it lifts.'\n })\n lockedAt: Date\n\n @Field({ nullable: true, description: 'Whether the user is the owner of the domain (not persisted in DB).' })\n owner: boolean /* should not be a column */\n\n @OneToMany(() => WebAuthCredential, credential => credential.user)\n credentials: WebAuthCredential[]\n\n @OneToMany(() => UsersAuthProviders, usersAuthProviders => usersAuthProviders.user)\n @Field(type => [UsersAuthProviders], {\n nullable: true,\n description: 'External authentication providers linked to the user.'\n })\n usersAuthProviders: UsersAuthProviders[]\n\n @ManyToOne(type => User, { nullable: true })\n @Field({ nullable: true, description: 'User who created this user account.' })\n creator: User\n\n @RelationId((user: User) => user.creator)\n creatorId: string\n\n @ManyToOne(type => User, { nullable: true })\n @Field({ nullable: true, description: 'User who last updated this user account.' })\n updater: User\n\n @RelationId((user: User) => user.updater)\n updaterId: string\n\n @CreateDateColumn()\n @Field({ nullable: true, description: 'Timestamp when the user account was created.' })\n createdAt: Date\n\n @UpdateDateColumn()\n @Field({ nullable: true, description: 'Timestamp when the user account was last updated.' })\n updatedAt: Date\n\n /* signing for jsonwebtoken */\n async sign(options?) {\n var { expiresIn = sessionExpirySeconds } = options || {}\n\n var user = {\n username: this.username || this.email,\n email: this.email\n }\n\n return await jwt.sign(user, SECRET, {\n expiresIn,\n issuer: 'hatiolab.com',\n subject: 'user'\n })\n }\n\n /* validate password through password rule */\n static validatePasswordByRule(password, lng) {\n validatePasswordByRule(password, lng)\n }\n\n /* generate salt */\n static generateSalt() {\n return crypto.randomBytes(16).toString('hex')\n }\n\n /* encode password */\n static encode(password: string, salt) {\n return crypto\n .createHmac('sha256', salt || SECRET)\n .update(password)\n .digest('base64')\n }\n\n /* verify password */\n static verify(hashed, password, salt) {\n return (\n hashed ==\n crypto\n .createHmac('sha256', salt || SECRET)\n .update(password)\n .digest('base64') ||\n hashed ==\n crypto\n .createHmac('sha1', salt || SECRET)\n .update(password)\n .digest('base64')\n )\n }\n\n static async checkAuthWithEmail(decoded) {\n if (!decoded?.email) {\n throw new AuthError({\n errorCode: AuthError.ERROR_CODES.USER_NOT_FOUND\n })\n }\n\n const repository = getRepository(User)\n var user = await repository.findOne({\n where: { email: decoded.email },\n relations: ['domains'],\n cache: true\n })\n\n if (!user)\n throw new AuthError({\n errorCode: AuthError.ERROR_CODES.USER_NOT_FOUND\n })\n else {\n switch (user.status) {\n case UserStatus.INACTIVE:\n throw new AuthError({\n errorCode: AuthError.ERROR_CODES.USER_NOT_ACTIVATED,\n detail: {\n email: user.email\n }\n })\n case UserStatus.LOCKED:\n /*\n * 잠금이 아직 유효한지는 `utils/account-lock-rule.ts` 한 곳이 판정한다 — `signin` 과\n * 이 자리가 각자 판단하면 로그인은 되는데 요청은 거절되는 상태가 생긴다.\n *\n * **여기서는 행을 고치지 않는다.** 매 요청 지나는 경로라 쓰기를 얹지 않는다. 판정이\n * 「풀렸다」면 통과시키고, 행 정리(`ACTIVATED` · `failCount` 0 · `lockedAt` 비움)는\n * 다음 `signin` 이 한다.\n */\n if (isAccountLocked(user, new Date(), lockDurationMinutes())) {\n throw new AuthError({\n errorCode: AuthError.ERROR_CODES.USER_LOCKED,\n detail: {\n email: user.email\n }\n })\n }\n break\n case UserStatus.DELETED:\n throw new AuthError({\n errorCode: AuthError.ERROR_CODES.USER_DELETED\n })\n }\n\n return user\n }\n }\n\n static async checkAuth(decoded) {\n // id 는 하위호환성을 위해 단기적으로 유지함\n const { id, username } = decoded || {}\n\n if (!id && !username) {\n throw new AuthError({\n errorCode: AuthError.ERROR_CODES.USER_NOT_FOUND\n })\n }\n\n const repository = getRepository(User)\n if (id) {\n var user = await repository.findOne({\n where: { id },\n relations: ['domains', 'credentials'],\n cache: true\n })\n } else {\n var user = await repository.findOne({\n where: { username },\n relations: ['domains', 'credentials'],\n cache: true\n })\n\n if (!user && /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/.test(username)) {\n user = await repository.findOne({\n where: {\n email: ILike(username)\n },\n relations: ['domains', 'credentials'],\n cache: true\n })\n }\n }\n\n if (!user)\n throw new AuthError({\n errorCode: AuthError.ERROR_CODES.USER_NOT_FOUND\n })\n else {\n switch (user.status) {\n case UserStatus.INACTIVE:\n throw new AuthError({\n errorCode: AuthError.ERROR_CODES.USER_NOT_ACTIVATED,\n detail: {\n email: user.email\n }\n })\n case UserStatus.LOCKED:\n /*\n * 잠금이 아직 유효한지는 `utils/account-lock-rule.ts` 한 곳이 판정한다 — `signin` 과\n * 이 자리가 각자 판단하면 로그인은 되는데 요청은 거절되는 상태가 생긴다.\n *\n * **여기서는 행을 고치지 않는다.** 매 요청 지나는 경로라 쓰기를 얹지 않는다. 판정이\n * 「풀렸다」면 통과시키고, 행 정리(`ACTIVATED` · `failCount` 0 · `lockedAt` 비움)는\n * 다음 `signin` 이 한다.\n */\n if (isAccountLocked(user, new Date(), lockDurationMinutes())) {\n throw new AuthError({\n errorCode: AuthError.ERROR_CODES.USER_LOCKED,\n detail: {\n email: user.email\n }\n })\n }\n break\n case UserStatus.DELETED:\n throw new AuthError({\n errorCode: AuthError.ERROR_CODES.USER_DELETED\n })\n }\n\n /* 설정이 없으면 `{}` 로 — 기본값 없이 구조 분해하면 `password` 를 설정하지 않은 배포에서\n 이 줄이 던진다. `password-rule.ts` 도 같은 자리에서 대비를 두고 있다. */\n const { defaultPassword } = config.get('password', {})\n\n if (defaultPassword && user.password === this.encode(defaultPassword, user.salt)) {\n user.status = UserStatus.PWD_RESET_REQUIRED\n }\n\n return user\n }\n }\n\n /**\n * 역할은 부모 도메인으로부터 상속되므로, 권한 판정도 현재 도메인과 부모 도메인에 정의된\n * 역할을 함께 본다 (상속 규약 단일 소스: `applyDomainInheritanceFilter`).\n * 부모 역할이 형제 자식 도메인으로 번지지 않도록 하는 것은 체크인 게이트(`getUserDomains`)의\n * 멤버십 조건이 담당한다.\n */\n static async hasPrivilege(privilege: string, category: string, domain: Domain, user: User): Promise<boolean> {\n const queryBuilder = getRepository(Privilege)\n .createQueryBuilder('privilege')\n .innerJoin('privilege.roles', 'role')\n .innerJoin('role.users', 'user')\n .where('privilege.category = :category', { category })\n .andWhere('privilege.name = :privilege', { privilege })\n .andWhere('user.id = :userId', { userId: user.id })\n\n applyDomainInheritanceFilter(queryBuilder, 'role', domain, InheritedValueType.Include)\n\n const result = await queryBuilder.getCount()\n\n return result > 0\n }\n\n static async getPrivilegesByDomain(user: User, domain: Domain): Promise<{ category: string; privilege: string }[]> {\n const queryBuilder = getRepository(User)\n .createQueryBuilder('user')\n .leftJoinAndSelect('user.roles', 'role')\n .leftJoinAndSelect('role.privileges', 'privilege')\n .select(['privilege.name AS privilege', 'privilege.category AS category'])\n .where('user.id = :userId', { userId: user.id })\n\n applyDomainInheritanceFilter(queryBuilder, 'role', domain, InheritedValueType.Include)\n\n const result = await queryBuilder\n .orderBy('privilege.category')\n .addOrderBy('privilege.name')\n .getRawMany()\n\n const distinct = result.reduce((acc, current) => {\n const last = acc[acc.length - 1]\n if (!last || last.privilege !== current.privilege || last.category !== current.category) {\n acc.push(current)\n }\n return acc\n }, [])\n\n return distinct\n }\n\n /**\n * 엔티티에서 조회 유틸을 정적으로 import 하면 순환 참조가 된다\n * (user → get-user-domains → checkin-domain-facts → granted-role → role → user).\n * 순환 참조 상태에서 엔티티 데코레이터가 평가되면 type-graphql 이 타입을 추론하지 못해\n * 모듈 로드 자체가 실패하므로, 호출 시점에 지연 로드한다.\n */\n static async getDomainsWithPrivilege(privilege: string, category: string, user: User) {\n const { getDomainsWithPrivilege } = await import('../../utils/get-user-domains.js')\n\n return getDomainsWithPrivilege(user, privilege, category)\n }\n}\n"]}