psn-client 0.1.0 → 0.2.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: 2dbe67ce2822ac72465d94380662813f2f2ef909842d6b7019f36bd4bfa663f7
4
- data.tar.gz: cfb5d533a12dce7ee57c37fcb0c4e47f84bd591081869110f647047b4e1765fc
3
+ metadata.gz: 3db23ae67a963e9df40f06cde9bb2841d51883e1a9c7299fe626a6aeaab4c2fe
4
+ data.tar.gz: 4e1ff777570091db644b84aaec871566df8539042d2f7e8a42c61ab9cdcc9b1d
5
5
  SHA512:
6
- metadata.gz: 5fde12bd20b84224bca82f475a09a673dae09d7c96fa79e34ec27f50c80313fd96f11086b51bdfb5be8a7ed00e0e9d3a41fde28beda642a335cc4e9f242271d7
7
- data.tar.gz: 13f7f23e307ee361f265897b0b48d41d8296b47e32be431ed59d16f9ce97b3e92e9114b0326b5a556358619cc64f9fea63d81b7039af0619101e9f29504b5b62
6
+ metadata.gz: ed99c7c1773807da639f6b3d811dfdd4a2a24d5c35fa51752e886797b19b9a57ed75156a233ecbe1e674e9bdb508c52ee05f885e100f57de1d23a0fd12b3219d
7
+ data.tar.gz: 6bc55a8f935d178096ee28ad712d914163c83abb2134898e11d63c82ccc46191544585c1099e09862d2f1ccad84f23c071ddbee0b1b3f799e4ca53efc12ee950
data/CHANGELOG.md CHANGED
@@ -1,5 +1,15 @@
1
1
  ## [Unreleased]
2
2
 
3
+ ## [0.2.0] - 2026-11-23
4
+
5
+ - `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
6
+ - Added `PSN::Client::Users` with `search`, `account_id`, `profile`, `profile_by_account_id` and `played_games`
7
+ - Added `PSN::Client::Account` with `devices`, `library`, `purchased_games` and `summary`
8
+ - Pagination arguments on `Users` and `Account` (`limit`, `offset`, `size`, `start`) must be Integers within bounds, or `ArgumentError` is raised
9
+ - Added `PSN::Client::PrivacyError`, raised when a user's privacy settings block a request
10
+ - Added multi-host, POST and persisted-query GraphQL support to `Request`
11
+ - `Request` now sends `User-Agent: psn-client/<version>` on every request (Sony's search backend rejects Net::HTTP's default `Ruby`)
12
+
3
13
  ## [0.1.0] - 2026-03-14
4
14
 
5
15
  - Initial release
data/CLAUDE.md ADDED
@@ -0,0 +1,66 @@
1
+ # CLAUDE.md
2
+
3
+ This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
4
+
5
+ ## Project
6
+
7
+ `psn-client` is a Ruby gem (Ruby >= 3.1) wrapping the PlayStation Network API: NPSSO-cookie authentication plus trophy, user and account endpoints. The only runtime dependency is `oauth2`; HTTP is done with `Net::HTTP` directly.
8
+
9
+ ## Commands
10
+
11
+ ```bash
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)
14
+ bundle exec rspec # all specs; writes a SimpleCov report to coverage/
15
+ bundle exec rspec spec/psn/client/trophies_spec.rb # one file
16
+ bundle exec rspec spec/psn/client/trophies_spec.rb:55 # one example/group by line
17
+ bundle exec rspec --only-failures # re-run failures (tracked in .rspec_status)
18
+ bundle exec rubocop # lint; `-a` (or `rake rubocop:autocorrect`) for safe autocorrect
19
+ bin/console # IRB with the gem loaded
20
+ bundle exec ruby bin/verify_trophies.rb # live smoke test against the real PSN API (needs the env vars below)
21
+ bundle exec ruby bin/verify_users.rb # live smoke test of Users and Account; exits 1 if any check fails
22
+ ```
23
+
24
+ - `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).
25
+ - The suite is at 100% line coverage. No minimum is enforced, and single-file runs report a low percentage — ignore it.
26
+ - Breakpoints: add `binding.break` and run under `bundle exec`. The `debug` gem is already required by `spec_helper`, `bin/console`, and `bin/verify_trophies.rb`.
27
+ - Release: bump `lib/psn/client/version.rb`, move the `[Unreleased]` entries in `CHANGELOG.md` under the new version, then `bundle exec rake release` (tags, pushes, and publishes to RubyGems — only on explicit request). Packaged files come from `git ls-files`, so untracked files are not shipped.
28
+
29
+ ## Architecture
30
+
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.
32
+
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.
36
+ - **`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
+ - **`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.
40
+
41
+ Things that are easy to get wrong:
42
+
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).
44
+ - **`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.
46
+ - **`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
+
48
+ `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
+
50
+ ## Testing conventions
51
+
52
+ No HTTP-mocking library is used and specs never touch the network. Collaborators are stubbed with `instance_double`:
53
+
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.
55
+ - 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`.
57
+
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`.
59
+
60
+ ## Project rules (from `.github/copilot-instructions.md`)
61
+
62
+ - Introduce no new RuboCop offenses.
63
+ - Every Ruby file starts with `# frozen_string_literal: true`.
64
+ - 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.
66
+ - When public API changes, update the `README.md` usage section and add an entry under `[Unreleased]` in `CHANGELOG.md`.
data/README.md CHANGED
@@ -20,13 +20,15 @@ gem install psn-client
20
20
 
21
21
  ### Environment variables
22
22
 
23
- Authentication requires three environment variables. You can find the values in the [PSN API documentation](https://andshrew.github.io/PlayStation-Trophies/APIv2.html) or the bundled [API reference](docs/andshrew/APIv2.md).
23
+ Authentication only needs your NPSSO token. To get it, sign in at playstation.com, then open <https://ca.account.sony.com/api/v1/ssocookie> and copy the `npsso` value. It lasts about two months.
24
24
 
25
- | Variable | Description |
26
- |---|---|
27
- | `PSN_NPSSO` | Your NPSSO token, obtained from a browser session on PlayStation.com |
28
- | `PSN_BASIC_TOKEN` | The base64-encoded `client_id:client_secret` for the PSN OAuth2 client |
29
- | `PSN_CLIENT_ID` | The PSN OAuth2 client ID |
25
+ | Variable | Required | Description |
26
+ |---|---|---|
27
+ | `PSN_NPSSO` | Yes | Your NPSSO token |
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 |
30
+
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.
30
32
 
31
33
  ### Authentication
32
34
 
@@ -68,6 +70,68 @@ trophies.title_trophies(np_communication_id: 'NPWR12345_00', platform: 'PS5')
68
70
  trophies.earned_trophies(np_communication_id: 'NPWR12345_00', platform: 'PS5')
69
71
  ```
70
72
 
73
+ ### User data
74
+
75
+ `PSN::Client::Users` looks up other players and their games. These use undocumented Sony endpoints that can change without notice.
76
+
77
+ ```ruby
78
+ users = PSN::Client::Users.new(access_token)
79
+
80
+ # Search for players (raw GraphQL response, first page only; near-matches included)
81
+ results = users.search('example')
82
+ results.dig('data', 'universalContextSearch', 'results')
83
+
84
+ # Resolve an online ID to an account ID string, via the profile
85
+ # (raises PSN::Client::Error if not found, ArgumentError for an invalid online ID)
86
+ users.account_id('example_user')
87
+
88
+ # Profile for an online ID (returns the "profile" hash)
89
+ users.profile(online_id: 'example_user')
90
+
91
+ # Profile for a numeric account ID
92
+ users.profile_by_account_id(account_id: '1234567890123456789')
93
+
94
+ # Games played by a user (user_id defaults to 'me'; limit defaults to 200, the maximum)
95
+ users.played_games
96
+ users.played_games(user_id: '1234567890123456789', limit: 50, offset: 0)
97
+ ```
98
+
99
+ `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
+
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`.
102
+
103
+ ```ruby
104
+ begin
105
+ users.played_games(user_id: account_id)
106
+ rescue PSN::Client::PrivacyError
107
+ # the user has hidden this data
108
+ end
109
+ ```
110
+
111
+ ### Signed-in account
112
+
113
+ `PSN::Client::Account` returns data about the authenticated account only. Like `Users`, it relies on undocumented Sony endpoints that can change.
114
+
115
+ ```ruby
116
+ account = PSN::Client::Account.new(access_token)
117
+
118
+ # Registered devices
119
+ account.devices
120
+
121
+ # Game library (limit defaults to 100, the maximum)
122
+ account.library
123
+ account.library(limit: 20)
124
+
125
+ # Purchased games (size defaults to 200, start to 0)
126
+ account.purchased_games
127
+ account.purchased_games(size: 50, start: 0)
128
+
129
+ # Profile summary, including online ID and account ID
130
+ account.summary.dig('data', 'oracleUserProfileRetrieve')
131
+ ```
132
+
133
+ `library` raises `ArgumentError` for a `limit` above 100. `library`, `purchased_games` and `summary` return the raw GraphQL response body.
134
+
71
135
  ## Development
72
136
 
73
137
  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.
@@ -0,0 +1,59 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative 'pagination'
4
+ require_relative 'request'
5
+
6
+ module PSN
7
+ module Client
8
+ # Handles requests about the authenticated account: devices, library, purchases and summary
9
+ class Account
10
+ include Pagination
11
+
12
+ # Served by the DMS host, which has no /api suffix, so the path carries it. Verified live 2026-11-22.
13
+ DEVICES_PATH = '/api/v1/devices/accounts/me'
14
+ DEVICES_PARAMS = { 'includeFields' => 'device,systemData', 'platform' => 'PS5,PS4,PS3,PSVita' }.freeze
15
+ LIBRARY_OPERATION = 'getUserGameList'
16
+ # Persisted query hash (and categories below) verified live 2026-11-22.
17
+ LIBRARY_HASH = 'e0136f81d7d1fb6be58238c574e9a46e1c0cc2f7f6977a08a5a46f224523a004'
18
+ LIBRARY_CATEGORIES = 'ps4_game,ps5_native_game'
19
+ # A limit above 100 is rejected by Sony (verified live 2026-07).
20
+ LIBRARY_MAX_LIMIT = 100
21
+ PURCHASED_OPERATION = 'getPurchasedGameList'
22
+ PURCHASED_HASH = '827a423f6a8ddca4107ac01395af2ec0eafd8396fc7fa204aaf9b7ed2eefa168'
23
+ # Persisted query and variables verified live 2026-11-22.
24
+ PURCHASED_VARIABLES = {
25
+ 'isActive' => true, 'platform' => %w[ps4 ps5], 'sortBy' => 'ACTIVE_DATE', 'sortDirection' => 'desc'
26
+ }.freeze
27
+ SUMMARY_OPERATION = 'getProfileOracle'
28
+ # Persisted query hash verified live 2026-11-22.
29
+ SUMMARY_HASH = 'fc0d765f537f3dce3e0d91c71e85daa401042ba43066acde9f8f584faced10df'
30
+ # Without this header the call returns HTTP 400 "Cannot query field" (verified live 2026-07-11).
31
+ SUMMARY_HEADERS = { 'apollographql-client-name' => 'oracle' }.freeze
32
+
33
+ def initialize(access_token)
34
+ @request = Request.new(access_token)
35
+ end
36
+
37
+ def devices
38
+ @request.get(DEVICES_PATH, host: :dms, params: DEVICES_PARAMS)
39
+ end
40
+
41
+ def library(limit: LIBRARY_MAX_LIMIT)
42
+ validate_page_param!('limit', limit, min: 1, max: LIBRARY_MAX_LIMIT)
43
+
44
+ @request.graphql(LIBRARY_OPERATION, { 'categories' => LIBRARY_CATEGORIES, 'limit' => limit }, LIBRARY_HASH)
45
+ end
46
+
47
+ def purchased_games(size: 200, start: 0)
48
+ validate_page_param!('size', size, min: 1)
49
+ validate_page_param!('start', start, min: 0)
50
+ variables = PURCHASED_VARIABLES.merge('size' => size, 'start' => start)
51
+ @request.graphql(PURCHASED_OPERATION, variables, PURCHASED_HASH)
52
+ end
53
+
54
+ def summary
55
+ @request.graphql(SUMMARY_OPERATION, {}, SUMMARY_HASH, host: :web, headers: SUMMARY_HEADERS)
56
+ end
57
+ end
58
+ end
59
+ end
@@ -11,7 +11,12 @@ module PSN
11
11
  # for an authorization code and then exchanging that code for a token.
12
12
  class Auth
13
13
  AUTH_URL = 'https://ca.account.sony.com/api/authz/v3/'
14
- BASIC_TOKEN = ENV.fetch('PSN_BASIC_TOKEN', nil)
14
+ # The PlayStation Android app's public OAuth client, the same for every user (see
15
+ # docs/andshrew/APIv2.md). PSN_CLIENT_ID and PSN_BASIC_TOKEN override them.
16
+ DEFAULT_CLIENT_ID = '09515159-7237-4370-9b40-3806e67c0891'
17
+ # Base64 of "<DEFAULT_CLIENT_ID>:<client secret>".
18
+ DEFAULT_BASIC_TOKEN = 'MDk1MTUxNTktNzIzNy00MzcwLTliNDAtMzgwNmU2N2MwODkxOnVjUGprYTV0bnRCMktxc1A='
19
+ BASIC_TOKEN = ENV.fetch('PSN_BASIC_TOKEN', DEFAULT_BASIC_TOKEN)
15
20
 
16
21
  class << self
17
22
  def authenticate
@@ -100,7 +105,7 @@ module PSN
100
105
  end
101
106
 
102
107
  def client
103
- @client ||= OAuth2::Client.new(ENV.fetch('PSN_CLIENT_ID', nil), '', site: AUTH_URL)
108
+ @client ||= OAuth2::Client.new(ENV.fetch('PSN_CLIENT_ID', DEFAULT_CLIENT_ID), '', site: AUTH_URL)
104
109
  end
105
110
 
106
111
  def auth_url
@@ -0,0 +1,17 @@
1
+ # frozen_string_literal: true
2
+
3
+ module PSN
4
+ module Client
5
+ # Argument checks shared by the paginated Users and Account calls
6
+ module Pagination
7
+ private
8
+
9
+ def validate_page_param!(name, value, min:, max: nil)
10
+ return if value.is_a?(Integer) && value >= min && (max.nil? || value <= max)
11
+
12
+ range = max ? "between #{min} and #{max}" : "at least #{min}"
13
+ raise ArgumentError, "#{name} must be an Integer #{range}, got #{value.inspect}"
14
+ end
15
+ end
16
+ end
17
+ end
@@ -2,39 +2,113 @@
2
2
 
3
3
  require 'net/http'
4
4
  require 'json'
5
+ require_relative 'version'
5
6
 
6
7
  module PSN
7
8
  module Client
8
9
  # Handles HTTP requests to the PSN API
9
10
  class Request
10
- BASE_URL = 'https://m.np.playstation.com/api'
11
+ HOSTS = {
12
+ mobile: 'https://m.np.playstation.com/api',
13
+ community: 'https://us-prof.np.community.playstation.net',
14
+ dms: 'https://dms.api.playstation.com',
15
+ web: 'https://web.np.playstation.com/api'
16
+ }.freeze
17
+ BASE_URL = HOSTS[:mobile]
18
+ GRAPHQL_PATH = '/graphql/v1/op'
19
+ PRIVACY_PATTERN = /access control|privacy/i
20
+ # Sony's search backend answers HTTP 200 with "Internal server error" when the
21
+ # User-Agent is Net::HTTP's default "Ruby" (verified live 2026-11-22), so every
22
+ # request identifies the gem instead.
23
+ USER_AGENT = "psn-client/#{VERSION}".freeze
11
24
 
12
25
  def initialize(access_token)
13
26
  @access_token = access_token
14
27
  end
15
28
 
16
- def get(path)
17
- uri = URI("#{BASE_URL}#{path}")
29
+ def get(path, host: :mobile, params: {}, headers: {})
30
+ uri = build_uri(host, path, params)
18
31
 
32
+ perform(uri, authorize(Net::HTTP::Get.new(uri), headers))
33
+ end
34
+
35
+ def post(path, body, host: :mobile, headers: {})
36
+ uri = build_uri(host, path, {})
37
+ request = authorize(Net::HTTP::Post.new(uri), headers)
38
+ request['Content-Type'] = 'application/json'
39
+ request.body = JSON.generate(body)
40
+
41
+ perform(uri, request)
42
+ end
43
+
44
+ def graphql(operation_name, variables, sha256_hash, host: :mobile, headers: {})
45
+ params = {
46
+ 'operationName' => operation_name,
47
+ 'variables' => JSON.generate(variables),
48
+ 'extensions' => JSON.generate('persistedQuery' => { 'version' => 1, 'sha256Hash' => sha256_hash })
49
+ }
50
+ result = get(GRAPHQL_PATH, host: host, params: params,
51
+ headers: { 'Apollo-Require-Preflight' => 'true' }.merge(headers))
52
+ raise_graphql_errors(result)
53
+ result
54
+ end
55
+
56
+ private
57
+
58
+ def authorize(request, headers)
59
+ request['Authorization'] = "Bearer #{@access_token}"
60
+ request['User-Agent'] = USER_AGENT
61
+ headers.each { |name, value| request[name] = value }
62
+ request
63
+ end
64
+
65
+ def raise_graphql_errors(result)
66
+ errors = result['errors'] if result.is_a?(Hash)
67
+ return unless errors.is_a?(Array) && !errors.empty?
68
+
69
+ messages = errors.filter_map { |error| error.is_a?(Hash) ? error['message'] : error.to_s }
70
+ raise Error, "PSN GraphQL error: #{messages.join('; ')}"
71
+ end
72
+
73
+ def build_uri(host, path, params)
74
+ url = "#{HOSTS.fetch(host)}#{path}"
75
+ unless params.empty?
76
+ separator = url.include?('?') ? '&' : '?'
77
+ url = "#{url}#{separator}#{URI.encode_www_form(params)}"
78
+ end
79
+ URI(url)
80
+ end
81
+
82
+ def perform(uri, http_request)
19
83
  response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: true) do |http|
20
- request = Net::HTTP::Get.new(uri)
21
- request['Authorization'] = "Bearer #{@access_token}"
22
- http.request(request)
84
+ http.request(http_request)
23
85
  end
24
86
 
25
87
  parse_response(response)
26
88
  end
27
89
 
28
- private
29
-
30
90
  def parse_response(response)
31
91
  case response
32
92
  when Net::HTTPSuccess
33
93
  JSON.parse(response.body)
34
94
  else
35
- raise Error, "Request failed: #{response.code} #{response.message} - #{response.body}"
95
+ message = "Request failed: #{response.code} #{response.message} - #{response.body}"
96
+ raise PrivacyError, message if privacy_error?(response)
97
+
98
+ raise Error, message
36
99
  end
37
100
  end
101
+
102
+ def privacy_error?(response)
103
+ return false unless response.code == '403'
104
+
105
+ body = JSON.parse(response.body)
106
+ error = body['error'] if body.is_a?(Hash)
107
+ error = error['message'] if error.is_a?(Hash)
108
+ error.is_a?(String) && error.match?(PRIVACY_PATTERN)
109
+ rescue JSON::ParserError, TypeError
110
+ false
111
+ end
38
112
  end
39
113
  end
40
114
  end
@@ -0,0 +1,79 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative 'pagination'
4
+ require_relative 'request'
5
+
6
+ module PSN
7
+ module Client
8
+ # Handles user and account lookups: search, profiles and played games
9
+ class Users
10
+ include Pagination
11
+
12
+ # Paths and quirks below were verified against the live API on 2026-11-22.
13
+ # Player search is the PlayStation App's persisted GraphQL "context" search. The
14
+ # older REST /search/v1/universalSearch POST is blocked at Sony's edge (Akamai
15
+ # 403 HTML, verified 2026-11-22). The query needs the app's client-name header
16
+ # and a displayTitleLocale variable. It returns the first page of results only.
17
+ SEARCH_OPERATION = 'metGetContextSearchResults'
18
+ SEARCH_HASH = 'ac5fb2b82c4d086ca0d272fba34418ab327a7762dd2cd620e63f175bbc5aff10'
19
+ SEARCH_CONTEXT = 'MobileUniversalSearchSocial'
20
+ SEARCH_LOCALE = 'en-US'
21
+ SEARCH_HEADERS = { 'apollographql-client-name' => 'PlayStationApp-Android' }.freeze
22
+ PROFILE2_PATH = '/userProfile/v1/users/%s/profile2'
23
+ PROFILE2_FIELDS = 'npId,onlineId,accountId,avatarUrls,plus,aboutMe,languagesUsed,' \
24
+ 'trophySummary(@default,level,progress,earnedTrophies),' \
25
+ 'isOfficiallyVerified,primaryOnlineStatus,' \
26
+ 'presences(@default,@titleInfo,platform,lastOnlineDate)'
27
+ # The internal profiles endpoint rejects "me" as a path account ID (HTTP 400).
28
+ PROFILE_BY_ACCOUNT_PATH = '/userProfile/v1/internal/users/%s/profiles'
29
+ PLAYED_GAMES_PATH = '/gamelist/v2/users/%s/titles'
30
+ # A limit of 201 returns HTTP 400.
31
+ PLAYED_GAMES_MAX_LIMIT = 200
32
+ USER_ID_PATTERN = /\A(me|\d+)\z/
33
+ ONLINE_ID_PATTERN = /\A[a-zA-Z0-9_-]{3,16}\z/
34
+
35
+ def initialize(access_token)
36
+ @request = Request.new(access_token)
37
+ end
38
+
39
+ def search(term)
40
+ variables = { 'searchTerm' => term, 'searchContext' => SEARCH_CONTEXT, 'displayTitleLocale' => SEARCH_LOCALE }
41
+ @request.graphql(SEARCH_OPERATION, variables, SEARCH_HASH, headers: SEARCH_HEADERS)
42
+ end
43
+
44
+ # Exact lookup via the profile, which carries the numeric account ID. Search is
45
+ # not used: it is fuzzy, and it leaves the authenticated account out of results.
46
+ def account_id(online_id)
47
+ id = profile(online_id: online_id)&.dig('accountId').to_s
48
+ raise Error, "no PSN account found for #{online_id.inspect}" if id.empty?
49
+
50
+ id
51
+ end
52
+
53
+ def profile(online_id:)
54
+ unless online_id.is_a?(String) && ONLINE_ID_PATTERN.match?(online_id)
55
+ raise ArgumentError, "invalid PSN online ID: #{online_id.inspect}"
56
+ end
57
+
58
+ response = @request.get(format(PROFILE2_PATH, online_id), host: :community,
59
+ params: { 'fields' => PROFILE2_FIELDS })
60
+ response['profile']
61
+ end
62
+
63
+ def profile_by_account_id(account_id:)
64
+ raise ArgumentError, "invalid PSN account ID: #{account_id.inspect}" unless account_id.to_s.match?(/\A\d+\z/)
65
+
66
+ @request.get(format(PROFILE_BY_ACCOUNT_PATH, account_id))
67
+ end
68
+
69
+ def played_games(user_id: 'me', limit: PLAYED_GAMES_MAX_LIMIT, offset: 0)
70
+ raise ArgumentError, "invalid PSN user ID: #{user_id.inspect}" unless user_id.to_s.match?(USER_ID_PATTERN)
71
+
72
+ validate_page_param!('limit', limit, min: 1, max: PLAYED_GAMES_MAX_LIMIT)
73
+ validate_page_param!('offset', offset, min: 0)
74
+
75
+ @request.get(format(PLAYED_GAMES_PATH, user_id), params: { 'limit' => limit, 'offset' => offset })
76
+ end
77
+ end
78
+ end
79
+ end
@@ -2,6 +2,6 @@
2
2
 
3
3
  module PSN
4
4
  module Client
5
- VERSION = '0.1.0'
5
+ VERSION = '0.2.0'
6
6
  end
7
7
  end
data/lib/psn/client.rb CHANGED
@@ -1,8 +1,11 @@
1
1
  # frozen_string_literal: true
2
2
 
3
+ require_relative 'client/account'
3
4
  require_relative 'client/auth'
5
+ require_relative 'client/pagination'
4
6
  require_relative 'client/request'
5
7
  require_relative 'client/trophies'
8
+ require_relative 'client/users'
6
9
  require_relative 'client/version'
7
10
  require_relative 'logger'
8
11
  require 'net/http'
@@ -10,6 +13,7 @@ require 'net/http'
10
13
  module PSN
11
14
  module Client
12
15
  class Error < StandardError; end
16
+ class PrivacyError < Error; end
13
17
  # Your code goes here...
14
18
  end
15
19
  end
@@ -0,0 +1,28 @@
1
+ module PSN
2
+ module Client
3
+ class Account
4
+ include Pagination
5
+
6
+ DEVICES_PATH: String
7
+ DEVICES_PARAMS: Hash[String, String]
8
+ LIBRARY_OPERATION: String
9
+ LIBRARY_HASH: String
10
+ LIBRARY_CATEGORIES: String
11
+ LIBRARY_MAX_LIMIT: Integer
12
+ PURCHASED_OPERATION: String
13
+ PURCHASED_HASH: String
14
+ PURCHASED_VARIABLES: Hash[String, untyped]
15
+ SUMMARY_OPERATION: String
16
+ SUMMARY_HASH: String
17
+ SUMMARY_HEADERS: Hash[String, String]
18
+
19
+ @request: Request
20
+
21
+ def initialize: (String access_token) -> void
22
+ def devices: () -> untyped
23
+ def library: (?limit: Integer) -> untyped
24
+ def purchased_games: (?size: Integer, ?start: Integer) -> untyped
25
+ def summary: () -> untyped
26
+ end
27
+ end
28
+ end
@@ -2,7 +2,9 @@ module PSN
2
2
  module Client
3
3
  class Auth
4
4
  AUTH_URL: String
5
- BASIC_TOKEN: String?
5
+ DEFAULT_CLIENT_ID: String
6
+ DEFAULT_BASIC_TOKEN: String
7
+ BASIC_TOKEN: String
6
8
 
7
9
  def self.authenticate: () -> String
8
10
  def authenticate: () -> String
@@ -0,0 +1,9 @@
1
+ module PSN
2
+ module Client
3
+ module Pagination
4
+ private
5
+
6
+ def validate_page_param!: (String name, untyped value, min: Integer, ?max: Integer?) -> void
7
+ end
8
+ end
9
+ end
@@ -1,14 +1,25 @@
1
1
  module PSN
2
2
  module Client
3
3
  class Request
4
+ HOSTS: Hash[Symbol, String]
4
5
  BASE_URL: String
6
+ GRAPHQL_PATH: String
7
+ PRIVACY_PATTERN: Regexp
8
+ USER_AGENT: String
5
9
 
6
10
  def initialize: (String access_token) -> void
7
- def get: (String path) -> untyped
11
+ def get: (String path, ?host: Symbol, ?params: Hash[untyped, untyped], ?headers: Hash[String, String]) -> untyped
12
+ def post: (String path, untyped body, ?host: Symbol, ?headers: Hash[String, String]) -> untyped
13
+ def graphql: (String operation_name, Hash[untyped, untyped] variables, String sha256_hash, ?host: Symbol, ?headers: Hash[String, String]) -> untyped
8
14
 
9
15
  private
10
16
 
17
+ def authorize: (Net::HTTPRequest request, Hash[String, String] headers) -> Net::HTTPRequest
18
+ def raise_graphql_errors: (untyped result) -> void
19
+ def build_uri: (Symbol host, String path, Hash[untyped, untyped] params) -> URI::Generic
20
+ def perform: (URI::Generic uri, Net::HTTPRequest http_request) -> untyped
11
21
  def parse_response: (Net::HTTPResponse response) -> untyped
22
+ def privacy_error?: (Net::HTTPResponse response) -> bool
12
23
  end
13
24
  end
14
25
  end
@@ -0,0 +1,29 @@
1
+ module PSN
2
+ module Client
3
+ class Users
4
+ include Pagination
5
+
6
+ SEARCH_OPERATION: String
7
+ SEARCH_HASH: String
8
+ SEARCH_CONTEXT: String
9
+ SEARCH_LOCALE: String
10
+ SEARCH_HEADERS: Hash[String, String]
11
+ PROFILE2_PATH: String
12
+ PROFILE2_FIELDS: String
13
+ PROFILE_BY_ACCOUNT_PATH: String
14
+ PLAYED_GAMES_PATH: String
15
+ PLAYED_GAMES_MAX_LIMIT: Integer
16
+ USER_ID_PATTERN: Regexp
17
+ ONLINE_ID_PATTERN: Regexp
18
+
19
+ @request: Request
20
+
21
+ def initialize: (String access_token) -> void
22
+ def search: (String term) -> untyped
23
+ def account_id: (String online_id) -> String
24
+ def profile: (online_id: String) -> Hash[String, untyped]?
25
+ def profile_by_account_id: (account_id: String) -> untyped
26
+ def played_games: (?user_id: String, ?limit: Integer, ?offset: Integer) -> untyped
27
+ end
28
+ end
29
+ end
data/sig/psn/client.rbs CHANGED
@@ -1,6 +1,13 @@
1
1
  module PSN
2
2
  module Client
3
3
  VERSION: String
4
+
5
+ class Error < StandardError
6
+ end
7
+
8
+ class PrivacyError < Error
9
+ end
10
+
4
11
  # See the writing guide of rbs: https://github.com/ruby/rbs#guides
5
12
  end
6
13
  end
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: psn-client
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.1.0
4
+ version: 0.2.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - Matthew Jacques
@@ -32,28 +32,34 @@ extensions: []
32
32
  extra_rdoc_files: []
33
33
  files:
34
34
  - CHANGELOG.md
35
+ - CLAUDE.md
35
36
  - CODE_OF_CONDUCT.md
36
37
  - LICENSE.txt
37
38
  - README.md
38
39
  - docs/andshrew/APIv2.md
39
40
  - docs/andshrew/LICENSE
40
41
  - lib/psn/client.rb
42
+ - lib/psn/client/account.rb
41
43
  - lib/psn/client/auth.rb
44
+ - lib/psn/client/pagination.rb
42
45
  - lib/psn/client/request.rb
43
46
  - lib/psn/client/trophies.rb
47
+ - lib/psn/client/users.rb
44
48
  - lib/psn/client/version.rb
45
49
  - lib/psn/logger.rb
46
50
  - sig/psn/client.rbs
51
+ - sig/psn/client/account.rbs
47
52
  - sig/psn/client/auth.rbs
53
+ - sig/psn/client/pagination.rbs
48
54
  - sig/psn/client/request.rbs
49
55
  - sig/psn/client/trophies.rbs
56
+ - sig/psn/client/users.rbs
50
57
  - sig/psn/logger.rbs
51
58
  homepage: https://github.com/MattyJacques/psn-client
52
59
  licenses:
53
60
  - MIT
54
61
  metadata:
55
62
  homepage_uri: https://github.com/MattyJacques/psn-client
56
- source_code_uri: https://github.com/MattyJacques/psn-client
57
63
  changelog_uri: https://github.com/MattyJacques/psn-client/blob/main/CHANGELOG.md
58
64
  rubygems_mfa_required: 'true'
59
65
  rdoc_options: []
@@ -70,7 +76,7 @@ required_rubygems_version: !ruby/object:Gem::Requirement
70
76
  - !ruby/object:Gem::Version
71
77
  version: '0'
72
78
  requirements: []
73
- rubygems_version: 4.0.3
79
+ rubygems_version: 3.6.9
74
80
  specification_version: 4
75
81
  summary: A Ruby client for the PlayStation Network API
76
82
  test_files: []