Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,24 @@ adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
A `Retry-After` hint is capped at 60s so a hostile or broken value cannot
stall a pass. Permanent failures (404, 400) and expired sessions are
still not retried.
- **PowerSchool MyCBE support (`sis` command tree).** The CBE parent/student
portal (https://sis.cbe.ab.ca) is now a first-class surface:
- `sis login` / `sis logout` — session-cookie auth against MyCBE
- `sis whoami` — student profile and section count
- `sis years` — academic-year picker
- `sis grades` — enrolled classes for the active year
- `sis grades --marks` — current T1/S1 course marks from the guardian
"Assignments & Grades" page
- `sis standards` — rubric outcomes per section
- `sis standard-grades` — outcome grades with proficiency codes and
calculated percentages
- `sis assignments` — posted assignments with due dates, categories,
scores and flags; bounded per-cell fan-out
- `sis scale` — the CBE High School Proficiency Scale
- `sis school` — per-school config
The `.env` file is optional for read-only commands; only login and the
401/403 re-auth path need credentials. Every `sis --json` payload is a
`count` envelope with snake_case keys.

### Changed
- **Output overhaul across every command.** Human-readable output is now a
Expand Down
64 changes: 64 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,7 @@ README spotlight; everything else lives further down.
| `archive` | Snapshot courses into a versioned, UUID-named blob store. Subcommand `list` for the saved index. |
| `assignment` / `dropbox` | List folders, show my submissions, download files. Scope with `--course <id>`. |
| `quiz` | List quizzes and show my attempts. Scope with `--course <id>`. |
| `sis` | PowerSchool MyCBE parent/student portal (`sis login`, `sis whoami`, `sis grades`, `sis grades --marks`, `sis standards`, `sis standard-grades`, `sis assignments`, `sis scale`, `sis years`, `sis school`). |

## Common flags

Expand Down Expand Up @@ -322,6 +323,69 @@ specifically need scriptable access.

Each of these has full `--help` text with endpoint details.

### PowerSchool MyCBE (`sis` subtree)

The Calgary Board of Education's parent/student portal
(https://sis.cbe.ab.ca) is the PowerSchool SIS in a different skin. We
talk to it through the Angular SPA's internal REST endpoints at
`/ws/xte/…`, with session-cookie auth.

```sh
schooltools sis login # sign in to MyCBE (saves to ~/.config/schooltools/sis-session.json)
schooltools sis whoami # student profile + section count
schooltools sis years # year picker
schooltools sis grades # every enrolled section for the active year
schooltools sis grades --marks # course marks for every reporting term (T1, T2, S1, …)
schooltools sis standards # standards (rubric items) per section
schooltools sis standard-grades # outcome grades + calculated percentages
schooltools sis assignments # posted assignments (often empty early in a term)
schooltools sis scale # CBE High School Proficiency Scale
schooltools sis school # per-school config (max comment size, etc.)
schooltools sis logout # clear the SIS session
```

The `.env` file is required only when credentials are actually needed:
`sis login` and any automatic re-authentication (when the saved session
is missing or the portal returns 401/403). Every read-only subcommand
works from the saved session alone, so `sis whoami`,
`sis grades --marks` and friends run fine in a directory without an
`.env`.

Every `sis --json` payload is an envelope with a `count` field and
snake_case keys, so `sis grades`, `sis standard-grades`, `sis
assignments`, `sis standards`, `sis years` and `sis school` can be
consumed without special-casing each command.

Auth uses `SIS_STUDENT_NUMBER` + `SIS_PASSWORD` from `.env` (fall
back to `CBE_STUDENT_NUMBER` + `CBE_PASSWORD`, then `CBE_EMAIL` +
`CBE_PASSWORD` — the last of which warns on stderr, because MyCBE
expects the student number and will reject an email address). CBE
customised PowerSchool's `doPCASLogin` to send
plaintext passwords, so no HMAC or `pskey` is required. The login
follows the browser's flow:

1. `GET /public/` seeds the `JSESSIONID` cookie
2. `POST /guardian/home.html` with form-urlencoded credentials → 302
back to `/guardian/home.html`, which sets the four session
cookies (`JSESSIONID`, `psaid`, `currentSchool`, `current_locale`)
3. The four cookies are saved to the SIS session file

Redirects that leave the portal's origin are refused.

`--auto-refresh` (on by default) re-authenticates when the saved
session is missing. To keep a logout sticky, pass
`--auto-refresh=false` to each subsequent command. A `sis` command
that gets a 401/403 from the portal also re-authenticates once and
retries, because PowerSchool issues `psaid`/`JSESSIONID` without an
`Expires` and a server-side revocation is invisible to the local expiry
check.

Set `SIS_DCID=<student DCID>` in `.env` to skip the credentials-link scrape
that `sis whoami` uses to discover the internal DCID. `sis assignments`
drills into the per-cell legacy endpoint once per standard, so it takes
`--section <dcid>` to narrow a run and `--max-cells` (default 200) to
cap it.

## Migration notes

### 0.1.0 → 0.2.0
Expand Down
10 changes: 5 additions & 5 deletions cmd/assignment.go
Original file line number Diff line number Diff line change
Expand Up @@ -543,7 +543,7 @@ func fetchMySubmissions(jar *cookiejar.Jar, courseID, folderID string) ([]Entity
if err != nil {
return nil, err
}
defer res.Body.Close()
defer func() { _ = res.Body.Close() }()
if res.StatusCode == 403 {
return nil, errSubmissionsBlocked
}
Expand All @@ -565,7 +565,7 @@ func fetchFeedback(jar *cookiejar.Jar, courseID, folderID, entityType, entityID
if err != nil {
return nil, err
}
defer res.Body.Close()
defer func() { _ = res.Body.Close() }()
if res.StatusCode == 404 {
return nil, nil
}
Expand Down Expand Up @@ -786,9 +786,9 @@ func submissionsSection(rep assignmentReport) string {
}
var b strings.Builder
for i, s := range rep.Submissions {
b.WriteString(fmt.Sprintf(" %s %s\n",
fmt.Fprintf(&b, " %s %s\n",
render.Accent(fmt.Sprintf("#%d", i+1)),
render.When(s.Date())))
render.When(s.Date()))
if note := s.Note(); note != "" {
b.WriteString(" " + render.Wrap(note, render.Width()-4) + "\n")
}
Expand Down Expand Up @@ -973,7 +973,7 @@ func formatFeedbackRubric(out Feedback, rubric *Rubric, folderID int, courseID s
if lvl := rubric.OverallLevelName(score); lvl != "" {
value += " → " + render.Accent(lvl)
}
b.WriteString(fmt.Sprintf("\n %-*s %s\n", 46, "Overall", value))
fmt.Fprintf(&b, "\n %-*s %s\n", 46, "Overall", value)
}
}
}
Expand Down
6 changes: 1 addition & 5 deletions cmd/course.go
Original file line number Diff line number Diff line change
Expand Up @@ -389,7 +389,7 @@ func renderCourseReport(rep courseReportOut, id string, own d2lCourse, haveOwn b
break
}
when := n.Date()
b.WriteString(fmt.Sprintf(" %s %s\n", render.Muted(render.Truncate(render.Rel(when), 12)), render.Truncate(n.Title, 60)))
fmt.Fprintf(&b, " %s %s\n", render.Muted(render.Truncate(render.Rel(when), 12)), render.Truncate(n.Title, 60))
}
b.WriteString(render.Hint("schooltools news --course %s", id))
}
Expand Down Expand Up @@ -554,10 +554,6 @@ func dateOrEmpty(s *string) string {
return *s
}

func formatDate(s *string) string {
return render.Date(dateOrEmpty(s))
}

func plural(n int) string {
if n == 1 {
return ""
Expand Down
6 changes: 3 additions & 3 deletions cmd/quiz.go
Original file line number Diff line number Diff line change
Expand Up @@ -421,7 +421,7 @@ func fetchQuizAttemptsFor(jar *cookiejar.Jar, courseID, quizID string) ([]QuizAt
if err != nil {
return nil, err
}
defer res.Body.Close()
defer func() { _ = res.Body.Close() }()
if res.StatusCode == 403 {
return nil, fmt.Errorf("D2L refused (403) — students cannot read this quiz's attempts")
}
Expand Down Expand Up @@ -564,10 +564,10 @@ func attemptsSection(ats []QuizAttempt) string {
if !a.Done() {
done = render.When(a.StartTime()) + " " + render.Warn("in progress")
}
b.WriteString(fmt.Sprintf(" %-6s %-44s %s\n",
fmt.Fprintf(&b, " %-6s %-44s %s\n",
fmt.Sprintf("#%d", a.AttemptNumber),
done,
score))
score)
}
if best := bestAttemptScore(ats); best != "" {
b.WriteString(render.KV(render.Row{Key: "Best", Value: render.Accent(best)}))
Expand Down
2 changes: 2 additions & 0 deletions cmd/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import (

"github.com/spf13/cobra"

"github.com/IamCoder18/schooltools/internal/authlog"
"github.com/IamCoder18/schooltools/internal/httpclient"
"github.com/IamCoder18/schooltools/internal/login"
)
Expand All @@ -28,6 +29,7 @@ func init() {
rootCmd.SilenceErrors = true
rootCmd.PersistentFlags().BoolVar(&noAuthLog, "no-auth-log", false, "Disable the JSONL auth log (~/.config/schooltools/auth.log)")
cobra.OnInitialize(func() {
authlog.SetEnabled(!noAuthLog)
httpclient.RegisterTokenRefresher(login.TokenRefresher())
})
}
Expand Down
128 changes: 128 additions & 0 deletions cmd/sis.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,128 @@
package cmd

import (
goerrors "errors"
"fmt"
"io/fs"
"net/http/cookiejar"

"github.com/spf13/cobra"

"github.com/IamCoder18/schooltools/internal/authlog"
"github.com/IamCoder18/schooltools/internal/cookies"
"github.com/IamCoder18/schooltools/internal/env"
"github.com/IamCoder18/schooltools/internal/ps"
)

var sisCmd = &cobra.Command{
Use: "sis",
Short: "PowerSchool MyCBE parent/student portal (sis.cbe.ab.ca)",
Long: "Access the Calgary Board of Education's PowerSchool SIS parent\n" +
"and student portal (https://sis.cbe.ab.ca). The portal is an Angular\n" +
"SPA on top of PowerSchool 21.06 / PDS 31.0.3 with internal REST\n" +
"endpoints under /ws/xte/....\n\n" +
"Login uses the student number (NOT email) + password. CBE customised\n" +
"PowerSchool's doPCASLogin to send plaintext passwords, so no HMAC\n" +
"or pskey is required.\n\n" +
"Use SIS_STUDENT_NUMBER + SIS_PASSWORD in .env (falls back to\n" +
"CBE_EMAIL + CBE_PASSWORD).",
Args: cobra.NoArgs,
PersistentPreRunE: func(cmd *cobra.Command, args []string) error {
envFile, _ := cmd.Flags().GetString("env-file")
return loadEnvOptional(envFile)
},
RunE: func(cmd *cobra.Command, args []string) error {
return cmd.Help()
},
}

func init() {
sisCmd.PersistentFlags().StringP("env-file", "e", ".env", "Path to .env (read for SIS_STUDENT_NUMBER / SIS_PASSWORD)")
sisCmd.PersistentFlags().Bool("auto-refresh", true, "Re-run 'sis login' automatically when the saved session is missing or the portal rejects it")
sisCmd.PersistentFlags().Bool("json", false, "Emit machine-readable JSON instead of a table")
rootCmd.AddCommand(sisCmd)
}

func loadEnvOptional(envFile string) error {
if err := env.LoadEnv(envFile); err != nil && !goerrors.Is(err, fs.ErrNotExist) {
return err
}
return nil
}

func sisClient(cmd *cobra.Command) (*ps.Client, error) {
envFile, _ := cmd.Flags().GetString("env-file")
autoRefresh, _ := cmd.Flags().GetBool("auto-refresh")

loginFn := func() ([]cookies.Record, error) { return sisLoginRunner(envFile) }
if !autoRefresh {
loginFn = nil
}

jar, err := ps.EnsureSession(ps.EnsureSessionOptions{
AutoRefresh: autoRefresh,
LoginFn: loginFn,
})
if err != nil {
return nil, err
}

client := ps.NewClient(jar)
if autoRefresh {
client.SetReauth(func() (*cookiejar.Jar, error) {
_ = authlog.Log("sis.reauth", map[string]any{"reason": "portal returned 401/403"})
return ps.Reauthenticate(loginFn)
})
}
return client, nil
}

func resolveYearID(client *ps.Client, dcid int64, override int) (int, error) {
if override != 0 {
return override, nil
}
years, err := client.GetYears(dcid)
if err != nil {
return 0, err
}
if len(years) == 0 {
return 0, fmt.Errorf("year picker returned no entries for this student; pass --year <id> to select one explicitly")
}
latest := years[0].YearID
for _, y := range years[1:] {
if y.YearID > latest {
latest = y.YearID
}
}
return latest, nil
}

func sisLoginRunner(envFile string) ([]cookies.Record, error) {
if err := env.LoadEnv(envFile); err != nil {
return nil, err
}
creds, err := env.GetSISCreds()
if err != nil {
return nil, err
}
_ = authlog.Log("sis.login.start", map[string]any{"account": creds.Account})
Comment thread
cubic-dev-ai[bot] marked this conversation as resolved.
Resolved
records, err := ps.Login(ps.LoginOptions{
Account: creds.Account,
Password: creds.Password,
})
if err != nil {
logSISLoginFailure(err)
return nil, err
}
_ = authlog.Log("sis.login.success", map[string]any{"cookie_count": len(records)})
return records, nil
}

func logSISLoginFailure(err error) {
code := "PS_LOGIN_ERROR"
var coder interface{ AuthCode() string }
if goerrors.As(err, &coder) {
code = coder.AuthCode()
}
_ = authlog.Log("sis.login.failure", map[string]any{"code": code, "message": err.Error()})
}
Loading
Loading