psn-client 0.2.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 3db23ae67a963e9df40f06cde9bb2841d51883e1a9c7299fe626a6aeaab4c2fe
4
- data.tar.gz: 4e1ff777570091db644b84aaec871566df8539042d2f7e8a42c61ab9cdcc9b1d
3
+ metadata.gz: cf72b6dc38be71835d9ab724648e9668001a71303900096894eb03ed05943daa
4
+ data.tar.gz: 1a11895216a151ad50af8c20a75767a55dde7ec4b8e307000c4adec045e68ebc
5
5
  SHA512:
6
- metadata.gz: ed99c7c1773807da639f6b3d811dfdd4a2a24d5c35fa51752e886797b19b9a57ed75156a233ecbe1e674e9bdb508c52ee05f885e100f57de1d23a0fd12b3219d
7
- data.tar.gz: 6bc55a8f935d178096ee28ad712d914163c83abb2134898e11d63c82ccc46191544585c1099e09862d2f1ccad84f23c071ddbee0b1b3f799e4ca53efc12ee950
6
+ metadata.gz: aa39cdc2cf85c9fd134c83e8f8e629db513de559fa62f6f6ac556e6a4f9a7cae634f6361e972b0f18c69ed322735627dca74d45832d5b65417e62abf289bbebc
7
+ data.tar.gz: 52fb1485939ae3ff8c7db3238a952f87e25f83562124f733cea4a966741fe5034739163c664193482992e7a5b5c7f09a1a36c6d499aacd7133fe24f83dde7410
data/CHANGELOG.md CHANGED
@@ -1,5 +1,33 @@
1
1
  ## [Unreleased]
2
2
 
3
+ ## [0.3.0] - 2026-11-24
4
+
5
+ - **Breaking:** `Trophies` validates the IDs it puts in request paths and raises `ArgumentError` before any request is made: `user_id` must be `'me'` or a numeric account ID, `np_communication_id` must look like `NPWR12345_00`, and `trophy_group_id` must be `'all'`, `'default'` or three digits such as `'001'`. Sony already answered HTTP 400 for anything else, including online IDs passed as `user_id`
6
+ - **Breaking:** `limit` and `offset` on `Trophies#trophy_titles`, `#title_trophies` and `#earned_trophies` must be Integers (`limit` at least 1, `offset` at least 0), or `ArgumentError` is raised. `trophy_titles` also rejects a `limit` above 800, Sony's maximum. Numeric strings such as `limit: '10'` are no longer accepted
7
+ - **Breaking:** `Trophies#title_trophies` and `#earned_trophies` raise `ArgumentError` for an unknown keyword instead of silently ignoring it
8
+ - `Trophies` query parameters are now URL-encoded by `Request`, and requests with no query parameters no longer end in a bare `?`
9
+ - `Auth.authenticate` and `Auth.new` accept `npsso:`, `client_id:` and `basic_token:`. The `PSN_*` environment variables remain the defaults
10
+ - `PSN_BASIC_TOKEN` is now read when authenticating instead of once when the gem loads, so setting it after `require` takes effect
11
+ - **Breaking:** removed the `Auth::BASIC_TOKEN` constant. Use `Auth::DEFAULT_BASIC_TOKEN`, or pass `basic_token:`
12
+ - `Trophies`, `Users` and `Account` accept `request:` to inject a request object in place of an access token
13
+ - `Request.new` accepts `open_timeout:`, `read_timeout:` and `write_timeout:`
14
+ - `Auth.authenticate`, `Auth.new`, `Session.authenticate` and `Session.new` accept the same three timeouts. `Auth` applies them to the authorisation request and the token exchange, and `Session` to the request it builds; passing them to `Session.new` with `request:` raises `ArgumentError`
15
+ - Added `PSN::Client::Session`, which shares one request across `trophies`, `users` and `account`, with `Session.authenticate` to build one from credentials
16
+ - **Breaking:** `Auth.authenticate` raises `PSN::Client::AuthenticationError` (or `TransportError`) instead of `RuntimeError`. Code rescuing `RuntimeError` must rescue `PSN::Client::Error` or a subclass
17
+ - **Breaking:** an API response of HTTP 401 raises `PSN::Client::AuthenticationError`, and GraphQL errors raise `PSN::Client::GraphQLError`. Both are still `PSN::Client::Error` subclasses
18
+ - Added structured errors: `PSN::Client::Error` now exposes `status`, `headers` and `body`, and new subclasses `AuthenticationError` (`error_code`), `RateLimitError` (`retry_at`), `GraphQLError` (`errors`, `data`), `TransportError` and `ParseError` cover authentication, HTTP 429, GraphQL, network and invalid-JSON failures
19
+ - Network failures and invalid JSON bodies no longer escape as `Net::*`, `SocketError`, `Errno::*`, `Faraday::*` or `JSON::ParserError`; the original exception is kept as `cause`
20
+ - A successful response with an empty body (such as HTTP 204) returns `nil` instead of raising `TypeError`. `Users#profile` returns `nil` for one, and an empty GraphQL response raises `ParseError`
21
+ - `Auth.authenticate` raises `RateLimitError` for HTTP 429 and plain `PSN::Client::Error` for HTTP 5xx, from either the authorisation request or the token exchange, instead of reporting them as `AuthenticationError`
22
+ - A malformed authorisation redirect raises `AuthenticationError`, and any `Faraday::Error`, corrupt compressed body or malformed response header raises `TransportError`
23
+ - `RateLimitError#retry_at` falls back to `Retry-After` when `X-RateLimit-Next-Available` is not a whole number
24
+ - `Auth.authenticate` no longer fails under debug logging when the token response has no `expires_in`
25
+ - Added `PSN::Client::Tokens`, which holds `access_token`, `expires_at`, `refresh_token` and `refresh_token_expires_at`, with `expired?` and `refresh_token_expired?`. Its `inspect` leaves the token values out
26
+ - Added `Auth.tokens` and `Auth#tokens`, which authenticate like `Auth.authenticate` but return `Tokens`, so the refresh token Sony issues is no longer discarded. `Auth.authenticate` still returns the access token string
27
+ - Added `Auth.refresh(refresh_token)` and `Auth#refresh`, which trade a refresh token for new `Tokens` without the NPSSO. A refresh token Sony no longer accepts raises `AuthenticationError` with an `error_code` of `"invalid_grant"`, and a `nil` or blank one raises `ArgumentError`
28
+ - Added `Session#tokens` and `Session.from_refresh_token(refresh_token)`, and `Session.new` accepts `Tokens` in place of an access token string. Nothing is refreshed automatically
29
+ - The `ParseError` for a malformed token response no longer repeats the JSON parser's message, which could quote the response body and any tokens in it. The parser's error is still available from `cause`
30
+
3
31
  ## [0.2.0] - 2026-11-23
4
32
 
5
33
  - `PSN_CLIENT_ID` and `PSN_BASIC_TOKEN` are now optional. They default to the PlayStation app's public OAuth client, so only `PSN_NPSSO` is required
data/CLAUDE.md CHANGED
@@ -10,15 +10,17 @@ This file provides guidance to Claude Code (claude.ai/code) when working with co
10
10
 
11
11
  ```bash
12
12
  bin/setup # bundle install (run first; nothing works under `bundle exec` until gems are installed)
13
- bundle exec rake # default task: spec + rubocop — exactly what CI runs (Ruby 3.1–3.4 matrix)
13
+ bundle exec rake # default task: spec + rubocop + rbs — exactly what CI runs (Ruby 3.1–3.4 matrix)
14
14
  bundle exec rspec # all specs; writes a SimpleCov report to coverage/
15
15
  bundle exec rspec spec/psn/client/trophies_spec.rb # one file
16
16
  bundle exec rspec spec/psn/client/trophies_spec.rb:55 # one example/group by line
17
17
  bundle exec rspec --only-failures # re-run failures (tracked in .rspec_status)
18
+ bundle exec rake rbs # `rbs validate` over sig/ (syntax and type names only; it does not compare sig/ with lib/)
18
19
  bundle exec rubocop # lint; `-a` (or `rake rubocop:autocorrect`) for safe autocorrect
19
20
  bin/console # IRB with the gem loaded
20
21
  bundle exec ruby bin/verify_trophies.rb # live smoke test against the real PSN API (needs the env vars below)
21
22
  bundle exec ruby bin/verify_users.rb # live smoke test of Users and Account; exits 1 if any check fails
23
+ bundle exec ruby bin/verify_auth.rb # live smoke test of Auth.tokens and Auth.refresh; prints expiry times, never tokens
22
24
  ```
23
25
 
24
26
  - `Gemfile.lock` is gitignored, so dependency versions resolve fresh per machine and per CI run. A lint failure that appears without a code change is usually a newer RuboCop (`NewCops: enable` is on).
@@ -28,39 +30,47 @@ bundle exec ruby bin/verify_users.rb # live smoke test of Users and Accou
28
30
 
29
31
  ## Architecture
30
32
 
31
- Everything lives under `PSN::Client` in `lib/psn/client/`; `require 'psn/client'` loads it all. The gem is two independent steps that the caller wires together with a plain token string — there is no client object holding state, and no token caching or refresh.
33
+ Everything lives under `PSN::Client` in `lib/psn/client/`; `require 'psn/client'` loads it all. The gem is two independent steps that the caller wires together with a plain token string, or with the optional `Session` facade (`session.rb`), which builds one `Request` and hands it to memoized `trophies`/`users`/`account`. Tokens are never cached or refreshed automatically: a refresh is an explicit call (`Auth.refresh`, `Session.from_refresh_token`), and a `Request` or `Session` keeps the access token it was built with.
32
34
 
33
- 1. **`Auth`** (`auth.rb`) — `Auth.authenticate` returns the access token as a *string*. It sends a GET to Sony's OAuth authorize URL carrying the `npsso` cookie, reads the auth code out of the redirect `Location` header (the redirect targets a mobile app scheme and is never followed), then exchanges the code for a JWT via the `oauth2` gem. Errors are derived from, in order: an `error_description` in the redirect query or JSON body, the `login_required` error code (expired NPSSO), or a generic fallback. They are logged and raised as plain `RuntimeError`, **not** `PSN::Client::Error`.
34
- 2. **API classes** — each is instantiated with the token, builds one `Request`, and returns the parsed JSON untouched (no model objects, no automatic pagination):
35
- - **`Trophies`** (`trophies.rb`) — builds paths and query strings by hand and calls `Request#get` on the mobile host.
35
+ 1. **`Auth`** (`auth.rb`) — `Auth.authenticate` returns the access token as a *string*; `Auth.tokens` runs the same flow and returns a `Tokens`. It sends a GET to Sony's OAuth authorize URL carrying the `npsso` cookie, reads the auth code out of the redirect `Location` header (the redirect targets a mobile app scheme and is never followed), then exchanges the code for a JWT via the `oauth2` gem. Errors are derived from, in order: an `error_description` in the redirect query or JSON body, the `login_required` error code (expired NPSSO), or a generic fallback. They are logged and raised as `AuthenticationError` (with `error_code` and the response's status/headers/body); `OAuth2::Error` from the token exchange becomes `AuthenticationError` too, a malformed JSON token response becomes `ParseError`, and network failures (including any `Faraday::Error`) become `TransportError`. The exception is by status (`Auth#response_error`): a 429 from either step raises `RateLimitError` and a 5xx plain `Error`, so outages are not mistaken for bad credentials. A redirect `Location` that cannot be parsed raises `AuthenticationError`.
36
+ - **`Auth.refresh(refresh_token)`** posts `grant_type=refresh_token` to the same token endpoint through `OAuth2::Client#get_token` and returns `Tokens`. It never reads the NPSSO, raises `ArgumentError` for a nil or blank token before any request, and shares the token exchange's rescue and error mapping (`request_token`).
37
+ - **`Tokens`** (`tokens.rb`) — a frozen value object: `access_token`, `expires_at`, `refresh_token`, `refresh_token_expires_at`, plus `expired?`/`refresh_token_expired?`. `Tokens.from_oauth2` builds one from the `OAuth2::AccessToken`. `inspect`/`to_s` leave the token values out.
38
+ - **`Session`** keeps the `Tokens` it was built from in `session.tokens` (nil when built from a string or `request:`). `Session.authenticate` and `Session.from_refresh_token` both go through `Session.new(tokens)`.
39
+ 2. **API classes** — each is instantiated with the token (building a `Request` via `Request.for`) or with an injected `request:`, and returns the parsed JSON untouched (no model objects, no automatic pagination):
40
+ - **`Trophies`** (`trophies.rb`) — builds paths by hand from validated IDs and calls `Request#get` on the mobile host with a `params:` hash.
36
41
  - **`Users`** (`users.rb`) — `search` (persisted GraphQL), `account_id`/`profile` by online ID (profile2 on the `community` host), `profile_by_account_id`, and `played_games`. Online IDs, account IDs and user IDs are validated against regexes before they reach a path.
37
42
  - **`Account`** (`account.rb`) — the signed-in account only: `devices` (`dms` host), and `library`, `purchased_games` and `summary` (persisted GraphQL; `summary` uses the `web` host).
38
- - **`Pagination`** (`pagination.rb`) — mixed into `Users` and `Account`; `validate_page_param!` raises `ArgumentError` unless a limit/offset/size/start is an Integer within bounds. Upper bounds are only set where Sony's limit was verified live.
39
- 3. **`Request`** (`request.rb`) — the single HTTP layer for API calls. `get`, `post` and `graphql` take a `host:` key into `HOSTS` (`:mobile` default, `:community`, `:dms`, `:web`), add the Bearer header and a `psn-client/<version>` User-Agent (Sony's search fails on Ruby's default), URL-encode `params:`, and merge caller `headers:`. `graphql` sends a persisted-query GET to `/graphql/v1/op` with `Apollo-Require-Preflight` and raises `Error` if the body has `errors`, even on HTTP 200. A non-2xx raises `PSN::Client::Error`, or its subclass `PrivacyError` for a 403 whose JSON error message mentions access control or privacy.
43
+ - **`Pagination`** (`pagination.rb`) — mixed into `Trophies`, `Users` and `Account`; `validate_page_param!` raises `ArgumentError` unless a limit/offset/size/start is an Integer within bounds. Upper bounds are only set where Sony's limit was verified live.
44
+ 3. **`Request`** (`request.rb`) — the single HTTP layer for API calls. `get`, `post` and `graphql` take a `host:` key into `HOSTS` (`:mobile` default, `:community`, `:dms`, `:web`), add the Bearer header and a `psn-client/<version>` User-Agent (Sony's search fails on Ruby's default), URL-encode `params:`, and merge caller `headers:`. `graphql` sends a persisted-query GET to `/graphql/v1/op` with `Apollo-Require-Preflight` and raises `GraphQLError` (keeping `errors` and partial `data`) if the body has `errors`, even on HTTP 200. A non-2xx raises `AuthenticationError` (401), `RateLimitError` (429), `PrivacyError` (403 whose JSON error message mentions access control or privacy) or plain `Error`; network exceptions become `TransportError` and invalid JSON `ParseError`; an empty 2xx body returns `nil` from `get`/`post` (callers must cope, as `Users#profile` does) and raises `ParseError` from `graphql`.
45
+
46
+ **Errors** (`errors.rb`) — everything raised from a PSN call derives from `PSN::Client::Error`, which carries `status`, `headers` (lowercased names) and `body` when built from a response (`Error.details_from(response)`). Raise inside the `rescue` so Ruby sets `cause`. `TransportError::NETWORK_ERRORS` is the shared list of `Net::HTTP` network exceptions.
40
47
 
41
48
  Things that are easy to get wrong:
42
49
 
43
- - **Configuration is env-only**: `PSN_NPSSO` (required), `PSN_CLIENT_ID` and `PSN_BASIC_TOKEN` (optional, defaulting to `Auth::DEFAULT_CLIENT_ID` / `DEFAULT_BASIC_TOKEN`, the PlayStation app's public OAuth client). `Auth::BASIC_TOKEN` is a constant read from ENV when the file is *loaded*; the other two are read lazily per call. Setting or stubbing `PSN_BASIC_TOKEN` after load has no effect (the `ENV.fetch` stub for it in `auth_spec.rb` is inert — use `stub_const` to control it).
50
+ - **Configuration defaults to env**: `Auth.new`/`Auth.authenticate` take `npsso:`, `client_id:` and `basic_token:`; each falls back to `PSN_NPSSO` (required), `PSN_CLIENT_ID` or `PSN_BASIC_TOKEN` (optional, defaulting to `Auth::DEFAULT_CLIENT_ID` / `DEFAULT_BASIC_TOKEN`, the PlayStation app's public OAuth client), all read lazily per call. `Request.new`, `Auth.new`/`Auth.authenticate` and `Session.new`/`Session.authenticate` take optional `open_timeout:`/`read_timeout:`/`write_timeout:` (seconds; `nil` keeps the library default). `Auth` applies them to its `Net::HTTP` call and, via `connection_opts`, to the `oauth2` token exchange; `Request.for` raises `ArgumentError` if options accompany an injected request.
51
+ - **Refresh tokens are short-lived and fixed** — verified live 2026-11-24: `refresh_token_expires_in` is 863999 (10 days, not the two months community docs give), a refresh returns the *same* refresh token and does not extend it (still true three hours after issue), and every NPSSO exchange issues a separate one. A refresh without `token_format=jwt` returns an opaque access token instead of a JWT. An unknown refresh token is HTTP 400 `invalid_grant`; a malformed one is HTTP 400 `invalid_request`. Never log a token or put a real one in a fixture.
44
52
  - **`np_service_name:` vs `platform:`** — title-scoped methods accept one or the other; passing both raises `ArgumentError`. `platform:` maps PS3/PS4/PSVita → `trophy` and PS5/PC → `trophy2` (`resolve_service_name`). Passing neither, or an unrecognised platform, silently omits `npServiceName`, which the API rejects for PS3/PS4/PSVita titles.
45
- - **Trophies query strings are not URL-encoded** (unlike `Request`'s `params:`) — `build_query_string` drops `nil` values and interpolates the rest raw. Optional `limit:`/`offset:` on `title_trophies`/`earned_trophies` travel through `**options`, so any other keyword passed there is silently ignored.
53
+ - **Trophies path segments are validated, not encoded** — `user_id`, `np_communication_id` and `trophy_group_id` pass through `user`/`title`/`group` (`segment` raises `ArgumentError` unless the value matches `USER_ID_PATTERN`, `NP_COMMUNICATION_ID_PATTERN` or `TROPHY_GROUP_ID_PATTERN`) before interpolation; a new path segment needs the same treatment. `user_id` is `'me'` or a numeric account ID, never an online ID. Query parameters go through `Request`'s `params:`; `title_params` builds the hash for title-scoped methods and drops `nil` values. `limit:`/`offset:` on `title_trophies`/`earned_trophies` are optional (no limit returns every trophy) and have no upper bound; only `trophy_titles` has one (`TROPHY_TITLES_MAX_LIMIT`, 800).
46
54
  - **`PSN.logger`** (`lib/psn/logger.rb`) defaults to `Rails.logger` when Rails is defined, otherwise stdout, and is memoized; override with `PSN.logger=`. Debug-level logging includes the raw auth code.
47
55
 
48
56
  `docs/andshrew/APIv2.md` is a vendored copy of the community PSN trophy API reference. Consult it for endpoint paths, parameters, and response shapes before adding or changing `Trophies` methods; it also documents endpoints not yet wrapped (per-title trophy summary by title ID, Game Help, language header, rate limits).
49
57
 
50
58
  ## Testing conventions
51
59
 
52
- No HTTP-mocking library is used and specs never touch the network. Collaborators are stubbed with `instance_double`:
60
+ Specs never touch the network: `spec_helper` requires `webmock/rspec`, which blocks real connections everywhere. Unit specs (`spec/psn/`) do not use WebMock's stubs; collaborators are stubbed with `instance_double`:
53
61
 
54
- - `Trophies` specs stub `Request.new`/`#get` and assert on the **exact path string**, so parameter order in `build_query_string` calls is part of the tested contract. `Users` and `Account` specs stub `Request.new` the same way and assert on `#get`/`#graphql` arguments.
62
+ - `Trophies` specs pass a `Request` double as `request:`, stub `#get` and assert on the exact path string and `params:` hash. `Users` and `Account` specs inject the double the same way and assert on `#get`/`#graphql` arguments. Only each `#initialize` group stubs `Request.new`, to cover the access-token path.
55
63
  - Stubs (`allow`) go in `before` blocks, never inside `it`; check calls afterwards with `have_received`. No cop enforces this.
56
- - `Auth` specs stub `Net::HTTP.new`, `OAuth2::Client`, `ENV.fetch`, and `PSN.logger`; `Request` specs stub `Net::HTTP.start`.
64
+ - `Auth` specs stub `Net::HTTP.new`, `OAuth2::Client`, `ENV.fetch`, and `PSN.logger`; `Request` specs stub `Net::HTTP.start`. Both return real `Net::HTTPResponse` objects built with `http_response(code, body, headers)` (`spec/support/http_responses.rb`, included in every example), because errors read `code`, `each_header` and `body`. `OAuth2::AccessToken` doubles need `refresh_token`, `expires_at` and `params` as well as `token`, because `Tokens.from_oauth2` reads them.
65
+
66
+ `spec/integration/` holds the end-to-end specs (tagged `:integration`, which mixes in `HTTPIntegration` from `spec/support/http_integration.rb`). They drive a real `Session` and let WebMock intercept the HTTP: `stub_request` in `before`, then `a_request(...).with(query:, headers:)` to assert on what went over the wire. Responses come from `spec/fixtures/*.json` via `fixture(name)` (raw body) or `json_fixture(name, status:, headers:)` (a `to_return` hash). Fixtures copy the shape of live responses but every value is made up — never commit a captured response without replacing account IDs, online IDs, device IDs and game data. Keep these few: one per kind of call or failure, not one per method.
57
67
 
58
- Monkey-patching is disabled (`RSpec.describe` and `expect` syntax only). RuboCop RSpec limits are set in `.rubocop.yml`: 15 lines per example, 3 expectations per example, 10 memoized helpers, 4 nesting levels. `Metrics/ParameterLists` is disabled only for `trophies.rb`.
68
+ Monkey-patching is disabled (`RSpec.describe` and `expect` syntax only). RuboCop RSpec limits are set in `.rubocop.yml`: 15 lines per example, 3 expectations per example, 10 memoized helpers, 4 nesting levels. `Metrics/ClassLength` is raised to 150 lines (`Auth` is at 149, so the next addition there needs an extraction), and `Metrics/ParameterLists` is disabled only for `trophies.rb`.
59
69
 
60
70
  ## Project rules (from `.github/copilot-instructions.md`)
61
71
 
62
72
  - Introduce no new RuboCop offenses.
63
73
  - Every Ruby file starts with `# frozen_string_literal: true`.
64
74
  - New functionality and bug fixes need RSpec coverage.
65
- - Update the RBS signatures in `sig/` whenever a method signature changes or a public method is added. `sig/` mirrors `lib/` one-to-one and includes private methods; nothing type-checks it in CI, so it must be kept in sync by hand.
75
+ - Update the RBS signatures in `sig/` whenever a method signature changes or a public method is added. `sig/` mirrors `lib/` one-to-one and includes private methods. CI runs `rake rbs`, which catches syntax errors and unknown type names but not drift from `lib/`, so it must still be kept in sync by hand. A third-party type named in `sig/` needs a stand-in under `spec/support/sig/` (as `OAuth2` has) or a `-r` library in the Rakefile.
66
76
  - When public API changes, update the `README.md` usage section and add an entry under `[Unreleased]` in `CHANGELOG.md`.
data/README.md CHANGED
@@ -24,9 +24,9 @@ Authentication only needs your NPSSO token. To get it, sign in at playstation.co
24
24
 
25
25
  | Variable | Required | Description |
26
26
  |---|---|---|
27
- | `PSN_NPSSO` | Yes | Your NPSSO token |
27
+ | `PSN_NPSSO` | Yes | Your NPSSO token. Not needed when you pass `npsso:` or use a [refresh token](#refresh-tokens) |
28
28
  | `PSN_CLIENT_ID` | No | The PSN OAuth2 client ID. Defaults to the PlayStation app's public client (`PSN::Client::Auth::DEFAULT_CLIENT_ID`) |
29
- | `PSN_BASIC_TOKEN` | No | The base64-encoded `client_id:client_secret`. Defaults to the PlayStation app's (`PSN::Client::Auth::DEFAULT_BASIC_TOKEN`). It is read once, when the gem loads |
29
+ | `PSN_BASIC_TOKEN` | No | The base64-encoded `client_id:client_secret`. Defaults to the PlayStation app's (`PSN::Client::Auth::DEFAULT_BASIC_TOKEN`). |
30
30
 
31
31
  The defaults are the same values listed in the [PSN API documentation](https://andshrew.github.io/PlayStation-Trophies/APIv2.html) and the bundled [API reference](docs/andshrew/APIv2.md). If you override `PSN_CLIENT_ID`, override `PSN_BASIC_TOKEN` to match.
32
32
 
@@ -40,18 +40,100 @@ access_token = PSN::Client::Auth.authenticate
40
40
 
41
41
  `authenticate` exchanges your NPSSO token for a short-lived PSN access token string.
42
42
 
43
+ The environment variables are only defaults. Pass credentials explicitly to use different ones per call, for example one NPSSO per user:
44
+
45
+ ```ruby
46
+ access_token = PSN::Client::Auth.authenticate(npsso: user.npsso)
47
+ # client_id: and basic_token: can be passed the same way
48
+ ```
49
+
50
+ `Auth.tokens` runs the same exchange with the same options, and returns a `PSN::Client::Tokens` holding the refresh token and both expiry times as well:
51
+
52
+ ```ruby
53
+ tokens = PSN::Client::Auth.tokens
54
+ tokens.access_token # the string authenticate returns
55
+ tokens.expires_at # Time, about an hour away
56
+ tokens.refresh_token
57
+ tokens.refresh_token_expires_at # Time
58
+ tokens.expired? # also refresh_token_expired?
59
+ ```
60
+
61
+ See [Refresh tokens](#refresh-tokens) for what the refresh token is for.
62
+
63
+ ### Sessions
64
+
65
+ `PSN::Client::Session` shares one access token and one HTTP request object across the API classes described below:
66
+
67
+ ```ruby
68
+ session = PSN::Client::Session.authenticate # or .authenticate(npsso: '...')
69
+ session = PSN::Client::Session.new(access_token) # from a token you already have
70
+
71
+ session.trophies.trophy_summary
72
+ session.users.profile(online_id: 'example_user')
73
+ session.account.devices
74
+ ```
75
+
76
+ A session built by `Session.authenticate` or `Session.from_refresh_token` keeps its `Tokens` in `session.tokens`. It is `nil` for a session built from an access token string or a `request:`.
77
+
78
+ ### Refresh tokens
79
+
80
+ An access token lasts about an hour. The refresh token issued with it gets a new one without the NPSSO, so an app can store the refresh token instead of asking for the NPSSO each time:
81
+
82
+ ```ruby
83
+ session = PSN::Client::Session.authenticate(npsso: npsso)
84
+ store.save(session.tokens.refresh_token, session.tokens.refresh_token_expires_at)
85
+
86
+ # later, without the NPSSO
87
+ session = PSN::Client::Session.from_refresh_token(store.refresh_token)
88
+ ```
89
+
90
+ Without a session, `PSN::Client::Auth.refresh(refresh_token)` returns the new `Tokens`, and `Session.new` accepts them in place of an access token string. Both refresh calls take `client_id:`, `basic_token:` and the timeouts, like `authenticate`.
91
+
92
+ Nothing is refreshed automatically, and a session keeps the access token it was built with. Once that expires, API calls raise `AuthenticationError`; build a new session with `from_refresh_token`.
93
+
94
+ This is how Sony treated refresh tokens when checked on 2026-11-24. Sony does not document it, so it may change:
95
+
96
+ - A refresh token lasted 10 days (`refresh_token_expires_in` was 863999 seconds), which is shorter than the NPSSO's two months.
97
+ - Refreshing returned the same refresh token and did not extend it. `refresh_token_expires_at` stays where the NPSSO exchange put it, so store it and expect to need the NPSSO again after that time.
98
+ - Every NPSSO exchange issued a new, separate refresh token with a fresh 10 days.
99
+
100
+ A refresh token Sony no longer accepts raises `AuthenticationError` with an `error_code` of `"invalid_grant"`. A `nil` or blank one raises `ArgumentError` before any request is made.
101
+
102
+ Treat both tokens as secrets. `Tokens#inspect` leaves the values out, and the gem never logs them.
103
+
104
+ ### Timeouts and custom transport
105
+
106
+ `open_timeout:`, `read_timeout:` and `write_timeout:` are in seconds, and each keeps Ruby's default when omitted. `Session` accepts them directly; `Session.authenticate` and `Auth.authenticate` also apply them to the authentication requests:
107
+
108
+ ```ruby
109
+ session = PSN::Client::Session.authenticate(open_timeout: 5, read_timeout: 10, write_timeout: 10)
110
+ session = PSN::Client::Session.new(access_token, open_timeout: 5, read_timeout: 10)
111
+ ```
112
+
113
+ `PSN::Client::Request` accepts the same timeouts, and every API class and `Session` accepts a `request:` in place of an access token:
114
+
115
+ ```ruby
116
+ request = PSN::Client::Request.new(access_token, open_timeout: 5, read_timeout: 10, write_timeout: 10)
117
+
118
+ session = PSN::Client::Session.new(request: request)
119
+ trophies = PSN::Client::Trophies.new(request: request)
120
+ ```
121
+
122
+ `request:` can be any object that responds to `get`, `post` and `graphql` like `Request` does, which is useful for adding retries or caching, or for injecting a fake in tests.
123
+
43
124
  ### Trophy data
44
125
 
45
- Pass the access token to `PSN::Client::Trophies` and call the relevant method. All `user_id` parameters default to `'me'` (the authenticated user).
126
+ Pass the access token to `PSN::Client::Trophies` and call the relevant method. All `user_id` parameters default to `'me'` (the authenticated user); for another player pass their numeric account ID (see `Users#account_id`), not their online ID.
46
127
 
47
128
  ```ruby
48
129
  trophies = PSN::Client::Trophies.new(access_token)
49
130
 
50
131
  # Overall trophy level, points, and earned counts
51
132
  trophies.trophy_summary
52
- trophies.trophy_summary(user_id: 'example_user')
133
+ trophies.trophy_summary(user_id: '1234567890123456789')
53
134
 
54
135
  # List of trophy titles (games) for a user
136
+ # (limit defaults to 800, the maximum)
55
137
  trophies.trophy_titles
56
138
  trophies.trophy_titles(limit: 100, offset: 0)
57
139
 
@@ -68,8 +150,13 @@ trophies.title_trophies(np_communication_id: 'NPWR12345_00', platform: 'PS5')
68
150
 
69
151
  # Trophy earned status for a user on a title
70
152
  trophies.earned_trophies(np_communication_id: 'NPWR12345_00', platform: 'PS5')
153
+
154
+ # Both trophy lists return every trophy unless paged with limit:/offset:
155
+ trophies.title_trophies(np_communication_id: 'NPWR12345_00', platform: 'PS5', limit: 50, offset: 0)
71
156
  ```
72
157
 
158
+ `limit` and `offset` must be Integers (`limit` at least 1, `offset` at least 0), or `ArgumentError` is raised. `trophy_titles` also rejects a `limit` above 800. `ArgumentError` is raised too for a `user_id` that is not `'me'` or numeric, an `np_communication_id` that does not look like `NPWR12345_00`, or a `trophy_group_id` other than `'all'`, `'default'` or three digits such as `'001'`.
159
+
73
160
  ### User data
74
161
 
75
162
  `PSN::Client::Users` looks up other players and their games. These use undocumented Sony endpoints that can change without notice.
@@ -98,7 +185,7 @@ users.played_games(user_id: '1234567890123456789', limit: 50, offset: 0)
98
185
 
99
186
  `profile` and `account_id` raise `ArgumentError` for an invalid online ID, `profile_by_account_id` for a non-numeric account ID, and `played_games` for a `user_id` that is not `'me'` or numeric, or a `limit` above 200.
100
187
 
101
- If a user's privacy settings block the request, Sony responds with HTTP 403 and the client raises `PSN::Client::PrivacyError`, a subclass of `PSN::Client::Error`.
188
+ If a user's privacy settings block the request, Sony responds with HTTP 403 and the client raises `PSN::Client::PrivacyError` (see [Errors](#errors)).
102
189
 
103
190
  ```ruby
104
191
  begin
@@ -132,6 +219,45 @@ account.summary.dig('data', 'oracleUserProfileRetrieve')
132
219
 
133
220
  `library` raises `ArgumentError` for a `limit` above 100. `library`, `purchased_games` and `summary` return the raw GraphQL response body.
134
221
 
222
+ ### Errors
223
+
224
+ Every error the gem raises from a PSN call is a `PSN::Client::Error` (argument validation still raises `ArgumentError`). Rescue a subclass to handle a specific failure:
225
+
226
+ | Class | Raised when |
227
+ | --- | --- |
228
+ | `PSN::Client::AuthenticationError` | `Auth.authenticate` or `Auth.tokens` is refused (expired or invalid NPSSO, rejected token exchange, malformed redirect), `Auth.refresh` is refused, or an API call returns HTTP 401. `error_code` holds Sony's OAuth error code, such as `"login_required"` for an expired NPSSO or `"invalid_grant"` for a refresh token Sony no longer accepts. |
229
+ | `PSN::Client::PrivacyError` | HTTP 403 caused by the target user's privacy settings |
230
+ | `PSN::Client::RateLimitError` | HTTP 429, from an API call or from `Auth`. `retry_at` is a `Time` from `X-RateLimit-Next-Available` or `Retry-After` (seconds counted from when the error was raised), or `nil` |
231
+ | `PSN::Client::GraphQLError` | A GraphQL response carries `errors`, even on HTTP 200. `errors` is the raw array and `data` any partial result |
232
+ | `PSN::Client::TransportError` | No usable response was received: DNS, connection, TLS or timeout failure, or a response that could not be read (malformed headers, corrupt compressed body) |
233
+ | `PSN::Client::ParseError` | A successful response body, or the token exchange response, is not valid JSON, or a GraphQL response is empty (any other empty body returns `nil` instead) |
234
+ | `PSN::Client::Error` | Any other non-2xx response, including an HTTP 5xx from `Auth` |
235
+
236
+ Errors built from a response expose `status` (Integer), `headers` (Hash with lowercase names) and `body` (raw String); otherwise these are `nil`/empty. The original exception, for transport, parse and token-exchange failures, is available from `cause`.
237
+
238
+ ```ruby
239
+ reauthenticated = false
240
+ rate_limit_retries = 0
241
+ begin
242
+ trophies.trophy_titles
243
+ rescue PSN::Client::RateLimitError => e
244
+ raise if (rate_limit_retries += 1) > 3
245
+
246
+ # retry_at is nil when Sony sent no usable header, so wait a fixed minute instead
247
+ sleep(e.retry_at ? [e.retry_at - Time.now, 1].max : 60)
248
+ retry
249
+ rescue PSN::Client::AuthenticationError
250
+ raise if reauthenticated # the fresh token was rejected too
251
+
252
+ reauthenticated = true
253
+ # API objects hold the token they were created with, so rebuild them with the new one
254
+ trophies = PSN::Client::Trophies.new(PSN::Client::Auth.authenticate)
255
+ retry
256
+ rescue PSN::Client::Error => e
257
+ warn "PSN request failed (#{e.status.inspect}): #{e.message}"
258
+ end
259
+ ```
260
+
135
261
  ## Development
136
262
 
137
263
  After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake spec` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment.
@@ -30,8 +30,10 @@ module PSN
30
30
  # Without this header the call returns HTTP 400 "Cannot query field" (verified live 2026-07-11).
31
31
  SUMMARY_HEADERS = { 'apollographql-client-name' => 'oracle' }.freeze
32
32
 
33
- def initialize(access_token)
34
- @request = Request.new(access_token)
33
+ # Pass an access token, or `request:` to inject a Request (or any object
34
+ # responding to the same methods) instead of building one.
35
+ def initialize(access_token = nil, request: nil)
36
+ @request = Request.for(access_token, request)
35
37
  end
36
38
 
37
39
  def devices
@@ -4,11 +4,13 @@ require 'net/http'
4
4
  require 'uri'
5
5
  require 'oauth2'
6
6
  require 'json'
7
+ require_relative 'errors'
8
+ require_relative 'tokens'
7
9
 
8
10
  module PSN
9
11
  module Client
10
- # Handles acquiring PSN access tokens by exchanging an NPSSO cookie
11
- # for an authorization code and then exchanging that code for a token.
12
+ # Acquires PSN tokens, either by exchanging an NPSSO cookie for an authorization code
13
+ # and that code for tokens, or by trading a saved refresh token for new ones.
12
14
  class Auth
13
15
  AUTH_URL = 'https://ca.account.sony.com/api/authz/v3/'
14
16
  # The PlayStation Android app's public OAuth client, the same for every user (see
@@ -16,25 +18,69 @@ module PSN
16
18
  DEFAULT_CLIENT_ID = '09515159-7237-4370-9b40-3806e67c0891'
17
19
  # Base64 of "<DEFAULT_CLIENT_ID>:<client secret>".
18
20
  DEFAULT_BASIC_TOKEN = 'MDk1MTUxNTktNzIzNy00MzcwLTliNDAtMzgwNmU2N2MwODkxOnVjUGprYTV0bnRCMktxc1A='
19
- BASIC_TOKEN = ENV.fetch('PSN_BASIC_TOKEN', DEFAULT_BASIC_TOKEN)
20
21
 
21
- class << self
22
- def authenticate
23
- new.authenticate
24
- end
22
+ REDIRECT_URI = 'com.scee.psxandroid.scecompcall://redirect'
23
+ SCOPE = 'psn:mobile.v2.core psn:clientapp'
24
+ TIMEOUT_OPTIONS = %i[open_timeout read_timeout write_timeout].freeze
25
+
26
+ def self.authenticate(**options)
27
+ new(**options).authenticate
28
+ end
29
+
30
+ def self.tokens(**options)
31
+ new(**options).tokens
32
+ end
33
+
34
+ def self.refresh(refresh_token, **options)
35
+ new(**options).refresh(refresh_token)
36
+ end
37
+
38
+ # Each credential falls back to its environment variable (PSN_NPSSO, PSN_CLIENT_ID,
39
+ # PSN_BASIC_TOKEN), read when it is used, and then to the default. Only #tokens and
40
+ # #authenticate use the NPSSO. Timeouts are in seconds and apply to the authorisation
41
+ # request and to every token request; nil keeps the HTTP library's default.
42
+ def initialize(npsso: nil, client_id: nil, basic_token: nil, **timeouts)
43
+ unknown = timeouts.keys - TIMEOUT_OPTIONS
44
+ raise ArgumentError, "unknown keyword: #{unknown.map(&:inspect).join(', ')}" unless unknown.empty?
45
+
46
+ @npsso = npsso
47
+ @client_id = client_id
48
+ @basic_token = basic_token
49
+ @timeouts = timeouts.compact
25
50
  end
26
51
 
52
+ # The access token alone; #tokens also returns the refresh token and both expiry times.
27
53
  def authenticate
54
+ tokens.access_token
55
+ end
56
+
57
+ # Exchanges the NPSSO for a new access token and refresh token.
58
+ def tokens
28
59
  PSN.logger.info('Getting new PSN access token')
29
60
 
30
61
  code = fetch_auth_code
31
62
  PSN.logger.debug { "Fetched authorisation code: #{code}" }
32
63
 
33
64
  access_token = fetch_token(code)
34
- PSN.logger.debug { "Fetched access token which expires in: #{access_token.expires_in / 60} minutes" }
65
+ minutes = access_token.expires_in&.div(60) || 'unknown'
66
+ PSN.logger.debug { "Fetched access token which expires in: #{minutes} minutes" }
35
67
  PSN.logger.info('Acquired new PSN access token')
36
68
 
37
- access_token.token
69
+ Tokens.from_oauth2(access_token)
70
+ end
71
+
72
+ # Trades a refresh token from an earlier #tokens or #refresh for new tokens, without the
73
+ # NPSSO. A refresh token Sony no longer accepts raises AuthenticationError with the
74
+ # error_code "invalid_grant".
75
+ def refresh(refresh_token)
76
+ blank = !refresh_token.is_a?(String) || refresh_token.strip.empty?
77
+ raise ArgumentError, 'a refresh token is required' if blank
78
+
79
+ PSN.logger.info('Refreshing PSN access token')
80
+ access_token = fetch_refreshed_token(refresh_token)
81
+ PSN.logger.info('Refreshed PSN access token')
82
+
83
+ Tokens.from_oauth2(access_token, fallback_refresh_token: refresh_token)
38
84
  end
39
85
 
40
86
  private
@@ -42,19 +88,26 @@ module PSN
42
88
  def fetch_auth_code
43
89
  uri = URI(auth_url)
44
90
 
45
- response = http_for(uri).request(request_for(uri))
91
+ response = request_auth_code(uri)
46
92
  if response['location'].nil?
47
- message = extract_error_message(response)
48
- PSN.logger.error(message)
49
- raise message
93
+ body = parse_json(response.body)
94
+ fail_with(body['error_description'] || 'Failed to fetch PSN auth code, location header missing', response,
95
+ error_code: body['error'])
50
96
  end
51
97
 
52
- parse_code(response['location'])
98
+ parse_code(response)
99
+ end
100
+
101
+ def request_auth_code(uri)
102
+ http_for(uri).request(request_for(uri))
103
+ rescue *TransportError::NETWORK_ERRORS => e
104
+ log_and_raise TransportError.new("PSN authorisation request failed: #{e.class}: #{e.message}")
53
105
  end
54
106
 
55
107
  def http_for(uri)
56
108
  http = Net::HTTP.new(uri.host, uri.port)
57
109
  http.use_ssl = uri.scheme == 'https'
110
+ @timeouts.each { |name, seconds| http.public_send("#{name}=", seconds) }
58
111
  http
59
112
  end
60
113
 
@@ -65,33 +118,74 @@ module PSN
65
118
  end
66
119
 
67
120
  def fetch_token(code)
68
- client.auth_code.get_token(code,
69
- redirect_uri: 'com.scee.psxandroid.scecompcall://redirect',
70
- token_format: 'jwt',
71
- headers: { Authorization: "Basic #{BASIC_TOKEN}" })
121
+ request_token('exchange') do
122
+ client.auth_code.get_token(code, redirect_uri: REDIRECT_URI, token_format: 'jwt',
123
+ headers: { Authorization: "Basic #{basic_token}" })
124
+ end
125
+ end
126
+
127
+ def fetch_refreshed_token(refresh_token)
128
+ request_token('refresh') do
129
+ client.get_token({ grant_type: 'refresh_token', refresh_token: refresh_token, scope: SCOPE,
130
+ token_format: 'jwt', headers: { Authorization: "Basic #{basic_token}" } })
131
+ end
132
+ end
133
+
134
+ # Runs a token request, turning its failures into this gem's errors. +action+ names the
135
+ # request in the error message.
136
+ def request_token(action)
137
+ yield
138
+ rescue OAuth2::Error, JSON::ParserError, Faraday::Error => e
139
+ log_and_raise token_error(e, action)
140
+ end
141
+
142
+ def token_error(error, action)
143
+ case error
144
+ when OAuth2::Error
145
+ response_error("PSN token #{action} failed: #{error.description || error.message}",
146
+ error.response, error_code: error.code)
147
+ # oauth2 parses the token body before returning the response, so none is available to attach.
148
+ # The JSON error can quote that body, tokens included, so it is left to +cause+.
149
+ when JSON::ParserError then ParseError.new('PSN token response was not valid JSON')
150
+ else TransportError.new("PSN token request failed: #{error.class}: #{error.message}")
151
+ end
72
152
  end
73
153
 
74
- def parse_code(location)
75
- params = URI.decode_www_form(URI(location).query.to_s).to_h
76
- code = params['code']
154
+ def parse_code(response)
155
+ params = URI.decode_www_form(URI(response['location']).query.to_s).to_h
156
+ return params['code'] if params['code']
77
157
 
78
- return code if code
158
+ fail_with(get_error_message(params['error'], params['error_description']), response,
159
+ error_code: params['error'])
160
+ rescue URI::InvalidURIError, ArgumentError => e
161
+ fail_with("PSN authorisation redirect was malformed: #{e.message}", response, error_code: nil)
162
+ end
79
163
 
80
- raise_auth_error(params)
164
+ def fail_with(message, response, error_code:)
165
+ log_and_raise response_error(message, response, error_code: error_code)
81
166
  end
82
167
 
83
- def raise_auth_error(params)
84
- message = get_error_message(params['error'], params['error_description'])
85
- PSN.logger.error(message)
86
- raise message
168
+ # A rate limit or a Sony outage says nothing about the credentials, so only the
169
+ # remaining statuses are reported as AuthenticationError.
170
+ def response_error(message, response, error_code:)
171
+ details = Error.details_from(response)
172
+ case details[:status]
173
+ when 429 then RateLimitError.new(message, **details)
174
+ when 500.. then Error.new(message, **details)
175
+ else AuthenticationError.new(message, error_code: error_code, **details)
176
+ end
87
177
  end
88
178
 
89
- def extract_error_message(response)
90
- error_description = JSON.parse(response.body).fetch('error_description', nil)
179
+ def log_and_raise(error)
180
+ PSN.logger.error(error.message)
181
+ raise error
182
+ end
91
183
 
92
- error_description || 'Failed to fetch PSN auth code, location header missing'
93
- rescue JSON::ParserError, NoMethodError, TypeError
94
- 'Failed to fetch PSN auth code, location header missing'
184
+ def parse_json(body)
185
+ parsed = JSON.parse(body.to_s)
186
+ parsed.is_a?(Hash) ? parsed : {}
187
+ rescue JSON::ParserError
188
+ {}
95
189
  end
96
190
 
97
191
  def get_error_message(error, error_description = nil)
@@ -105,17 +199,23 @@ module PSN
105
199
  end
106
200
 
107
201
  def client
108
- @client ||= OAuth2::Client.new(ENV.fetch('PSN_CLIENT_ID', DEFAULT_CLIENT_ID), '', site: AUTH_URL)
202
+ @client ||= OAuth2::Client.new(client_id, '', site: AUTH_URL, connection_opts: { request: @timeouts })
109
203
  end
110
204
 
111
205
  def auth_url
112
- client.auth_code.authorize_url(access_type: 'offline',
113
- redirect_uri: 'com.scee.psxandroid.scecompcall://redirect',
114
- scope: 'psn:mobile.v2.core psn:clientapp')
206
+ client.auth_code.authorize_url(access_type: 'offline', redirect_uri: REDIRECT_URI, scope: SCOPE)
115
207
  end
116
208
 
117
209
  def npsso_cookie
118
- "npsso=#{ENV.fetch('PSN_NPSSO', nil)}"
210
+ "npsso=#{@npsso || ENV.fetch('PSN_NPSSO', nil)}"
211
+ end
212
+
213
+ def client_id
214
+ @client_id || ENV.fetch('PSN_CLIENT_ID', DEFAULT_CLIENT_ID)
215
+ end
216
+
217
+ def basic_token
218
+ @basic_token || ENV.fetch('PSN_BASIC_TOKEN', DEFAULT_BASIC_TOKEN)
119
219
  end
120
220
  end
121
221
  end