erp-login 0.2.0__tar.gz

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.

Potentially problematic release.


This version of erp-login might be problematic. Click here for more details.

@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,210 @@
1
+ Metadata-Version: 2.4
2
+ Name: erp_login
3
+ Version: 0.2.0
4
+ Summary: Unofficial headless login for the IIT Kharagpur ERP: handles password, security question and emailed Gmail OTP, then prints the session as JSON.
5
+ Author-email: Krishna Singha <krishnasingha.dev@gmail.com>
6
+ License-Expression: Apache-2.0
7
+ Project-URL: Source, https://github.com/krishna-singha/erp-login
8
+ Keywords: iit-kharagpur,erp,login,otp,gmail
9
+ Classifier: Environment :: Console
10
+ Classifier: Operating System :: POSIX :: Linux
11
+ Classifier: Programming Language :: Python :: 3
12
+ Requires-Python: >=3.10
13
+ Description-Content-Type: text/markdown
14
+ License-File: LICENSE
15
+ Dynamic: license-file
16
+
17
+ # erp_login
18
+
19
+ Zero-dependency headless login for the IIT Kharagpur ERP (`erp.iitkgp.ac.in`).
20
+ Handles password, security question, and emailed Gmail OTP, then returns or prints **only the session fields you request**.
21
+
22
+ - **Zero runtime dependencies** — Python `>=3.10` standard library only.
23
+ - **Least-privilege field selection** — request only `sso_token`, `cookies`, `cookie_header`, or `issued_at`. Required in the library; defaults to `cookies` in the CLI.
24
+ - **Scope filtering** — restrict cookies to `cdc`, `erp`, `sso`, or `all`.
25
+ - **Skips unnecessary requests** — skips the CDC warm-up request when CDC cookies aren't needed.
26
+ - **Redacted `repr`** — `LoginResult.__repr__` and `__str__` mask `sso_token`, `cookies`, and `cookie_header` as `***` so accidental `print(result)` calls don't leak secrets.
27
+ - **Hardened networking** — TLS 1.2+, blocks HTTPS-to-HTTP downgrades and off-domain redirects (`*.iitkgp.ac.in` / `*.googleapis.com`), disables core dumps (`RLIMIT_CORE = 0`), and enforces a 90s deadline.
28
+
29
+ ---
30
+
31
+ ## Installation
32
+
33
+ ```bash
34
+ pip install erp_login
35
+ ```
36
+
37
+ For CLI-only usage:
38
+
39
+ ```bash
40
+ pipx install erp_login
41
+ # or: uv tool install erp_login
42
+ ```
43
+
44
+ ---
45
+
46
+ ## Quick Start
47
+
48
+ 1. Set your credentials as environment variables (or via systemd `CREDENTIALS_DIRECTORY`):
49
+
50
+ ```bash
51
+ export ERP_USER="YOUR_ROLL_NO"
52
+ export ERP_PASS="YOUR_PASSWORD"
53
+ export ERP_ANSWERS='{"Security Question 1": "Answer 1", "Security Question 2": "Answer 2", "Security Question 3": "Answer 3"}'
54
+ export GMAIL_OAUTH_JSON='{"client_id": "...", "client_secret": "...", "refresh_token": "..."}'
55
+ ```
56
+
57
+ 2. Run the CLI:
58
+
59
+ ```bash
60
+ erp_login
61
+ # or: python3 -m erp_login
62
+ ```
63
+
64
+ `stdout` prints one JSON line:
65
+
66
+ ```json
67
+ {"v": 1, "cookies": [...]}
68
+ ```
69
+
70
+ Progress and errors are written to `stderr` (never secrets).
71
+
72
+ ---
73
+
74
+ ## CLI Reference
75
+
76
+ ```text
77
+ erp_login [--fields FIELDS ...] [--scope {all,cdc,erp,sso}]
78
+ ```
79
+
80
+ - `--fields`: Space- or comma-separated list of fields to include (default: `cookies`).
81
+ - Selectable fields: `sso_token`, `cookies`, `cookie_header`, `issued_at`
82
+ - `--scope`: Filter `cookies` and `cookie_header` by cookie path prefix:
83
+ - `all` (default): all cookies
84
+ - `cdc`: `/TrainingPlacementSSO`
85
+ - `erp`: `/IIT_ERP3`
86
+ - `sso`: `/SSOAdministration`
87
+
88
+ ### Examples
89
+
90
+ ```bash
91
+ # Only sso_token (skips the CDC warm-up request)
92
+ erp_login --fields sso_token
93
+
94
+ # Only CDC cookies + ready-to-use Cookie header + timestamp
95
+ erp_login --fields cookies cookie_header issued_at --scope cdc
96
+
97
+ # Comma-separated syntax also works
98
+ erp_login --fields sso_token,issued_at
99
+ ```
100
+
101
+ ### Exit Codes
102
+
103
+ | Code | Error Type | Meaning & Action |
104
+ | ---- | ---------- | ---------------- |
105
+ | `0` | — | Success. Single-line JSON on `stdout`. |
106
+ | `10` | `Transient` | Safe to retry with backoff (OTP timeout/mismatch, network/5xx/429, 90s deadline). |
107
+ | `20` | `Fatal` | **Do not retry blindly** — wrong password/security answer, invalid roll number, missing/malformed config, revoked Gmail token, or invalid `--fields`/`--scope`. |
108
+ | `1` | Unexpected | Unhandled exception. Set `DOOT_DEBUG=1` to print traceback to `stderr`. |
109
+
110
+ ---
111
+
112
+ ## Python Library Usage
113
+
114
+ `fields` is **required** (keyword-only) in `erp_login.login(...)` so callers never receive all session data by accident.
115
+
116
+ ```python
117
+ from erp_login import Fatal, GmailOtp, Transient, config, login
118
+
119
+ creds = config.load()
120
+
121
+ try:
122
+ res = login(
123
+ creds,
124
+ GmailOtp(creds.gmail),
125
+ fields=("cookies", "cookie_header", "issued_at"),
126
+ scope="cdc",
127
+ )
128
+ except Transient as e:
129
+ ... # retry later with backoff
130
+ except Fatal as e:
131
+ ... # fix credentials/config; do not retry blindly
132
+
133
+ print(res) # LoginResult({'v': 1, 'issued_at': ..., 'cookies': '***', 'cookie_header': '***'})
134
+ cookie_header = res["cookie_header"]
135
+ ```
136
+
137
+ ### Passing Credentials Directly (without env vars)
138
+
139
+ ```python
140
+ from erp_login import Creds, GmailOtp, login
141
+
142
+ creds = Creds(
143
+ user="YOUR_ROLL_NO",
144
+ password="YOUR_PASSWORD",
145
+ answers={"Security Question 1": "Answer 1"},
146
+ gmail={"client_id": "...", "client_secret": "...", "refresh_token": "..."},
147
+ )
148
+ res = login(creds, GmailOtp(creds.gmail), fields=("sso_token",))
149
+ ```
150
+
151
+ ### Custom OTP Source
152
+
153
+ `login()` accepts any object implementing the `OtpSource` protocol (`mark() -> None`, `wait() -> str`):
154
+
155
+ ```python
156
+ class ManualOtp:
157
+ def mark(self) -> None:
158
+ pass
159
+
160
+ def wait(self) -> str:
161
+ return input("Enter 6-digit ERP OTP: ").strip()
162
+
163
+ res = login(creds, ManualOtp(), fields=("sso_token",))
164
+ ```
165
+
166
+ ---
167
+
168
+ ## Output Schema (`v: 1`)
169
+
170
+ `LoginResult` is a `dict` subclass containing `"v": 1` plus **only** the requested fields:
171
+
172
+ | Field | Type | Description |
173
+ | ----- | ---- | ----------- |
174
+ | `v` | `int` | Always `1` (schema version). |
175
+ | `sso_token` | `str` | The `ssoToken` value. |
176
+ | `cookies` | `list[dict]` | List of `{name, value, domain, path, expires, secure}` dicts. |
177
+ | `cookie_header` | `str` | Ready-to-use `name=value; ...` string built from the scoped cookies. |
178
+ | `issued_at` | `int` | Unix epoch timestamp (seconds). |
179
+
180
+ Credentials (`password`, `answers`, `otp`, `gmail`) are never selectable and raise `Fatal` if requested.
181
+
182
+ ---
183
+
184
+ ## Configuration
185
+
186
+ `config.load()` checks `$CREDENTIALS_DIRECTORY` (for systemd `LoadCredential` / `LoadCredentialEncrypted`) first, then falls back to environment variables:
187
+
188
+ | systemd credential | Env var | Format |
189
+ | ------------------ | ------- | ------ |
190
+ | `erp_user` | `ERP_USER` | Roll number string |
191
+ | `erp_pass` | `ERP_PASS` | ERP password string |
192
+ | `erp_answers` | `ERP_ANSWERS` | JSON object `{question: answer}` |
193
+ | `gmail_oauth` | `GMAIL_OAUTH_JSON` | JSON object `{client_id, client_secret, refresh_token}` |
194
+
195
+ Optional environment variables:
196
+ - `DOOT_DEBUG=1`: Print full traceback to `stderr` on unexpected errors (exit code `1`).
197
+ - `DOOT_CA_FILE=/path/to/ca.pem`: Custom CA bundle for TLS verification.
198
+
199
+ ---
200
+
201
+ ## Security & Disclaimer
202
+
203
+ - Field selection enforces least privilege between callers, but **anyone holding `cookies`, `cookie_header`, or `sso_token` can act as you on ERP**. Store credentials with `0600` permissions (or systemd encrypted credentials), never log stdout JSON, and pass output over private pipes only.
204
+ - Unofficial tool; not affiliated with IIT Kharagpur.
205
+
206
+ ---
207
+
208
+ ## License
209
+
210
+ Apache License 2.0 — see `LICENSE` for details.
@@ -0,0 +1,194 @@
1
+ # erp_login
2
+
3
+ Zero-dependency headless login for the IIT Kharagpur ERP (`erp.iitkgp.ac.in`).
4
+ Handles password, security question, and emailed Gmail OTP, then returns or prints **only the session fields you request**.
5
+
6
+ - **Zero runtime dependencies** — Python `>=3.10` standard library only.
7
+ - **Least-privilege field selection** — request only `sso_token`, `cookies`, `cookie_header`, or `issued_at`. Required in the library; defaults to `cookies` in the CLI.
8
+ - **Scope filtering** — restrict cookies to `cdc`, `erp`, `sso`, or `all`.
9
+ - **Skips unnecessary requests** — skips the CDC warm-up request when CDC cookies aren't needed.
10
+ - **Redacted `repr`** — `LoginResult.__repr__` and `__str__` mask `sso_token`, `cookies`, and `cookie_header` as `***` so accidental `print(result)` calls don't leak secrets.
11
+ - **Hardened networking** — TLS 1.2+, blocks HTTPS-to-HTTP downgrades and off-domain redirects (`*.iitkgp.ac.in` / `*.googleapis.com`), disables core dumps (`RLIMIT_CORE = 0`), and enforces a 90s deadline.
12
+
13
+ ---
14
+
15
+ ## Installation
16
+
17
+ ```bash
18
+ pip install erp_login
19
+ ```
20
+
21
+ For CLI-only usage:
22
+
23
+ ```bash
24
+ pipx install erp_login
25
+ # or: uv tool install erp_login
26
+ ```
27
+
28
+ ---
29
+
30
+ ## Quick Start
31
+
32
+ 1. Set your credentials as environment variables (or via systemd `CREDENTIALS_DIRECTORY`):
33
+
34
+ ```bash
35
+ export ERP_USER="YOUR_ROLL_NO"
36
+ export ERP_PASS="YOUR_PASSWORD"
37
+ export ERP_ANSWERS='{"Security Question 1": "Answer 1", "Security Question 2": "Answer 2", "Security Question 3": "Answer 3"}'
38
+ export GMAIL_OAUTH_JSON='{"client_id": "...", "client_secret": "...", "refresh_token": "..."}'
39
+ ```
40
+
41
+ 2. Run the CLI:
42
+
43
+ ```bash
44
+ erp_login
45
+ # or: python3 -m erp_login
46
+ ```
47
+
48
+ `stdout` prints one JSON line:
49
+
50
+ ```json
51
+ {"v": 1, "cookies": [...]}
52
+ ```
53
+
54
+ Progress and errors are written to `stderr` (never secrets).
55
+
56
+ ---
57
+
58
+ ## CLI Reference
59
+
60
+ ```text
61
+ erp_login [--fields FIELDS ...] [--scope {all,cdc,erp,sso}]
62
+ ```
63
+
64
+ - `--fields`: Space- or comma-separated list of fields to include (default: `cookies`).
65
+ - Selectable fields: `sso_token`, `cookies`, `cookie_header`, `issued_at`
66
+ - `--scope`: Filter `cookies` and `cookie_header` by cookie path prefix:
67
+ - `all` (default): all cookies
68
+ - `cdc`: `/TrainingPlacementSSO`
69
+ - `erp`: `/IIT_ERP3`
70
+ - `sso`: `/SSOAdministration`
71
+
72
+ ### Examples
73
+
74
+ ```bash
75
+ # Only sso_token (skips the CDC warm-up request)
76
+ erp_login --fields sso_token
77
+
78
+ # Only CDC cookies + ready-to-use Cookie header + timestamp
79
+ erp_login --fields cookies cookie_header issued_at --scope cdc
80
+
81
+ # Comma-separated syntax also works
82
+ erp_login --fields sso_token,issued_at
83
+ ```
84
+
85
+ ### Exit Codes
86
+
87
+ | Code | Error Type | Meaning & Action |
88
+ | ---- | ---------- | ---------------- |
89
+ | `0` | — | Success. Single-line JSON on `stdout`. |
90
+ | `10` | `Transient` | Safe to retry with backoff (OTP timeout/mismatch, network/5xx/429, 90s deadline). |
91
+ | `20` | `Fatal` | **Do not retry blindly** — wrong password/security answer, invalid roll number, missing/malformed config, revoked Gmail token, or invalid `--fields`/`--scope`. |
92
+ | `1` | Unexpected | Unhandled exception. Set `DOOT_DEBUG=1` to print traceback to `stderr`. |
93
+
94
+ ---
95
+
96
+ ## Python Library Usage
97
+
98
+ `fields` is **required** (keyword-only) in `erp_login.login(...)` so callers never receive all session data by accident.
99
+
100
+ ```python
101
+ from erp_login import Fatal, GmailOtp, Transient, config, login
102
+
103
+ creds = config.load()
104
+
105
+ try:
106
+ res = login(
107
+ creds,
108
+ GmailOtp(creds.gmail),
109
+ fields=("cookies", "cookie_header", "issued_at"),
110
+ scope="cdc",
111
+ )
112
+ except Transient as e:
113
+ ... # retry later with backoff
114
+ except Fatal as e:
115
+ ... # fix credentials/config; do not retry blindly
116
+
117
+ print(res) # LoginResult({'v': 1, 'issued_at': ..., 'cookies': '***', 'cookie_header': '***'})
118
+ cookie_header = res["cookie_header"]
119
+ ```
120
+
121
+ ### Passing Credentials Directly (without env vars)
122
+
123
+ ```python
124
+ from erp_login import Creds, GmailOtp, login
125
+
126
+ creds = Creds(
127
+ user="YOUR_ROLL_NO",
128
+ password="YOUR_PASSWORD",
129
+ answers={"Security Question 1": "Answer 1"},
130
+ gmail={"client_id": "...", "client_secret": "...", "refresh_token": "..."},
131
+ )
132
+ res = login(creds, GmailOtp(creds.gmail), fields=("sso_token",))
133
+ ```
134
+
135
+ ### Custom OTP Source
136
+
137
+ `login()` accepts any object implementing the `OtpSource` protocol (`mark() -> None`, `wait() -> str`):
138
+
139
+ ```python
140
+ class ManualOtp:
141
+ def mark(self) -> None:
142
+ pass
143
+
144
+ def wait(self) -> str:
145
+ return input("Enter 6-digit ERP OTP: ").strip()
146
+
147
+ res = login(creds, ManualOtp(), fields=("sso_token",))
148
+ ```
149
+
150
+ ---
151
+
152
+ ## Output Schema (`v: 1`)
153
+
154
+ `LoginResult` is a `dict` subclass containing `"v": 1` plus **only** the requested fields:
155
+
156
+ | Field | Type | Description |
157
+ | ----- | ---- | ----------- |
158
+ | `v` | `int` | Always `1` (schema version). |
159
+ | `sso_token` | `str` | The `ssoToken` value. |
160
+ | `cookies` | `list[dict]` | List of `{name, value, domain, path, expires, secure}` dicts. |
161
+ | `cookie_header` | `str` | Ready-to-use `name=value; ...` string built from the scoped cookies. |
162
+ | `issued_at` | `int` | Unix epoch timestamp (seconds). |
163
+
164
+ Credentials (`password`, `answers`, `otp`, `gmail`) are never selectable and raise `Fatal` if requested.
165
+
166
+ ---
167
+
168
+ ## Configuration
169
+
170
+ `config.load()` checks `$CREDENTIALS_DIRECTORY` (for systemd `LoadCredential` / `LoadCredentialEncrypted`) first, then falls back to environment variables:
171
+
172
+ | systemd credential | Env var | Format |
173
+ | ------------------ | ------- | ------ |
174
+ | `erp_user` | `ERP_USER` | Roll number string |
175
+ | `erp_pass` | `ERP_PASS` | ERP password string |
176
+ | `erp_answers` | `ERP_ANSWERS` | JSON object `{question: answer}` |
177
+ | `gmail_oauth` | `GMAIL_OAUTH_JSON` | JSON object `{client_id, client_secret, refresh_token}` |
178
+
179
+ Optional environment variables:
180
+ - `DOOT_DEBUG=1`: Print full traceback to `stderr` on unexpected errors (exit code `1`).
181
+ - `DOOT_CA_FILE=/path/to/ca.pem`: Custom CA bundle for TLS verification.
182
+
183
+ ---
184
+
185
+ ## Security & Disclaimer
186
+
187
+ - Field selection enforces least privilege between callers, but **anyone holding `cookies`, `cookie_header`, or `sso_token` can act as you on ERP**. Store credentials with `0600` permissions (or systemd encrypted credentials), never log stdout JSON, and pass output over private pipes only.
188
+ - Unofficial tool; not affiliated with IIT Kharagpur.
189
+
190
+ ---
191
+
192
+ ## License
193
+
194
+ Apache License 2.0 — see `LICENSE` for details.
@@ -0,0 +1,15 @@
1
+ from .config import Creds
2
+ from .erp import LoginResult, SCOPES, SELECTABLE_FIELDS, login
3
+ from .errors import Fatal, Transient
4
+ from .otp import GmailOtp
5
+
6
+ __all__ = [
7
+ "Creds",
8
+ "Fatal",
9
+ "GmailOtp",
10
+ "LoginResult",
11
+ "SCOPES",
12
+ "SELECTABLE_FIELDS",
13
+ "Transient",
14
+ "login",
15
+ ]
@@ -0,0 +1,74 @@
1
+ """One-shot ERP login.
2
+
3
+ stdout: one JSON line {"v": 1, ...<selected fields>} (secret)
4
+ stderr: progress and errors, never secrets.
5
+ Exit: 0 ok | 10 transient (retry with backoff) | 20 fatal (wrong password/answer, bad config:
6
+ do not retry blindly, it can lock the account) | 1 bug
7
+ """
8
+ import argparse
9
+ import json
10
+ import os
11
+ import resource
12
+ import signal
13
+ import sys
14
+ import traceback
15
+ from collections.abc import Collection
16
+
17
+ from . import config, erp, otp
18
+ from .errors import Fatal, Transient
19
+ from .log import log
20
+
21
+ DEADLINE_S = 90
22
+ OK, UNEXPECTED, TRANSIENT, FATAL = 0, 1, 10, 20
23
+
24
+
25
+ def _expire(*_):
26
+ raise Transient("deadline exceeded")
27
+
28
+
29
+ def _parse_args(argv: list[str] | None = None) -> argparse.Namespace:
30
+ p = argparse.ArgumentParser(prog="erp_login", description="One-shot IIT KGP ERP login.")
31
+ p.add_argument(
32
+ "--fields",
33
+ nargs="+",
34
+ default=["cookies"],
35
+ help="Fields to include in JSON output (default: cookies).",
36
+ )
37
+ p.add_argument(
38
+ "--scope",
39
+ choices=("all", *erp.SCOPES),
40
+ default=None,
41
+ help="Optional cookie scope filter.",
42
+ )
43
+ return p.parse_args(argv)
44
+
45
+
46
+ def run(fields: Collection[str] = ("cookies",), scope: str | None = None) -> erp.LoginResult:
47
+ creds = config.load()
48
+ return erp.login(creds, otp.GmailOtp(creds.gmail), fields=fields, scope=scope)
49
+
50
+
51
+ def main(argv: list[str] | None = None) -> int:
52
+ args = _parse_args(argv)
53
+ fields = [f for item in args.fields for f in item.split(",") if f]
54
+ resource.setrlimit(resource.RLIMIT_CORE, (0, 0)) # no core dumps holding secrets
55
+ signal.signal(signal.SIGALRM, _expire)
56
+ signal.alarm(DEADLINE_S)
57
+ try:
58
+ out = run(fields=fields, scope=args.scope)
59
+ except (Transient, Fatal) as e:
60
+ log(str(e))
61
+ return TRANSIENT if isinstance(e, Transient) else FATAL
62
+ except Exception as e:
63
+ log(f"unexpected {type(e).__name__}")
64
+ if os.environ.get("DOOT_DEBUG"):
65
+ traceback.print_exc()
66
+ return UNEXPECTED
67
+ finally:
68
+ signal.alarm(0)
69
+ print(json.dumps(out))
70
+ return OK
71
+
72
+
73
+ if __name__ == "__main__":
74
+ sys.exit(main())
@@ -0,0 +1,41 @@
1
+ import json
2
+ import os
3
+ from dataclasses import dataclass
4
+ from pathlib import Path
5
+
6
+ from .errors import Fatal
7
+
8
+ _GMAIL_KEYS = {"client_id", "client_secret", "refresh_token"}
9
+
10
+
11
+ @dataclass(frozen=True, slots=True)
12
+ class Creds:
13
+ user: str
14
+ password: str
15
+ answers: dict[str, str]
16
+ gmail: dict[str, str]
17
+
18
+
19
+ def _read(name: str, env: str) -> str:
20
+ """systemd credential first (works with LoadCredentialEncrypted=), env var as dev fallback."""
21
+ if d := os.environ.get("CREDENTIALS_DIRECTORY"):
22
+ if (p := Path(d, name)).is_file():
23
+ return p.read_text("utf-8").strip()
24
+ if v := os.environ.get(env, "").strip():
25
+ return v
26
+ raise Fatal(f"missing credential: {name}")
27
+
28
+
29
+ def load() -> Creds:
30
+ try:
31
+ c = Creds(
32
+ _read("erp_user", "ERP_USER"),
33
+ _read("erp_pass", "ERP_PASS"),
34
+ json.loads(_read("erp_answers", "ERP_ANSWERS")),
35
+ json.loads(_read("gmail_oauth", "GMAIL_OAUTH_JSON")),
36
+ )
37
+ except json.JSONDecodeError:
38
+ raise Fatal("malformed JSON credential") from None
39
+ if not _GMAIL_KEYS <= c.gmail.keys():
40
+ raise Fatal("gmail_oauth is missing keys")
41
+ return c
@@ -0,0 +1,159 @@
1
+ import re
2
+ import time
3
+ import urllib.parse
4
+ from collections.abc import Collection
5
+ from typing import Protocol
6
+
7
+ from .config import Creds
8
+ from .errors import Fatal, Transient
9
+ from .log import log
10
+ from .net import Session, jloads
11
+
12
+ CONTRACT_V = 1
13
+ SELECTABLE_FIELDS = frozenset({"sso_token", "cookies", "cookie_header", "issued_at"})
14
+ _SECRET_FIELDS = frozenset({"sso_token", "cookies", "cookie_header"})
15
+ SCOPES: dict[str, tuple[str, ...]] = {
16
+ "cdc": ("/TrainingPlacementSSO",),
17
+ "erp": ("/IIT_ERP3",),
18
+ "sso": ("/SSOAdministration",),
19
+ }
20
+
21
+ BASE = "https://erp.iitkgp.ac.in/"
22
+ HOME = BASE + "IIT_ERP3/"
23
+ KEEPALIVE = HOME + "keepAlive.htm"
24
+ CDC = BASE + "TrainingPlacementSSO/Notice.jsp"
25
+ SSO = BASE + "SSOAdministration/"
26
+ _TAG = re.compile(r"""<[^>]*\bid=["']sessionToken["'][^>]*>""")
27
+ _VALUE = re.compile(r"""\bvalue=["']([^"']+)""")
28
+ _SESSION_PARAM = re.compile(r"[?&]sessionToken=([^&#]+)")
29
+ _SSO_TOKEN = re.compile(r"[?&]ssoToken=([^&#]+)")
30
+
31
+
32
+ class OtpSource(Protocol):
33
+ def mark(self) -> None:
34
+ """Called just before the ERP is asked to send the OTP."""
35
+
36
+ def wait(self) -> str:
37
+ """Return the OTP that arrived after mark()."""
38
+
39
+
40
+ def _session_token(html: str, url: str = "") -> str:
41
+ if (tag := _TAG.search(html)) and (v := _VALUE.search(tag[0])):
42
+ return v[1]
43
+ if m := _SESSION_PARAM.search(url):
44
+ return urllib.parse.unquote(m[1])
45
+ raise Transient("sessionToken not found on ERP login page")
46
+
47
+
48
+ def _request_otp(s: Session, form: dict) -> None:
49
+ msg = jloads(s.fetch(SSO + "getEmilOTP.htm", form)[1]).get("msg", "") # never retried
50
+ low = msg.lower()
51
+ if "sent to your email" in low:
52
+ return
53
+ if "answare mismatch" in low or "answer mismatch" in low: # "answare" is the ERP's own typo
54
+ raise Fatal("wrong security answer")
55
+ if "password mismatch" in low:
56
+ raise Fatal("wrong password")
57
+ raise Fatal(f"OTP request rejected: {msg[:80]}")
58
+
59
+
60
+ def _signin(s: Session, form: dict, user: str) -> str:
61
+ """POST the login. The ssoToken arrives in a redirect; no redirect at all means another session blocks us."""
62
+ for attempt in (0, 1):
63
+ _, body = s.fetch(SSO + "auth.htm", form)
64
+ if "Email OTP mismatch" in body:
65
+ raise Transient("OTP mismatch")
66
+ if tok := next((m[1] for u in s.hops if (m := _SSO_TOKEN.search(u))), None):
67
+ return tok
68
+ if s.hops or attempt:
69
+ break
70
+ log("login blocked by another session, clearing sessions")
71
+ s.fetch(SSO + "clearAllSessions.htm", {"user_code": user}, retries=1)
72
+ raise Transient("login did not yield an ssoToken")
73
+
74
+
75
+ class LoginResult(dict):
76
+ """Dict-like login result whose repr redacts secret fields."""
77
+
78
+ def __repr__(self) -> str:
79
+ redacted = {k: ("***" if k in _SECRET_FIELDS else v) for k, v in self.items()}
80
+ return f"{type(self).__name__}({dict.__repr__(redacted)})"
81
+
82
+ __str__ = __repr__
83
+
84
+
85
+ def _validate_selection(fields: Collection[str], scope: str | None) -> set[str]:
86
+ selected = set(fields)
87
+ if not selected:
88
+ raise Fatal("at least one field must be selected")
89
+ if bad := sorted(selected - SELECTABLE_FIELDS):
90
+ raise Fatal(f"unknown or disallowed field(s): {', '.join(bad)}")
91
+ if scope is not None and scope != "all" and scope not in SCOPES:
92
+ raise Fatal(f"unknown scope: {scope}")
93
+ return selected
94
+
95
+
96
+ def _filter_cookies(jar, scope: str | None) -> list[dict]:
97
+ prefixes = SCOPES.get(scope) if scope and scope != "all" else None
98
+ return [
99
+ {
100
+ "name": k.name,
101
+ "value": k.value,
102
+ "domain": k.domain,
103
+ "path": k.path,
104
+ "expires": k.expires or 0,
105
+ "secure": k.secure,
106
+ }
107
+ for k in jar
108
+ if prefixes is None or (k.path or "").startswith(prefixes)
109
+ ]
110
+
111
+
112
+ def login(
113
+ c: Creds,
114
+ otp: OtpSource,
115
+ *,
116
+ fields: Collection[str],
117
+ scope: str | None = None,
118
+ ) -> LoginResult:
119
+ """Full ERP login returning only the requested fields (plus schema version `v`)."""
120
+ selected = _validate_selection(fields, scope)
121
+ s = Session("iitkgp.ac.in")
122
+ home_url, home_html = s.fetch(HOME, retries=2)
123
+ token = _session_token(home_html, home_url)
124
+
125
+ q = s.fetch(SSO + "getSecurityQues.htm", {"user_id": c.user}, retries=2)[1].strip()
126
+ if q == "FALSE":
127
+ raise Fatal("invalid roll number")
128
+ if q not in c.answers:
129
+ raise Fatal(f"no answer configured for security question: {q[:100]}")
130
+
131
+ form = {"user_id": c.user, "password": c.password, "answer": c.answers[q],
132
+ "typeee": "SI", "sessionToken": token, "requestedUrl": HOME}
133
+ otp.mark()
134
+ _request_otp(s, form)
135
+ log("otp requested")
136
+ form["email_otp"] = otp.wait()
137
+ log("otp received")
138
+ sso = _signin(s, form, c.user)
139
+
140
+ if "Session Extended" not in s.fetch(KEEPALIVE, retries=1)[1]:
141
+ raise Transient("session not alive after login")
142
+
143
+ need_cookies = bool(selected & {"cookies", "cookie_header"})
144
+ if need_cookies and scope in (None, "all", "cdc"):
145
+ s.fetch(CDC, retries=1) # warm the TrainingPlacementSSO cookie only when CDC cookies may be returned
146
+ log("signed in")
147
+
148
+ result = LoginResult({"v": CONTRACT_V})
149
+ if "issued_at" in selected:
150
+ result["issued_at"] = int(time.time())
151
+ if "sso_token" in selected:
152
+ result["sso_token"] = next((k.value for k in s.jar if k.name == "ssoToken"), sso)
153
+ if need_cookies:
154
+ cookies = _filter_cookies(s.jar, scope)
155
+ if "cookies" in selected:
156
+ result["cookies"] = cookies
157
+ if "cookie_header" in selected:
158
+ result["cookie_header"] = "; ".join(f"{k['name']}={k['value']}" for k in cookies)
159
+ return result
@@ -0,0 +1,6 @@
1
+ class Transient(Exception):
2
+ """Retry later with backoff."""
3
+
4
+
5
+ class Fatal(Exception):
6
+ """Do not retry: bad credentials, rejected request or broken config."""
@@ -0,0 +1,6 @@
1
+ import sys
2
+
3
+
4
+ def log(msg: str) -> None:
5
+ """Progress to stderr. Never pass secrets (tokens, cookies, redirect URLs) here."""
6
+ print(f"doot_login: {msg}", file=sys.stderr, flush=True)
@@ -0,0 +1,81 @@
1
+ import http.cookiejar
2
+ import json
3
+ import os
4
+ import ssl
5
+ import time
6
+ import urllib.error
7
+ import urllib.parse
8
+ import urllib.request
9
+
10
+ from .errors import Fatal, Transient
11
+
12
+ MAX_BODY = 2_000_000
13
+ UA = {
14
+ "User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 Chrome/120.0.0.0 Safari/537.36",
15
+ "Accept-Language": "en-US,en;q=0.9",
16
+ }
17
+ # Verifies certificate and hostname. If the ERP's chain is incomplete, point DOOT_CA_FILE at the
18
+ # right CA bundle; never disable verification.
19
+ _CTX = ssl.create_default_context(cafile=os.environ.get("DOOT_CA_FILE") or None)
20
+ _CTX.minimum_version = ssl.TLSVersion.TLSv1_2
21
+
22
+
23
+ def _allowed(host: str, suffixes: tuple[str, ...]) -> bool:
24
+ return any(host == s or host.endswith("." + s) for s in suffixes)
25
+
26
+
27
+ class _Guard(urllib.request.HTTPRedirectHandler):
28
+ """Refuse redirects that downgrade to http or leave the allowed domains; record each hop."""
29
+
30
+ def __init__(self, suffixes: tuple[str, ...], hops: list[str]):
31
+ self.suffixes, self.hops = suffixes, hops
32
+
33
+ def redirect_request(self, req, fp, code, msg, headers, newurl):
34
+ u = urllib.parse.urlparse(newurl)
35
+ if u.scheme != "https" or not _allowed(u.hostname or "", self.suffixes):
36
+ raise Fatal(f"blocked redirect to {u.hostname}")
37
+ self.hops.append(newurl)
38
+ return super().redirect_request(req, fp, code, msg, headers, newurl)
39
+
40
+
41
+ class Session:
42
+ """Cookie-keeping HTTPS client restricted to the given domain suffixes.
43
+
44
+ After fetch(), `hops` holds the redirect URLs followed by that call (they can contain tokens).
45
+ """
46
+
47
+ def __init__(self, *suffixes: str):
48
+ self.jar = http.cookiejar.CookieJar()
49
+ self.hops: list[str] = []
50
+ self._open = urllib.request.build_opener(
51
+ urllib.request.HTTPSHandler(context=_CTX),
52
+ urllib.request.HTTPCookieProcessor(self.jar),
53
+ _Guard(suffixes, self.hops),
54
+ ).open
55
+
56
+ def fetch(self, url: str, form=None, headers=None, retries: int = 0) -> tuple[str, str]:
57
+ """GET, or POST when form is given. Only pass retries > 0 for idempotent calls."""
58
+ data = urllib.parse.urlencode(form).encode() if form is not None else None
59
+ host, err = urllib.parse.urlparse(url).netloc, None
60
+ for i in range(retries + 1):
61
+ if i:
62
+ time.sleep(0.5 * 2 ** (i - 1))
63
+ self.hops.clear()
64
+ try:
65
+ req = urllib.request.Request(url, data, {**UA, **(headers or {})})
66
+ with self._open(req, timeout=15) as r:
67
+ return r.geturl(), r.read(MAX_BODY).decode("utf-8", "replace")
68
+ except urllib.error.HTTPError as e:
69
+ if e.code < 500 and e.code != 429:
70
+ raise Fatal(f"HTTP {e.code} from {host}") from None
71
+ err = e
72
+ except (urllib.error.URLError, TimeoutError, OSError) as e:
73
+ err = e
74
+ raise Transient(f"{host}: {err}")
75
+
76
+
77
+ def jloads(body: str):
78
+ try:
79
+ return json.loads(body)
80
+ except ValueError:
81
+ raise Transient("non-JSON response") from None
@@ -0,0 +1,68 @@
1
+ import base64
2
+ import itertools
3
+ import re
4
+ import time
5
+ import urllib.parse
6
+
7
+ from .errors import Fatal, Transient
8
+ from .net import Session, jloads
9
+
10
+ SUBJECT = "OTP for Sign In in ERP Portal of IIT Kharagpur"
11
+ _TOKEN_URL = "https://oauth2.googleapis.com/token"
12
+ _API = "https://gmail.googleapis.com/gmail/v1/users/me/messages"
13
+ _OTP = re.compile(r"\b(\d{6})\b")
14
+ _TAGS = re.compile(r"<[^>]+>")
15
+
16
+
17
+ def _text(part: dict):
18
+ """Yield the decoded text of every body in a Gmail payload tree."""
19
+ if data := part.get("body", {}).get("data"):
20
+ yield base64.urlsafe_b64decode(data + "=" * (-len(data) % 4)).decode("utf-8", "replace")
21
+ for p in part.get("parts", []):
22
+ yield from _text(p)
23
+
24
+
25
+ class GmailOtp:
26
+ """Clock-free OTP lookup: remember the newest ERP mail before the ERP sends one, then wait for a new one.
27
+
28
+ Constructing it refreshes the Gmail token, so a revoked grant fails before any OTP is requested.
29
+ """
30
+
31
+ def __init__(self, gmail: dict[str, str], timeout: float = 60):
32
+ self._s, self._timeout = Session("googleapis.com"), timeout
33
+ self._base: str | None = None
34
+ form = {k: gmail[k] for k in ("client_id", "client_secret", "refresh_token")}
35
+ form["grant_type"] = "refresh_token"
36
+ try:
37
+ token = jloads(self._s.fetch(_TOKEN_URL, form, retries=2)[1])["access_token"]
38
+ except KeyError:
39
+ raise Fatal("gmail token response has no access_token") from None
40
+ self._auth = {"Authorization": f"Bearer {token}"}
41
+ self._q = urllib.parse.quote(f'subject:"{SUBJECT}" newer_than:1d')
42
+
43
+ def _get(self, path: str):
44
+ return jloads(self._s.fetch(_API + path, headers=self._auth, retries=1)[1])
45
+
46
+ def _latest(self) -> str | None:
47
+ return next((m["id"] for m in self._get(f"?q={self._q}&maxResults=1&fields=messages/id").get("messages", [])), None)
48
+
49
+ def mark(self) -> None:
50
+ self._base = self._latest()
51
+
52
+ def wait(self) -> str:
53
+ end = time.monotonic() + self._timeout
54
+ for delay in itertools.chain((1, 1.5, 2, 2), itertools.repeat(3)):
55
+ if (mid := self._latest()) and mid != self._base:
56
+ return self._code(mid)
57
+ if time.monotonic() + delay > end:
58
+ raise Transient("OTP email not received in time")
59
+ time.sleep(delay)
60
+ raise Transient("OTP email not received in time")
61
+
62
+ def _code(self, mid: str) -> str:
63
+ if hits := _OTP.findall(self._get(f"/{mid}?format=minimal&fields=snippet")["snippet"]):
64
+ return hits[-1]
65
+ body = _TAGS.sub(" ", " ".join(_text(self._get(f"/{mid}?format=full")["payload"])))
66
+ if hits := _OTP.findall(body):
67
+ return hits[-1]
68
+ raise Transient("no OTP found in mail")
@@ -0,0 +1,210 @@
1
+ Metadata-Version: 2.4
2
+ Name: erp_login
3
+ Version: 0.2.0
4
+ Summary: Unofficial headless login for the IIT Kharagpur ERP: handles password, security question and emailed Gmail OTP, then prints the session as JSON.
5
+ Author-email: Krishna Singha <krishnasingha.dev@gmail.com>
6
+ License-Expression: Apache-2.0
7
+ Project-URL: Source, https://github.com/krishna-singha/erp-login
8
+ Keywords: iit-kharagpur,erp,login,otp,gmail
9
+ Classifier: Environment :: Console
10
+ Classifier: Operating System :: POSIX :: Linux
11
+ Classifier: Programming Language :: Python :: 3
12
+ Requires-Python: >=3.10
13
+ Description-Content-Type: text/markdown
14
+ License-File: LICENSE
15
+ Dynamic: license-file
16
+
17
+ # erp_login
18
+
19
+ Zero-dependency headless login for the IIT Kharagpur ERP (`erp.iitkgp.ac.in`).
20
+ Handles password, security question, and emailed Gmail OTP, then returns or prints **only the session fields you request**.
21
+
22
+ - **Zero runtime dependencies** — Python `>=3.10` standard library only.
23
+ - **Least-privilege field selection** — request only `sso_token`, `cookies`, `cookie_header`, or `issued_at`. Required in the library; defaults to `cookies` in the CLI.
24
+ - **Scope filtering** — restrict cookies to `cdc`, `erp`, `sso`, or `all`.
25
+ - **Skips unnecessary requests** — skips the CDC warm-up request when CDC cookies aren't needed.
26
+ - **Redacted `repr`** — `LoginResult.__repr__` and `__str__` mask `sso_token`, `cookies`, and `cookie_header` as `***` so accidental `print(result)` calls don't leak secrets.
27
+ - **Hardened networking** — TLS 1.2+, blocks HTTPS-to-HTTP downgrades and off-domain redirects (`*.iitkgp.ac.in` / `*.googleapis.com`), disables core dumps (`RLIMIT_CORE = 0`), and enforces a 90s deadline.
28
+
29
+ ---
30
+
31
+ ## Installation
32
+
33
+ ```bash
34
+ pip install erp_login
35
+ ```
36
+
37
+ For CLI-only usage:
38
+
39
+ ```bash
40
+ pipx install erp_login
41
+ # or: uv tool install erp_login
42
+ ```
43
+
44
+ ---
45
+
46
+ ## Quick Start
47
+
48
+ 1. Set your credentials as environment variables (or via systemd `CREDENTIALS_DIRECTORY`):
49
+
50
+ ```bash
51
+ export ERP_USER="YOUR_ROLL_NO"
52
+ export ERP_PASS="YOUR_PASSWORD"
53
+ export ERP_ANSWERS='{"Security Question 1": "Answer 1", "Security Question 2": "Answer 2", "Security Question 3": "Answer 3"}'
54
+ export GMAIL_OAUTH_JSON='{"client_id": "...", "client_secret": "...", "refresh_token": "..."}'
55
+ ```
56
+
57
+ 2. Run the CLI:
58
+
59
+ ```bash
60
+ erp_login
61
+ # or: python3 -m erp_login
62
+ ```
63
+
64
+ `stdout` prints one JSON line:
65
+
66
+ ```json
67
+ {"v": 1, "cookies": [...]}
68
+ ```
69
+
70
+ Progress and errors are written to `stderr` (never secrets).
71
+
72
+ ---
73
+
74
+ ## CLI Reference
75
+
76
+ ```text
77
+ erp_login [--fields FIELDS ...] [--scope {all,cdc,erp,sso}]
78
+ ```
79
+
80
+ - `--fields`: Space- or comma-separated list of fields to include (default: `cookies`).
81
+ - Selectable fields: `sso_token`, `cookies`, `cookie_header`, `issued_at`
82
+ - `--scope`: Filter `cookies` and `cookie_header` by cookie path prefix:
83
+ - `all` (default): all cookies
84
+ - `cdc`: `/TrainingPlacementSSO`
85
+ - `erp`: `/IIT_ERP3`
86
+ - `sso`: `/SSOAdministration`
87
+
88
+ ### Examples
89
+
90
+ ```bash
91
+ # Only sso_token (skips the CDC warm-up request)
92
+ erp_login --fields sso_token
93
+
94
+ # Only CDC cookies + ready-to-use Cookie header + timestamp
95
+ erp_login --fields cookies cookie_header issued_at --scope cdc
96
+
97
+ # Comma-separated syntax also works
98
+ erp_login --fields sso_token,issued_at
99
+ ```
100
+
101
+ ### Exit Codes
102
+
103
+ | Code | Error Type | Meaning & Action |
104
+ | ---- | ---------- | ---------------- |
105
+ | `0` | — | Success. Single-line JSON on `stdout`. |
106
+ | `10` | `Transient` | Safe to retry with backoff (OTP timeout/mismatch, network/5xx/429, 90s deadline). |
107
+ | `20` | `Fatal` | **Do not retry blindly** — wrong password/security answer, invalid roll number, missing/malformed config, revoked Gmail token, or invalid `--fields`/`--scope`. |
108
+ | `1` | Unexpected | Unhandled exception. Set `DOOT_DEBUG=1` to print traceback to `stderr`. |
109
+
110
+ ---
111
+
112
+ ## Python Library Usage
113
+
114
+ `fields` is **required** (keyword-only) in `erp_login.login(...)` so callers never receive all session data by accident.
115
+
116
+ ```python
117
+ from erp_login import Fatal, GmailOtp, Transient, config, login
118
+
119
+ creds = config.load()
120
+
121
+ try:
122
+ res = login(
123
+ creds,
124
+ GmailOtp(creds.gmail),
125
+ fields=("cookies", "cookie_header", "issued_at"),
126
+ scope="cdc",
127
+ )
128
+ except Transient as e:
129
+ ... # retry later with backoff
130
+ except Fatal as e:
131
+ ... # fix credentials/config; do not retry blindly
132
+
133
+ print(res) # LoginResult({'v': 1, 'issued_at': ..., 'cookies': '***', 'cookie_header': '***'})
134
+ cookie_header = res["cookie_header"]
135
+ ```
136
+
137
+ ### Passing Credentials Directly (without env vars)
138
+
139
+ ```python
140
+ from erp_login import Creds, GmailOtp, login
141
+
142
+ creds = Creds(
143
+ user="YOUR_ROLL_NO",
144
+ password="YOUR_PASSWORD",
145
+ answers={"Security Question 1": "Answer 1"},
146
+ gmail={"client_id": "...", "client_secret": "...", "refresh_token": "..."},
147
+ )
148
+ res = login(creds, GmailOtp(creds.gmail), fields=("sso_token",))
149
+ ```
150
+
151
+ ### Custom OTP Source
152
+
153
+ `login()` accepts any object implementing the `OtpSource` protocol (`mark() -> None`, `wait() -> str`):
154
+
155
+ ```python
156
+ class ManualOtp:
157
+ def mark(self) -> None:
158
+ pass
159
+
160
+ def wait(self) -> str:
161
+ return input("Enter 6-digit ERP OTP: ").strip()
162
+
163
+ res = login(creds, ManualOtp(), fields=("sso_token",))
164
+ ```
165
+
166
+ ---
167
+
168
+ ## Output Schema (`v: 1`)
169
+
170
+ `LoginResult` is a `dict` subclass containing `"v": 1` plus **only** the requested fields:
171
+
172
+ | Field | Type | Description |
173
+ | ----- | ---- | ----------- |
174
+ | `v` | `int` | Always `1` (schema version). |
175
+ | `sso_token` | `str` | The `ssoToken` value. |
176
+ | `cookies` | `list[dict]` | List of `{name, value, domain, path, expires, secure}` dicts. |
177
+ | `cookie_header` | `str` | Ready-to-use `name=value; ...` string built from the scoped cookies. |
178
+ | `issued_at` | `int` | Unix epoch timestamp (seconds). |
179
+
180
+ Credentials (`password`, `answers`, `otp`, `gmail`) are never selectable and raise `Fatal` if requested.
181
+
182
+ ---
183
+
184
+ ## Configuration
185
+
186
+ `config.load()` checks `$CREDENTIALS_DIRECTORY` (for systemd `LoadCredential` / `LoadCredentialEncrypted`) first, then falls back to environment variables:
187
+
188
+ | systemd credential | Env var | Format |
189
+ | ------------------ | ------- | ------ |
190
+ | `erp_user` | `ERP_USER` | Roll number string |
191
+ | `erp_pass` | `ERP_PASS` | ERP password string |
192
+ | `erp_answers` | `ERP_ANSWERS` | JSON object `{question: answer}` |
193
+ | `gmail_oauth` | `GMAIL_OAUTH_JSON` | JSON object `{client_id, client_secret, refresh_token}` |
194
+
195
+ Optional environment variables:
196
+ - `DOOT_DEBUG=1`: Print full traceback to `stderr` on unexpected errors (exit code `1`).
197
+ - `DOOT_CA_FILE=/path/to/ca.pem`: Custom CA bundle for TLS verification.
198
+
199
+ ---
200
+
201
+ ## Security & Disclaimer
202
+
203
+ - Field selection enforces least privilege between callers, but **anyone holding `cookies`, `cookie_header`, or `sso_token` can act as you on ERP**. Store credentials with `0600` permissions (or systemd encrypted credentials), never log stdout JSON, and pass output over private pipes only.
204
+ - Unofficial tool; not affiliated with IIT Kharagpur.
205
+
206
+ ---
207
+
208
+ ## License
209
+
210
+ Apache License 2.0 — see `LICENSE` for details.
@@ -0,0 +1,16 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ erp_login/__init__.py
5
+ erp_login/__main__.py
6
+ erp_login/config.py
7
+ erp_login/erp.py
8
+ erp_login/errors.py
9
+ erp_login/log.py
10
+ erp_login/net.py
11
+ erp_login/otp.py
12
+ erp_login.egg-info/PKG-INFO
13
+ erp_login.egg-info/SOURCES.txt
14
+ erp_login.egg-info/dependency_links.txt
15
+ erp_login.egg-info/entry_points.txt
16
+ erp_login.egg-info/top_level.txt
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ erp_login = erp_login.__main__:main
@@ -0,0 +1 @@
1
+ erp_login
@@ -0,0 +1,32 @@
1
+ [build-system]
2
+ requires = ["setuptools>=77"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "erp_login"
7
+ version = "0.2.0"
8
+ description = "Unofficial headless login for the IIT Kharagpur ERP: handles password, security question and emailed Gmail OTP, then prints the session as JSON."
9
+ readme = "README.md"
10
+ authors = [{ name = "Krishna Singha", email = "krishnasingha.dev@gmail.com" }]
11
+ license = "Apache-2.0"
12
+ license-files = ["LICENSE"]
13
+ requires-python = ">=3.10"
14
+ dependencies = []
15
+ keywords = ["iit-kharagpur", "erp", "login", "otp", "gmail"]
16
+ classifiers = [
17
+ "Environment :: Console",
18
+ "Operating System :: POSIX :: Linux",
19
+ "Programming Language :: Python :: 3",
20
+ ]
21
+
22
+ [project.urls]
23
+ Source = "https://github.com/krishna-singha/erp-login"
24
+
25
+ [project.scripts]
26
+ erp_login = "erp_login.__main__:main"
27
+
28
+ [tool.setuptools]
29
+ packages = ["erp_login"]
30
+
31
+ [tool.pyrefly]
32
+ search-path = ["."]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+